##// END OF EJS Templates
Ensures that ipython-complete is called....
Pete Aykroyd -
Show More
@@ -1,495 +1,503 b''
1 ;;; ipython.el --- Adds support for IPython to python-mode.el
1 ;;; ipython.el --- Adds support for IPython to python-mode.el
2
2
3 ;; Copyright (C) 2002, 2003, 2004, 2005 Alexander Schmolck
3 ;; Copyright (C) 2002, 2003, 2004, 2005 Alexander Schmolck
4 ;; Author: Alexander Schmolck
4 ;; Author: Alexander Schmolck
5 ;; Keywords: ipython python languages oop
5 ;; Keywords: ipython python languages oop
6 ;; URL: http://ipython.org
6 ;; URL: http://ipython.org
7 ;; Compatibility: Emacs21, XEmacs21
7 ;; Compatibility: Emacs21, XEmacs21
8 ;; FIXME: #$@! INPUT RING
8 ;; FIXME: #$@! INPUT RING
9 (defconst ipython-version "0.11"
9 (defconst ipython-version "0.11"
10 "Tied to IPython main version number.")
10 "Tied to IPython main version number.")
11
11
12 ;;; Commentary
12 ;;; Commentary
13 ;; This library makes all the functionality python-mode has when running with
13 ;; This library makes all the functionality python-mode has when running with
14 ;; the normal python-interpreter available for ipython, too. It also enables a
14 ;; the normal python-interpreter available for ipython, too. It also enables a
15 ;; persistent py-shell command history across sessions (if you exit python
15 ;; persistent py-shell command history across sessions (if you exit python
16 ;; with C-d in py-shell) and defines the command `ipython-to-doctest', which
16 ;; with C-d in py-shell) and defines the command `ipython-to-doctest', which
17 ;; can be used to convert bits of a ipython session into something that can be
17 ;; can be used to convert bits of a ipython session into something that can be
18 ;; used for doctests. To install, put this file somewhere in your emacs
18 ;; used for doctests. To install, put this file somewhere in your emacs
19 ;; `load-path' [1] and add the following line to your ~/.emacs file (the first
19 ;; `load-path' [1] and add the following line to your ~/.emacs file (the first
20 ;; line only needed if the default (``"ipython"``) is wrong)::
20 ;; line only needed if the default (``"ipython"``) is wrong)::
21 ;;
21 ;;
22 ;; (setq ipython-command "/SOME-PATH/ipython")
22 ;; (setq ipython-command "/SOME-PATH/ipython")
23 ;; (require 'ipython)
23 ;; (require 'ipython)
24 ;;
24 ;;
25 ;; Ipython will be set as the default python shell, but only if the ipython
25 ;; Ipython will be set as the default python shell, but only if the ipython
26 ;; executable is in the path. For ipython sessions autocompletion with <tab>
26 ;; executable is in the path. For ipython sessions autocompletion with <tab>
27 ;; is also enabled (experimental feature!). Please also note that all the
27 ;; is also enabled (experimental feature!). Please also note that all the
28 ;; terminal functions in py-shell are handled by emacs's comint, **not** by
28 ;; terminal functions in py-shell are handled by emacs's comint, **not** by
29 ;; (i)python, so importing readline etc. will have 0 effect.
29 ;; (i)python, so importing readline etc. will have 0 effect.
30 ;;
30 ;;
31 ;; To start an interactive ipython session run `py-shell' with ``M-x py-shell``
31 ;; To start an interactive ipython session run `py-shell' with ``M-x py-shell``
32 ;; (or the default keybinding ``C-c C-!``).
32 ;; (or the default keybinding ``C-c C-!``).
33 ;;
33 ;;
34 ;; You can customize the arguments passed to the IPython instance at startup by
34 ;; You can customize the arguments passed to the IPython instance at startup by
35 ;; setting the ``py-python-command-args`` variable. For example, to start
35 ;; setting the ``py-python-command-args`` variable. For example, to start
36 ;; always in ``pylab`` mode with hardcoded light-background colors, you can
36 ;; always in ``pylab`` mode with hardcoded light-background colors, you can
37 ;; use::
37 ;; use::
38 ;;
38 ;;
39 ;; (setq py-python-command-args '("--pylab" "--colors=LightBG"))
39 ;; (setq py-python-command-args '("--pylab" "--colors=LightBG"))
40 ;;
40 ;;
41 ;;
41 ;;
42 ;; NOTE: This mode is currently somewhat alpha and although I hope that it
42 ;; NOTE: This mode is currently somewhat alpha and although I hope that it
43 ;; will work fine for most cases, doing certain things (like the
43 ;; will work fine for most cases, doing certain things (like the
44 ;; autocompletion and a decent scheme to switch between python interpreters)
44 ;; autocompletion and a decent scheme to switch between python interpreters)
45 ;; properly will also require changes to ipython that will likely have to wait
45 ;; properly will also require changes to ipython that will likely have to wait
46 ;; for a larger rewrite scheduled some time in the future.
46 ;; for a larger rewrite scheduled some time in the future.
47 ;;
47 ;;
48 ;;
48 ;;
49 ;; Further note that I don't know whether this runs under windows or not and
49 ;; Further note that I don't know whether this runs under windows or not and
50 ;; that if it doesn't I can't really help much, not being afflicted myself.
50 ;; that if it doesn't I can't really help much, not being afflicted myself.
51 ;;
51 ;;
52 ;;
52 ;;
53 ;; Hints for effective usage
53 ;; Hints for effective usage
54 ;; -------------------------
54 ;; -------------------------
55 ;;
55 ;;
56 ;; - IMO the best feature by far of the ipython/emacs combo is how much easier
56 ;; - IMO the best feature by far of the ipython/emacs combo is how much easier
57 ;; it makes it to find and fix bugs thanks to the ``%pdb on or %debug``/
57 ;; it makes it to find and fix bugs thanks to the ``%pdb on or %debug``/
58 ;; pdbtrack combo. Try it: first in the ipython to shell do ``%pdb on`` then
58 ;; pdbtrack combo. Try it: first in the ipython to shell do ``%pdb on`` then
59 ;; do something that will raise an exception (FIXME nice example), or type
59 ;; do something that will raise an exception (FIXME nice example), or type
60 ;; ``%debug`` after the exception has been raised. YOu'll be amazed at how
60 ;; ``%debug`` after the exception has been raised. YOu'll be amazed at how
61 ;; easy it is to inspect the live objects in each stack frames and to jump to
61 ;; easy it is to inspect the live objects in each stack frames and to jump to
62 ;; the corresponding sourcecode locations as you walk up and down the stack
62 ;; the corresponding sourcecode locations as you walk up and down the stack
63 ;; trace (even without ``%pdb on`` you can always use ``C-c -``
63 ;; trace (even without ``%pdb on`` you can always use ``C-c -``
64 ;; (`py-up-exception') to jump to the corresponding source code locations).
64 ;; (`py-up-exception') to jump to the corresponding source code locations).
65 ;;
65 ;;
66 ;; - emacs gives you much more powerful commandline editing and output searching
66 ;; - emacs gives you much more powerful commandline editing and output searching
67 ;; capabilities than ipython-standalone -- isearch is your friend if you
67 ;; capabilities than ipython-standalone -- isearch is your friend if you
68 ;; quickly want to print 'DEBUG ...' to stdout out etc.
68 ;; quickly want to print 'DEBUG ...' to stdout out etc.
69 ;;
69 ;;
70 ;; - This is not really specific to ipython, but for more convenient history
70 ;; - This is not really specific to ipython, but for more convenient history
71 ;; access you might want to add something like the following to *the beggining*
71 ;; access you might want to add something like the following to *the beggining*
72 ;; of your ``.emacs`` (if you want behavior that's more similar to stand-alone
72 ;; of your ``.emacs`` (if you want behavior that's more similar to stand-alone
73 ;; ipython, you can change ``meta p`` etc. for ``control p``)::
73 ;; ipython, you can change ``meta p`` etc. for ``control p``)::
74 ;;
74 ;;
75 ;; (require 'comint)
75 ;; (require 'comint)
76 ;; (define-key comint-mode-map [(meta p)]
76 ;; (define-key comint-mode-map [(meta p)]
77 ;; 'comint-previous-matching-input-from-input)
77 ;; 'comint-previous-matching-input-from-input)
78 ;; (define-key comint-mode-map [(meta n)]
78 ;; (define-key comint-mode-map [(meta n)]
79 ;; 'comint-next-matching-input-from-input)
79 ;; 'comint-next-matching-input-from-input)
80 ;; (define-key comint-mode-map [(control meta n)]
80 ;; (define-key comint-mode-map [(control meta n)]
81 ;; 'comint-next-input)
81 ;; 'comint-next-input)
82 ;; (define-key comint-mode-map [(control meta p)]
82 ;; (define-key comint-mode-map [(control meta p)]
83 ;; 'comint-previous-input)
83 ;; 'comint-previous-input)
84 ;;
84 ;;
85 ;; - Be aware that if you customize py-python-command previously, this value
85 ;; - Be aware that if you customize py-python-command previously, this value
86 ;; will override what ipython.el does (because loading the customization
86 ;; will override what ipython.el does (because loading the customization
87 ;; variables comes later).
87 ;; variables comes later).
88 ;;
88 ;;
89 ;; Please send comments and feedback to the ipython-list
89 ;; Please send comments and feedback to the ipython-list
90 ;; (<ipython-user@scipy.org>) where I (a.s.) or someone else will try to
90 ;; (<ipython-user@scipy.org>) where I (a.s.) or someone else will try to
91 ;; answer them (it helps if you specify your emacs version, OS etc;
91 ;; answer them (it helps if you specify your emacs version, OS etc;
92 ;; familiarity with <http://www.catb.org/~esr/faqs/smart-questions.html> might
92 ;; familiarity with <http://www.catb.org/~esr/faqs/smart-questions.html> might
93 ;; speed up things further).
93 ;; speed up things further).
94 ;;
94 ;;
95 ;; Footnotes:
95 ;; Footnotes:
96 ;;
96 ;;
97 ;; [1] If you don't know what `load-path' is, C-h v load-path will tell
97 ;; [1] If you don't know what `load-path' is, C-h v load-path will tell
98 ;; you; if required you can also add a new directory. So assuming that
98 ;; you; if required you can also add a new directory. So assuming that
99 ;; ipython.el resides in ~/el/, put this in your emacs:
99 ;; ipython.el resides in ~/el/, put this in your emacs:
100 ;;
100 ;;
101 ;;
101 ;;
102 ;; (add-to-list 'load-path "~/el")
102 ;; (add-to-list 'load-path "~/el")
103 ;; (setq ipython-command "/some-path/ipython")
103 ;; (setq ipython-command "/some-path/ipython")
104 ;; (require 'ipython)
104 ;; (require 'ipython)
105 ;;
105 ;;
106 ;;
106 ;;
107 ;;
107 ;;
108 ;;
108 ;;
109 ;; TODO:
109 ;; TODO:
110 ;; - do autocompletion properly
110 ;; - do autocompletion properly
111 ;; - implement a proper switching between python interpreters
111 ;; - implement a proper switching between python interpreters
112 ;;
112 ;;
113 ;; BUGS:
113 ;; BUGS:
114 ;; - neither::
114 ;; - neither::
115 ;;
115 ;;
116 ;; (py-shell "-c print 'FOOBAR'")
116 ;; (py-shell "-c print 'FOOBAR'")
117 ;;
117 ;;
118 ;; nor::
118 ;; nor::
119 ;;
119 ;;
120 ;; (let ((py-python-command-args (append py-python-command-args
120 ;; (let ((py-python-command-args (append py-python-command-args
121 ;; '("-c" "print 'FOOBAR'"))))
121 ;; '("-c" "print 'FOOBAR'"))))
122 ;; (py-shell))
122 ;; (py-shell))
123 ;;
123 ;;
124 ;; seem to print anything as they should
124 ;; seem to print anything as they should
125 ;;
125 ;;
126 ;; - look into init priority issues with `py-python-command' (if it's set
126 ;; - look into init priority issues with `py-python-command' (if it's set
127 ;; via custom)
127 ;; via custom)
128
128
129
129
130 ;;; Code
130 ;;; Code
131 (require 'cl)
131 (require 'cl)
132 (require 'shell)
132 (require 'shell)
133 (require 'executable)
133 (require 'executable)
134 (require 'ansi-color)
134 (require 'ansi-color)
135
135
136 (defcustom ipython-command "ipython"
136 (defcustom ipython-command "ipython"
137 "*Shell command used to start ipython."
137 "*Shell command used to start ipython."
138 :type 'string
138 :type 'string
139 :group 'python)
139 :group 'python)
140
140
141 ;; Users can set this to nil
141 ;; Users can set this to nil
142 (defvar py-shell-initial-switch-buffers t
142 (defvar py-shell-initial-switch-buffers t
143 "If nil, don't switch to the *Python* buffer on the first call to
143 "If nil, don't switch to the *Python* buffer on the first call to
144 `py-shell'.")
144 `py-shell'.")
145
145
146 (defvar ipython-backup-of-py-python-command nil
146 (defvar ipython-backup-of-py-python-command nil
147 "HACK")
147 "HACK")
148
148
149
149
150 (defvar ipython-de-input-prompt-regexp "\\(?:
150 (defvar ipython-de-input-prompt-regexp "\\(?:
151 In \\[[0-9]+\\]: *.*
151 In \\[[0-9]+\\]: *.*
152 ----+> \\(.*
152 ----+> \\(.*
153 \\)[\n]?\\)\\|\\(?:
153 \\)[\n]?\\)\\|\\(?:
154 In \\[[0-9]+\\]: *\\(.*
154 In \\[[0-9]+\\]: *\\(.*
155 \\)\\)\\|^[ ]\\{3\\}[.]\\{3,\\}: *\\(.*
155 \\)\\)\\|^[ ]\\{3\\}[.]\\{3,\\}: *\\(.*
156 \\)"
156 \\)"
157 "A regular expression to match the IPython input prompt and the python
157 "A regular expression to match the IPython input prompt and the python
158 command after it. The first match group is for a command that is rewritten,
158 command after it. The first match group is for a command that is rewritten,
159 the second for a 'normal' command, and the third for a multiline command.")
159 the second for a 'normal' command, and the third for a multiline command.")
160 (defvar ipython-de-output-prompt-regexp "^Out\\[[0-9]+\\]: "
160 (defvar ipython-de-output-prompt-regexp "^Out\\[[0-9]+\\]: "
161 "A regular expression to match the output prompt of IPython.")
161 "A regular expression to match the output prompt of IPython.")
162
162
163
163
164 (if (not (executable-find ipython-command))
164 (if (not (executable-find ipython-command))
165 (message (format "Can't find executable %s - ipython.el *NOT* activated!!!"
165 (message (format "Can't find executable %s - ipython.el *NOT* activated!!!"
166 ipython-command))
166 ipython-command))
167 ;; XXX load python-mode, so that we can screw around with its variables
167 ;; XXX load python-mode, so that we can screw around with its variables
168 ;; this has the disadvantage that python-mode is loaded even if no
168 ;; this has the disadvantage that python-mode is loaded even if no
169 ;; python-file is ever edited etc. but it means that `py-shell' works
169 ;; python-file is ever edited etc. but it means that `py-shell' works
170 ;; without loading a python-file first. Obviously screwing around with
170 ;; without loading a python-file first. Obviously screwing around with
171 ;; python-mode's variables like this is a mess, but well.
171 ;; python-mode's variables like this is a mess, but well.
172 (require 'python-mode)
172 (require 'python-mode)
173 ;; turn on ansi colors for ipython and activate completion
173 ;; turn on ansi colors for ipython and activate completion
174 (defun ipython-shell-hook ()
174 (defun ipython-shell-hook ()
175 ;; the following is to synchronize dir-changes
175 ;; the following is to synchronize dir-changes
176 (make-local-variable 'shell-dirstack)
176 (make-local-variable 'shell-dirstack)
177 (setq shell-dirstack nil)
177 (setq shell-dirstack nil)
178 (make-local-variable 'shell-last-dir)
178 (make-local-variable 'shell-last-dir)
179 (setq shell-last-dir nil)
179 (setq shell-last-dir nil)
180 (make-local-variable 'shell-dirtrackp)
180 (make-local-variable 'shell-dirtrackp)
181 (setq shell-dirtrackp t)
181 (setq shell-dirtrackp t)
182 (add-hook 'comint-input-filter-functions 'shell-directory-tracker nil t)
182 (add-hook 'comint-input-filter-functions 'shell-directory-tracker nil t)
183
183
184 (ansi-color-for-comint-mode-on)
184 (ansi-color-for-comint-mode-on)
185 (define-key py-shell-map [tab] 'ipython-complete)
185 (define-key py-shell-map [tab] 'ipython-complete)
186 ;; Add this so that tab-completion works both in X11 frames and inside
186 ;; Add this so that tab-completion works both in X11 frames and inside
187 ;; terminals (such as when emacs is called with -nw).
187 ;; terminals (such as when emacs is called with -nw).
188 (define-key py-shell-map "\t" 'ipython-complete)
188 (define-key py-shell-map "\t" 'ipython-complete)
189 ;;XXX this is really just a cheap hack, it only completes symbols in the
189 ;;XXX this is really just a cheap hack, it only completes symbols in the
190 ;;interactive session -- useful nonetheless.
190 ;;interactive session -- useful nonetheless.
191 (define-key py-mode-map [(meta tab)] 'ipython-complete)
191 (define-key py-mode-map [(meta tab)] 'ipython-complete)
192
192
193 )
193 )
194 (add-hook 'py-shell-hook 'ipython-shell-hook)
194 (add-hook 'py-shell-hook 'ipython-shell-hook)
195 ;; Regular expression that describes tracebacks for IPython in context and
195 ;; Regular expression that describes tracebacks for IPython in context and
196 ;; verbose mode.
196 ;; verbose mode.
197
197
198 ;;Adapt python-mode settings for ipython.
198 ;;Adapt python-mode settings for ipython.
199 ;; (this works for %xmode 'verbose' or 'context')
199 ;; (this works for %xmode 'verbose' or 'context')
200
200
201 ;; XXX putative regexps for syntax errors; unfortunately the
201 ;; XXX putative regexps for syntax errors; unfortunately the
202 ;; current python-mode traceback-line-re scheme is too primitive,
202 ;; current python-mode traceback-line-re scheme is too primitive,
203 ;; so it's either matching syntax errors, *or* everything else
203 ;; so it's either matching syntax errors, *or* everything else
204 ;; (XXX: should ask Fernando for a change)
204 ;; (XXX: should ask Fernando for a change)
205 ;;"^ File \"\\(.*?\\)\", line \\([0-9]+\\).*\n.*\n.*\nSyntaxError:"
205 ;;"^ File \"\\(.*?\\)\", line \\([0-9]+\\).*\n.*\n.*\nSyntaxError:"
206 ;;^ File \"\\(.*?\\)\", line \\([0-9]+\\)"
206 ;;^ File \"\\(.*?\\)\", line \\([0-9]+\\)"
207
207
208 (setq py-traceback-line-re
208 (setq py-traceback-line-re
209 "\\(^[^\t >].+?\\.py\\).*\n +[0-9]+[^\00]*?\n-+> \\([0-9]+\\)+")
209 "\\(^[^\t >].+?\\.py\\).*\n +[0-9]+[^\00]*?\n-+> \\([0-9]+\\)+")
210
210
211
211
212 ;; Recognize the ipython pdb, whose prompt is 'ipdb>' or 'ipydb>'
212 ;; Recognize the ipython pdb, whose prompt is 'ipdb>' or 'ipydb>'
213 ;;instead of '(Pdb)'
213 ;;instead of '(Pdb)'
214 (setq py-pdbtrack-input-prompt "\n[(<]*[Ii]?[Pp]y?db[>)]+ ")
214 (setq py-pdbtrack-input-prompt "\n[(<]*[Ii]?[Pp]y?db[>)]+ ")
215 (setq pydb-pydbtrack-input-prompt "\n[(]*ipydb[>)]+ ")
215 (setq pydb-pydbtrack-input-prompt "\n[(]*ipydb[>)]+ ")
216
216
217 (setq py-shell-input-prompt-1-regexp "^In \\[[0-9]+\\]: *"
217 (setq py-shell-input-prompt-1-regexp "^In \\[[0-9]+\\]: *"
218 py-shell-input-prompt-2-regexp "^ [.][.][.]+: *" )
218 py-shell-input-prompt-2-regexp "^ [.][.][.]+: *" )
219 ;; select a suitable color-scheme
219 ;; select a suitable color-scheme
220 (unless (delq nil
220 (unless (delq nil
221 (mapcar (lambda (x) (eq (string-match "^--colors=*" x) 0))
221 (mapcar (lambda (x) (eq (string-match "^--colors=*" x) 0))
222 py-python-command-args))
222 py-python-command-args))
223 (push (format "--colors=%s"
223 (push (format "--colors=%s"
224 (cond
224 (cond
225 ((eq frame-background-mode 'dark)
225 ((eq frame-background-mode 'dark)
226 "Linux")
226 "Linux")
227 ((eq frame-background-mode 'light)
227 ((eq frame-background-mode 'light)
228 "LightBG")
228 "LightBG")
229 (t ; default (backg-mode isn't always set by XEmacs)
229 (t ; default (backg-mode isn't always set by XEmacs)
230 "LightBG")))
230 "LightBG")))
231 py-python-command-args))
231 py-python-command-args))
232 (when (boundp 'py-python-command)
232 (when (boundp 'py-python-command)
233 (unless (equal ipython-backup-of-py-python-command py-python-command)
233 (unless (equal ipython-backup-of-py-python-command py-python-command)
234 (setq ipython-backup-of-py-python-command py-python-command)))
234 (setq ipython-backup-of-py-python-command py-python-command)))
235 (setq py-python-command ipython-command)
235 (setq py-python-command ipython-command)
236 (when (boundp 'py-shell-name)
236 (when (boundp 'py-shell-name)
237 (setq py-shell-name ipython-command)))
237 (setq py-shell-name ipython-command)))
238
238
239 ;; MODIFY py-shell so that it loads the editing history
239 ;; MODIFY py-shell so that it loads the editing history
240 (defadvice py-shell (around py-shell-with-history)
240 (defadvice py-shell (around py-shell-with-history)
241 "Add persistent command-history support (in
241 "Add persistent command-history support (in
242 $PYTHONHISTORY (or \"~/.ipython/history\", if we use IPython)). Also, if
242 $PYTHONHISTORY (or \"~/.ipython/history\", if we use IPython)). Also, if
243 `py-shell-initial-switch-buffers' is nil, it only switches to *Python* if that
243 `py-shell-initial-switch-buffers' is nil, it only switches to *Python* if that
244 buffer already exists."
244 buffer already exists."
245 (if (comint-check-proc "*Python*")
245 (if (comint-check-proc "*Python*")
246 ad-do-it
246 ad-do-it
247 (setq comint-input-ring-file-name
247 (setq comint-input-ring-file-name
248 (if (string-equal py-python-command ipython-command)
248 (if (string-equal py-python-command ipython-command)
249 (concat (or (getenv "IPYTHONDIR") "~/.ipython") "/history")
249 (concat (or (getenv "IPYTHONDIR") "~/.ipython") "/history")
250 (or (getenv "PYTHONHISTORY") "~/.python-history.py")))
250 (or (getenv "PYTHONHISTORY") "~/.python-history.py")))
251 (comint-read-input-ring t)
251 (comint-read-input-ring t)
252 (let ((buf (current-buffer)))
252 (let ((buf (current-buffer)))
253 ad-do-it
253 ad-do-it
254 (unless py-shell-initial-switch-buffers
254 (unless py-shell-initial-switch-buffers
255 (switch-to-buffer-other-window buf)))))
255 (switch-to-buffer-other-window buf)))))
256 (ad-activate 'py-shell)
256 (ad-activate 'py-shell)
257 ;; (defadvice py-execute-region (before py-execute-buffer-ensure-process)
257 ;; (defadvice py-execute-region (before py-execute-buffer-ensure-process)
258 ;; "HACK: test that ipython is already running before executing something.
258 ;; "HACK: test that ipython is already running before executing something.
259 ;; Doing this properly seems not worth the bother (unless people actually
259 ;; Doing this properly seems not worth the bother (unless people actually
260 ;; request it)."
260 ;; request it)."
261 ;; (unless (comint-check-proc "*Python*")
261 ;; (unless (comint-check-proc "*Python*")
262 ;; (error "Sorry you have to first do M-x py-shell to send something to ipython.")))
262 ;; (error "Sorry you have to first do M-x py-shell to send something to ipython.")))
263 ;; (ad-activate 'py-execute-region)
263 ;; (ad-activate 'py-execute-region)
264
264
265 (defadvice py-execute-region (around py-execute-buffer-ensure-process)
265 (defadvice py-execute-region (around py-execute-buffer-ensure-process)
266 "HACK: if `py-shell' is not active or ASYNC is explicitly desired, fall back
266 "HACK: if `py-shell' is not active or ASYNC is explicitly desired, fall back
267 to python instead of ipython."
267 to python instead of ipython."
268 (let ((py-which-shell (if (and (comint-check-proc "*Python*") (not async))
268 (let ((py-which-shell (if (and (comint-check-proc "*Python*") (not async))
269 py-python-command
269 py-python-command
270 ipython-backup-of-py-python-command)))
270 ipython-backup-of-py-python-command)))
271 ad-do-it))
271 ad-do-it))
272 (ad-activate 'py-execute-region)
272 (ad-activate 'py-execute-region)
273
273
274 (defun ipython-to-doctest (start end)
274 (defun ipython-to-doctest (start end)
275 "Transform a cut-and-pasted bit from an IPython session into something that
275 "Transform a cut-and-pasted bit from an IPython session into something that
276 looks like it came from a normal interactive python session, so that it can
276 looks like it came from a normal interactive python session, so that it can
277 be used in doctests. Example:
277 be used in doctests. Example:
278
278
279
279
280 In [1]: import sys
280 In [1]: import sys
281
281
282 In [2]: sys.stdout.write 'Hi!\n'
282 In [2]: sys.stdout.write 'Hi!\n'
283 ------> sys.stdout.write ('Hi!\n')
283 ------> sys.stdout.write ('Hi!\n')
284 Hi!
284 Hi!
285
285
286 In [3]: 3 + 4
286 In [3]: 3 + 4
287 Out[3]: 7
287 Out[3]: 7
288
288
289 gets converted to:
289 gets converted to:
290
290
291 >>> import sys
291 >>> import sys
292 >>> sys.stdout.write ('Hi!\n')
292 >>> sys.stdout.write ('Hi!\n')
293 Hi!
293 Hi!
294 >>> 3 + 4
294 >>> 3 + 4
295 7
295 7
296
296
297 "
297 "
298 (interactive "*r\n")
298 (interactive "*r\n")
299 ;(message (format "###DEBUG s:%de:%d" start end))
299 ;(message (format "###DEBUG s:%de:%d" start end))
300 (save-excursion
300 (save-excursion
301 (save-match-data
301 (save-match-data
302 ;; replace ``In [3]: bla`` with ``>>> bla`` and
302 ;; replace ``In [3]: bla`` with ``>>> bla`` and
303 ;; ``... : bla`` with ``... bla``
303 ;; ``... : bla`` with ``... bla``
304 (goto-char start)
304 (goto-char start)
305 (while (re-search-forward ipython-de-input-prompt-regexp end t)
305 (while (re-search-forward ipython-de-input-prompt-regexp end t)
306 ;(message "finding 1")
306 ;(message "finding 1")
307 (cond ((match-string 3) ;continued
307 (cond ((match-string 3) ;continued
308 (replace-match "... \\3" t nil))
308 (replace-match "... \\3" t nil))
309 (t
309 (t
310 (replace-match ">>> \\1\\2" t nil))))
310 (replace-match ">>> \\1\\2" t nil))))
311 ;; replace ``
311 ;; replace ``
312 (goto-char start)
312 (goto-char start)
313 (while (re-search-forward ipython-de-output-prompt-regexp end t)
313 (while (re-search-forward ipython-de-output-prompt-regexp end t)
314 (replace-match "" t nil)))))
314 (replace-match "" t nil)))))
315
315
316 (defvar ipython-completion-command-string
316 (defvar ipython-completion-command-string
317 "print(';'.join(get_ipython().Completer.all_completions('%s'))) #PYTHON-MODE SILENT\n"
317 "print(';'.join(get_ipython().Completer.all_completions('%s'))) #PYTHON-MODE SILENT\n"
318 "The string send to ipython to query for all possible completions")
318 "The string send to ipython to query for all possible completions")
319
319
320
320
321 ;; xemacs doesn't have `comint-preoutput-filter-functions' so we'll try the
321 ;; xemacs doesn't have `comint-preoutput-filter-functions' so we'll try the
322 ;; following wonderful hack to work around this case
322 ;; following wonderful hack to work around this case
323 (if (featurep 'xemacs)
323 (if (featurep 'xemacs)
324 ;;xemacs
324 ;;xemacs
325 (defun ipython-complete ()
325 (defun ipython-complete ()
326 "Try to complete the python symbol before point. Only knows about the stuff
326 "Try to complete the python symbol before point. Only knows about the stuff
327 in the current *Python* session."
327 in the current *Python* session."
328 (interactive)
328 (interactive)
329 (let* ((ugly-return nil)
329 (let* ((ugly-return nil)
330 (sep ";")
330 (sep ";")
331 (python-process (or (get-buffer-process (current-buffer))
331 (python-process (or (get-buffer-process (current-buffer))
332 ;XXX hack for .py buffers
332 ;XXX hack for .py buffers
333 (get-process py-which-bufname)))
333 (get-process py-which-bufname)))
334 ;; XXX currently we go backwards to find the beginning of an
334 ;; XXX currently we go backwards to find the beginning of an
335 ;; expression part; a more powerful approach in the future might be
335 ;; expression part; a more powerful approach in the future might be
336 ;; to let ipython have the complete line, so that context can be used
336 ;; to let ipython have the complete line, so that context can be used
337 ;; to do things like filename completion etc.
337 ;; to do things like filename completion etc.
338 (beg (save-excursion (skip-chars-backward "a-z0-9A-Z_." (point-at-bol))
338 (beg (save-excursion (skip-chars-backward "a-z0-9A-Z_." (point-at-bol))
339 (point)))
339 (point)))
340 (end (point))
340 (end (point))
341 (pattern (buffer-substring-no-properties beg end))
341 (pattern (buffer-substring-no-properties beg end))
342 (completions nil)
342 (completions nil)
343 (completion-table nil)
343 (completion-table nil)
344 completion
344 completion
345 (comint-output-filter-functions
345 (comint-output-filter-functions
346 (append comint-output-filter-functions
346 (append comint-output-filter-functions
347 '(ansi-color-filter-apply
347 '(ansi-color-filter-apply
348 (lambda (string)
348 (lambda (string)
349 ;(message (format "DEBUG filtering: %s" string))
349 ;(message (format "DEBUG filtering: %s" string))
350 (setq ugly-return (concat ugly-return string))
350 (setq ugly-return (concat ugly-return string))
351 (delete-region comint-last-output-start
351 (delete-region comint-last-output-start
352 (process-mark (get-buffer-process (current-buffer)))))))))
352 (process-mark (get-buffer-process (current-buffer)))))))))
353 ;(message (format "#DEBUG pattern: '%s'" pattern))
353 ;(message (format "#DEBUG pattern: '%s'" pattern))
354 (process-send-string python-process
354 (process-send-string python-process
355 (format ipython-completion-command-string pattern))
355 (format ipython-completion-command-string pattern))
356 (accept-process-output python-process)
356 (accept-process-output python-process)
357
357
358 ;(message (format "DEBUG return: %s" ugly-return))
358 ;(message (format "DEBUG return: %s" ugly-return))
359 (setq completions
359 (setq completions
360 (split-string (substring ugly-return 0 (position ?\n ugly-return)) sep))
360 (split-string (substring ugly-return 0 (position ?\n ugly-return)) sep))
361 (setq completion-table (loop for str in completions
361 (setq completion-table (loop for str in completions
362 collect (list str nil)))
362 collect (list str nil)))
363 (setq completion (try-completion pattern completion-table))
363 (setq completion (try-completion pattern completion-table))
364 (cond ((eq completion t))
364 (cond ((eq completion t))
365 ((null completion)
365 ((null completion)
366 (message "Can't find completion for \"%s\"" pattern)
366 (message "Can't find completion for \"%s\"" pattern)
367 (ding))
367 (ding))
368 ((not (string= pattern completion))
368 ((not (string= pattern completion))
369 (delete-region beg end)
369 (delete-region beg end)
370 (insert completion))
370 (insert completion))
371 (t
371 (t
372 (message "Making completion list...")
372 (message "Making completion list...")
373 (with-output-to-temp-buffer "*Python Completions*"
373 (with-output-to-temp-buffer "*Python Completions*"
374 (display-completion-list (all-completions pattern completion-table)))
374 (display-completion-list (all-completions pattern completion-table)))
375 (message "Making completion list...%s" "done")))))
375 (message "Making completion list...%s" "done")))))
376 ;; emacs
376 ;; emacs
377 (defun ipython-complete ()
377 (defun ipython-complete ()
378 "Try to complete the python symbol before point. Only knows about the stuff
378 "Try to complete the python symbol before point. Only knows about the stuff
379 in the current *Python* session."
379 in the current *Python* session."
380 (interactive)
380 (interactive)
381 (let* ((ugly-return nil)
381 (let* ((ugly-return nil)
382 (sep ";")
382 (sep ";")
383 (python-process (or (get-buffer-process (current-buffer))
383 (python-process (or (get-buffer-process (current-buffer))
384 ;XXX hack for .py buffers
384 ;XXX hack for .py buffers
385 (get-process py-which-bufname)))
385 (get-process py-which-bufname)))
386 ;; XXX currently we go backwards to find the beginning of an
386 ;; XXX currently we go backwards to find the beginning of an
387 ;; expression part; a more powerful approach in the future might be
387 ;; expression part; a more powerful approach in the future might be
388 ;; to let ipython have the complete line, so that context can be used
388 ;; to let ipython have the complete line, so that context can be used
389 ;; to do things like filename completion etc.
389 ;; to do things like filename completion etc.
390 (beg (save-excursion (skip-chars-backward "a-z0-9A-Z_./" (point-at-bol))
390 (beg (save-excursion (skip-chars-backward "a-z0-9A-Z_./" (point-at-bol))
391 (point)))
391 (point)))
392 (end (point))
392 (end (point))
393 (pattern (buffer-substring-no-properties beg end))
393 (pattern (buffer-substring-no-properties beg end))
394 (completions nil)
394 (completions nil)
395 (completion-table nil)
395 (completion-table nil)
396 completion
396 completion
397 (comint-preoutput-filter-functions
397 (comint-preoutput-filter-functions
398 (append comint-preoutput-filter-functions
398 (append comint-preoutput-filter-functions
399 '(ansi-color-filter-apply
399 '(ansi-color-filter-apply
400 (lambda (string)
400 (lambda (string)
401 (setq ugly-return (concat ugly-return string))
401 (setq ugly-return (concat ugly-return string))
402 "")))))
402 "")))))
403 (process-send-string python-process
403 (process-send-string python-process
404 (format ipython-completion-command-string pattern))
404 (format ipython-completion-command-string pattern))
405 (accept-process-output python-process)
405 (accept-process-output python-process)
406 (setq completions
406 (setq completions
407 (split-string (substring ugly-return 0 (position ?\n ugly-return)) sep))
407 (split-string (substring ugly-return 0 (position ?\n ugly-return)) sep))
408 ;(message (format "DEBUG completions: %S" completions))
408 ;(message (format "DEBUG completions: %S" completions))
409 (setq completion-table (loop for str in completions
409 (setq completion-table (loop for str in completions
410 collect (list str nil)))
410 collect (list str nil)))
411 (setq completion (try-completion pattern completion-table))
411 (setq completion (try-completion pattern completion-table))
412 (cond ((eq completion t))
412 (cond ((eq completion t))
413 ((null completion)
413 ((null completion)
414 (message "Can't find completion for \"%s\"" pattern)
414 (message "Can't find completion for \"%s\"" pattern)
415 (ding))
415 (ding))
416 ((not (string= pattern completion))
416 ((not (string= pattern completion))
417 (delete-region beg end)
417 (delete-region beg end)
418 (insert completion))
418 (insert completion))
419 (t
419 (t
420 (message "Making completion list...")
420 (message "Making completion list...")
421 (with-output-to-temp-buffer "*IPython Completions*"
421 (with-output-to-temp-buffer "*IPython Completions*"
422 (display-completion-list (all-completions pattern completion-table)))
422 (display-completion-list (all-completions pattern completion-table)))
423 (message "Making completion list...%s" "done")))))
423 (message "Making completion list...%s" "done")))))
424 )
424 )
425
425
426 ;;; if python-mode's keybinding for the tab key wins then py-shell-complete is called
427 ;;; instead of ipython-complete which result in hanging emacs since there is no shell
428 ;;; process for python-mode to communicate with
429 (defadvice py-shell-complete
430 (around avoid-py-shell-complete activate)
431 (ipython-complete))
432
433
426 ;;; autoindent support: patch sent in by Jin Liu <m.liu.jin@gmail.com>,
434 ;;; autoindent support: patch sent in by Jin Liu <m.liu.jin@gmail.com>,
427 ;;; originally written by doxgen@newsmth.net
435 ;;; originally written by doxgen@newsmth.net
428 ;;; Minor modifications by fperez for xemacs compatibility.
436 ;;; Minor modifications by fperez for xemacs compatibility.
429
437
430 (defvar ipython-autoindent t
438 (defvar ipython-autoindent t
431 "If non-nil, enable autoindent for IPython shell through python-mode.")
439 "If non-nil, enable autoindent for IPython shell through python-mode.")
432
440
433 (defvar ipython-indenting-buffer-name "*IPython Indentation Calculation*"
441 (defvar ipython-indenting-buffer-name "*IPython Indentation Calculation*"
434 "Temporary buffer for indenting multiline statement.")
442 "Temporary buffer for indenting multiline statement.")
435
443
436 (defun ipython-get-indenting-buffer ()
444 (defun ipython-get-indenting-buffer ()
437 "Return a temporary buffer set in python-mode. Create one if necessary."
445 "Return a temporary buffer set in python-mode. Create one if necessary."
438 (let ((buf (get-buffer-create ipython-indenting-buffer-name)))
446 (let ((buf (get-buffer-create ipython-indenting-buffer-name)))
439 (set-buffer buf)
447 (set-buffer buf)
440 (unless (eq major-mode 'python-mode)
448 (unless (eq major-mode 'python-mode)
441 (python-mode))
449 (python-mode))
442 buf))
450 buf))
443
451
444 (defvar ipython-indentation-string nil
452 (defvar ipython-indentation-string nil
445 "Indentation for the next line in a multiline statement.")
453 "Indentation for the next line in a multiline statement.")
446
454
447 (defun ipython-send-and-indent ()
455 (defun ipython-send-and-indent ()
448 "Send the current line to IPython, and calculate the indentation for
456 "Send the current line to IPython, and calculate the indentation for
449 the next line."
457 the next line."
450 (interactive)
458 (interactive)
451 (if ipython-autoindent
459 (if ipython-autoindent
452 (let ((line (buffer-substring (point-at-bol) (point)))
460 (let ((line (buffer-substring (point-at-bol) (point)))
453 (after-prompt1)
461 (after-prompt1)
454 (after-prompt2))
462 (after-prompt2))
455 (save-excursion
463 (save-excursion
456 (comint-bol t)
464 (comint-bol t)
457 (if (looking-at py-shell-input-prompt-1-regexp)
465 (if (looking-at py-shell-input-prompt-1-regexp)
458 (setq after-prompt1 t)
466 (setq after-prompt1 t)
459 (setq after-prompt2 (looking-at py-shell-input-prompt-2-regexp)))
467 (setq after-prompt2 (looking-at py-shell-input-prompt-2-regexp)))
460 (with-current-buffer (ipython-get-indenting-buffer)
468 (with-current-buffer (ipython-get-indenting-buffer)
461 (when after-prompt1
469 (when after-prompt1
462 (erase-buffer))
470 (erase-buffer))
463 (when (or after-prompt1 after-prompt2)
471 (when (or after-prompt1 after-prompt2)
464 (delete-region (point-at-bol) (point))
472 (delete-region (point-at-bol) (point))
465 (insert line)
473 (insert line)
466 (newline-and-indent))))))
474 (newline-and-indent))))))
467 ;; send input line to ipython interpreter
475 ;; send input line to ipython interpreter
468 (comint-send-input))
476 (comint-send-input))
469
477
470 (defun ipython-indentation-hook (string)
478 (defun ipython-indentation-hook (string)
471 "Insert indentation string if py-shell-input-prompt-2-regexp
479 "Insert indentation string if py-shell-input-prompt-2-regexp
472 matches last process output."
480 matches last process output."
473 (let* ((start-marker (or comint-last-output-start
481 (let* ((start-marker (or comint-last-output-start
474 (point-min-marker)))
482 (point-min-marker)))
475 (end-marker (process-mark (get-buffer-process (current-buffer))))
483 (end-marker (process-mark (get-buffer-process (current-buffer))))
476 (text (ansi-color-filter-apply (buffer-substring start-marker end-marker))))
484 (text (ansi-color-filter-apply (buffer-substring start-marker end-marker))))
477 ;; XXX if `text' matches both pattern, it MUST be the last prompt-2
485 ;; XXX if `text' matches both pattern, it MUST be the last prompt-2
478 (when (and (string-match py-shell-input-prompt-2-regexp text)
486 (when (and (string-match py-shell-input-prompt-2-regexp text)
479 (not (string-match "\n$" text)))
487 (not (string-match "\n$" text)))
480 (with-current-buffer (ipython-get-indenting-buffer)
488 (with-current-buffer (ipython-get-indenting-buffer)
481 (setq ipython-indentation-string
489 (setq ipython-indentation-string
482 (buffer-substring (point-at-bol) (point))))
490 (buffer-substring (point-at-bol) (point))))
483 (goto-char end-marker)
491 (goto-char end-marker)
484 (insert ipython-indentation-string)
492 (insert ipython-indentation-string)
485 (setq ipython-indentation-string nil))))
493 (setq ipython-indentation-string nil))))
486
494
487 (add-hook 'py-shell-hook
495 (add-hook 'py-shell-hook
488 (lambda ()
496 (lambda ()
489 (add-hook 'comint-output-filter-functions
497 (add-hook 'comint-output-filter-functions
490 'ipython-indentation-hook)))
498 'ipython-indentation-hook)))
491
499
492 (define-key py-shell-map (kbd "RET") 'ipython-send-and-indent)
500 (define-key py-shell-map (kbd "RET") 'ipython-send-and-indent)
493 ;;; / end autoindent support
501 ;;; / end autoindent support
494
502
495 (provide 'ipython)
503 (provide 'ipython)
General Comments 0
You need to be logged in to leave comments. Login now