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