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