##// END OF EJS Templates
Undeprecate autoindent...
Matthias Bussonnier -
Show More

The requested changes are too big and content was truncated. Show full diff

@@ -0,0 +1,2 b''
1 The autoindent feature that was deprecated in 5.x was re-enabled and
2 un-deprecated in :ghpull:`11257`
1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
@@ -1,207 +1,205 b''
1 """Extra magics for terminal use."""
1 """Extra magics for terminal use."""
2
2
3 # Copyright (c) IPython Development Team.
3 # Copyright (c) IPython Development Team.
4 # Distributed under the terms of the Modified BSD License.
4 # Distributed under the terms of the Modified BSD License.
5
5
6
6
7 from logging import error
7 from logging import error
8 import os
8 import os
9 import sys
9 import sys
10
10
11 from IPython.core.error import TryNext, UsageError
11 from IPython.core.error import TryNext, UsageError
12 from IPython.core.inputsplitter import IPythonInputSplitter
12 from IPython.core.inputsplitter import IPythonInputSplitter
13 from IPython.core.magic import Magics, magics_class, line_magic
13 from IPython.core.magic import Magics, magics_class, line_magic
14 from IPython.lib.clipboard import ClipboardEmpty
14 from IPython.lib.clipboard import ClipboardEmpty
15 from IPython.utils.text import SList, strip_email_quotes
15 from IPython.utils.text import SList, strip_email_quotes
16 from IPython.utils import py3compat
16 from IPython.utils import py3compat
17
17
18 def get_pasted_lines(sentinel, l_input=py3compat.input, quiet=False):
18 def get_pasted_lines(sentinel, l_input=py3compat.input, quiet=False):
19 """ Yield pasted lines until the user enters the given sentinel value.
19 """ Yield pasted lines until the user enters the given sentinel value.
20 """
20 """
21 if not quiet:
21 if not quiet:
22 print("Pasting code; enter '%s' alone on the line to stop or use Ctrl-D." \
22 print("Pasting code; enter '%s' alone on the line to stop or use Ctrl-D." \
23 % sentinel)
23 % sentinel)
24 prompt = ":"
24 prompt = ":"
25 else:
25 else:
26 prompt = ""
26 prompt = ""
27 while True:
27 while True:
28 try:
28 try:
29 l = l_input(prompt)
29 l = l_input(prompt)
30 if l == sentinel:
30 if l == sentinel:
31 return
31 return
32 else:
32 else:
33 yield l
33 yield l
34 except EOFError:
34 except EOFError:
35 print('<EOF>')
35 print('<EOF>')
36 return
36 return
37
37
38
38
39 @magics_class
39 @magics_class
40 class TerminalMagics(Magics):
40 class TerminalMagics(Magics):
41 def __init__(self, shell):
41 def __init__(self, shell):
42 super(TerminalMagics, self).__init__(shell)
42 super(TerminalMagics, self).__init__(shell)
43 self.input_splitter = IPythonInputSplitter()
43 self.input_splitter = IPythonInputSplitter()
44
44
45 def store_or_execute(self, block, name):
45 def store_or_execute(self, block, name):
46 """ Execute a block, or store it in a variable, per the user's request.
46 """ Execute a block, or store it in a variable, per the user's request.
47 """
47 """
48 if name:
48 if name:
49 # If storing it for further editing
49 # If storing it for further editing
50 self.shell.user_ns[name] = SList(block.splitlines())
50 self.shell.user_ns[name] = SList(block.splitlines())
51 print("Block assigned to '%s'" % name)
51 print("Block assigned to '%s'" % name)
52 else:
52 else:
53 b = self.preclean_input(block)
53 b = self.preclean_input(block)
54 self.shell.user_ns['pasted_block'] = b
54 self.shell.user_ns['pasted_block'] = b
55 self.shell.using_paste_magics = True
55 self.shell.using_paste_magics = True
56 try:
56 try:
57 self.shell.run_cell(b)
57 self.shell.run_cell(b)
58 finally:
58 finally:
59 self.shell.using_paste_magics = False
59 self.shell.using_paste_magics = False
60
60
61 def preclean_input(self, block):
61 def preclean_input(self, block):
62 lines = block.splitlines()
62 lines = block.splitlines()
63 while lines and not lines[0].strip():
63 while lines and not lines[0].strip():
64 lines = lines[1:]
64 lines = lines[1:]
65 return strip_email_quotes('\n'.join(lines))
65 return strip_email_quotes('\n'.join(lines))
66
66
67 def rerun_pasted(self, name='pasted_block'):
67 def rerun_pasted(self, name='pasted_block'):
68 """ Rerun a previously pasted command.
68 """ Rerun a previously pasted command.
69 """
69 """
70 b = self.shell.user_ns.get(name)
70 b = self.shell.user_ns.get(name)
71
71
72 # Sanity checks
72 # Sanity checks
73 if b is None:
73 if b is None:
74 raise UsageError('No previous pasted block available')
74 raise UsageError('No previous pasted block available')
75 if not isinstance(b, str):
75 if not isinstance(b, str):
76 raise UsageError(
76 raise UsageError(
77 "Variable 'pasted_block' is not a string, can't execute")
77 "Variable 'pasted_block' is not a string, can't execute")
78
78
79 print("Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)))
79 print("Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)))
80 self.shell.run_cell(b)
80 self.shell.run_cell(b)
81
81
82 @line_magic
82 @line_magic
83 def autoindent(self, parameter_s = ''):
83 def autoindent(self, parameter_s = ''):
84 """Toggle autoindent on/off (deprecated)"""
84 """Toggle autoindent on/off (deprecated)"""
85 print("%autoindent is deprecated since IPython 5: you can now paste "
86 "multiple lines without turning autoindentation off.")
87 self.shell.set_autoindent()
85 self.shell.set_autoindent()
88 print("Automatic indentation is:",['OFF','ON'][self.shell.autoindent])
86 print("Automatic indentation is:",['OFF','ON'][self.shell.autoindent])
89
87
90 @line_magic
88 @line_magic
91 def cpaste(self, parameter_s=''):
89 def cpaste(self, parameter_s=''):
92 """Paste & execute a pre-formatted code block from clipboard.
90 """Paste & execute a pre-formatted code block from clipboard.
93
91
94 You must terminate the block with '--' (two minus-signs) or Ctrl-D
92 You must terminate the block with '--' (two minus-signs) or Ctrl-D
95 alone on the line. You can also provide your own sentinel with '%paste
93 alone on the line. You can also provide your own sentinel with '%paste
96 -s %%' ('%%' is the new sentinel for this operation).
94 -s %%' ('%%' is the new sentinel for this operation).
97
95
98 The block is dedented prior to execution to enable execution of method
96 The block is dedented prior to execution to enable execution of method
99 definitions. '>' and '+' characters at the beginning of a line are
97 definitions. '>' and '+' characters at the beginning of a line are
100 ignored, to allow pasting directly from e-mails, diff files and
98 ignored, to allow pasting directly from e-mails, diff files and
101 doctests (the '...' continuation prompt is also stripped). The
99 doctests (the '...' continuation prompt is also stripped). The
102 executed block is also assigned to variable named 'pasted_block' for
100 executed block is also assigned to variable named 'pasted_block' for
103 later editing with '%edit pasted_block'.
101 later editing with '%edit pasted_block'.
104
102
105 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
103 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
106 This assigns the pasted block to variable 'foo' as string, without
104 This assigns the pasted block to variable 'foo' as string, without
107 dedenting or executing it (preceding >>> and + is still stripped)
105 dedenting or executing it (preceding >>> and + is still stripped)
108
106
109 '%cpaste -r' re-executes the block previously entered by cpaste.
107 '%cpaste -r' re-executes the block previously entered by cpaste.
110 '%cpaste -q' suppresses any additional output messages.
108 '%cpaste -q' suppresses any additional output messages.
111
109
112 Do not be alarmed by garbled output on Windows (it's a readline bug).
110 Do not be alarmed by garbled output on Windows (it's a readline bug).
113 Just press enter and type -- (and press enter again) and the block
111 Just press enter and type -- (and press enter again) and the block
114 will be what was just pasted.
112 will be what was just pasted.
115
113
116 IPython statements (magics, shell escapes) are not supported (yet).
114 IPython statements (magics, shell escapes) are not supported (yet).
117
115
118 See also
116 See also
119 --------
117 --------
120 paste: automatically pull code from clipboard.
118 paste: automatically pull code from clipboard.
121
119
122 Examples
120 Examples
123 --------
121 --------
124 ::
122 ::
125
123
126 In [8]: %cpaste
124 In [8]: %cpaste
127 Pasting code; enter '--' alone on the line to stop.
125 Pasting code; enter '--' alone on the line to stop.
128 :>>> a = ["world!", "Hello"]
126 :>>> a = ["world!", "Hello"]
129 :>>> print " ".join(sorted(a))
127 :>>> print " ".join(sorted(a))
130 :--
128 :--
131 Hello world!
129 Hello world!
132 """
130 """
133 opts, name = self.parse_options(parameter_s, 'rqs:', mode='string')
131 opts, name = self.parse_options(parameter_s, 'rqs:', mode='string')
134 if 'r' in opts:
132 if 'r' in opts:
135 self.rerun_pasted()
133 self.rerun_pasted()
136 return
134 return
137
135
138 quiet = ('q' in opts)
136 quiet = ('q' in opts)
139
137
140 sentinel = opts.get('s', u'--')
138 sentinel = opts.get('s', u'--')
141 block = '\n'.join(get_pasted_lines(sentinel, quiet=quiet))
139 block = '\n'.join(get_pasted_lines(sentinel, quiet=quiet))
142 self.store_or_execute(block, name)
140 self.store_or_execute(block, name)
143
141
144 @line_magic
142 @line_magic
145 def paste(self, parameter_s=''):
143 def paste(self, parameter_s=''):
146 """Paste & execute a pre-formatted code block from clipboard.
144 """Paste & execute a pre-formatted code block from clipboard.
147
145
148 The text is pulled directly from the clipboard without user
146 The text is pulled directly from the clipboard without user
149 intervention and printed back on the screen before execution (unless
147 intervention and printed back on the screen before execution (unless
150 the -q flag is given to force quiet mode).
148 the -q flag is given to force quiet mode).
151
149
152 The block is dedented prior to execution to enable execution of method
150 The block is dedented prior to execution to enable execution of method
153 definitions. '>' and '+' characters at the beginning of a line are
151 definitions. '>' and '+' characters at the beginning of a line are
154 ignored, to allow pasting directly from e-mails, diff files and
152 ignored, to allow pasting directly from e-mails, diff files and
155 doctests (the '...' continuation prompt is also stripped). The
153 doctests (the '...' continuation prompt is also stripped). The
156 executed block is also assigned to variable named 'pasted_block' for
154 executed block is also assigned to variable named 'pasted_block' for
157 later editing with '%edit pasted_block'.
155 later editing with '%edit pasted_block'.
158
156
159 You can also pass a variable name as an argument, e.g. '%paste foo'.
157 You can also pass a variable name as an argument, e.g. '%paste foo'.
160 This assigns the pasted block to variable 'foo' as string, without
158 This assigns the pasted block to variable 'foo' as string, without
161 executing it (preceding >>> and + is still stripped).
159 executing it (preceding >>> and + is still stripped).
162
160
163 Options:
161 Options:
164
162
165 -r: re-executes the block previously entered by cpaste.
163 -r: re-executes the block previously entered by cpaste.
166
164
167 -q: quiet mode: do not echo the pasted text back to the terminal.
165 -q: quiet mode: do not echo the pasted text back to the terminal.
168
166
169 IPython statements (magics, shell escapes) are not supported (yet).
167 IPython statements (magics, shell escapes) are not supported (yet).
170
168
171 See also
169 See also
172 --------
170 --------
173 cpaste: manually paste code into terminal until you mark its end.
171 cpaste: manually paste code into terminal until you mark its end.
174 """
172 """
175 opts, name = self.parse_options(parameter_s, 'rq', mode='string')
173 opts, name = self.parse_options(parameter_s, 'rq', mode='string')
176 if 'r' in opts:
174 if 'r' in opts:
177 self.rerun_pasted()
175 self.rerun_pasted()
178 return
176 return
179 try:
177 try:
180 block = self.shell.hooks.clipboard_get()
178 block = self.shell.hooks.clipboard_get()
181 except TryNext as clipboard_exc:
179 except TryNext as clipboard_exc:
182 message = getattr(clipboard_exc, 'args')
180 message = getattr(clipboard_exc, 'args')
183 if message:
181 if message:
184 error(message[0])
182 error(message[0])
185 else:
183 else:
186 error('Could not get text from the clipboard.')
184 error('Could not get text from the clipboard.')
187 return
185 return
188 except ClipboardEmpty:
186 except ClipboardEmpty:
189 raise UsageError("The clipboard appears to be empty")
187 raise UsageError("The clipboard appears to be empty")
190
188
191 # By default, echo back to terminal unless quiet mode is requested
189 # By default, echo back to terminal unless quiet mode is requested
192 if 'q' not in opts:
190 if 'q' not in opts:
193 write = self.shell.write
191 write = self.shell.write
194 write(self.shell.pycolorize(block))
192 write(self.shell.pycolorize(block))
195 if not block.endswith('\n'):
193 if not block.endswith('\n'):
196 write('\n')
194 write('\n')
197 write("## -- End pasted text --\n")
195 write("## -- End pasted text --\n")
198
196
199 self.store_or_execute(block, name)
197 self.store_or_execute(block, name)
200
198
201 # Class-level: add a '%cls' magic only on Windows
199 # Class-level: add a '%cls' magic only on Windows
202 if sys.platform == 'win32':
200 if sys.platform == 'win32':
203 @line_magic
201 @line_magic
204 def cls(self, s):
202 def cls(self, s):
205 """Clear screen.
203 """Clear screen.
206 """
204 """
207 os.system("cls")
205 os.system("cls")
@@ -1,244 +1,250 b''
1 """
1 """
2 Module to define and register Terminal IPython shortcuts with
2 Module to define and register Terminal IPython shortcuts with
3 :mod:`prompt_toolkit`
3 :mod:`prompt_toolkit`
4 """
4 """
5
5
6 # Copyright (c) IPython Development Team.
6 # Copyright (c) IPython Development Team.
7 # Distributed under the terms of the Modified BSD License.
7 # Distributed under the terms of the Modified BSD License.
8
8
9 import warnings
9 import warnings
10 import signal
10 import signal
11 import sys
11 import sys
12 from typing import Callable
12 from typing import Callable
13
13
14
14
15 from prompt_toolkit.application.current import get_app
15 from prompt_toolkit.application.current import get_app
16 from prompt_toolkit.enums import DEFAULT_BUFFER, SEARCH_BUFFER
16 from prompt_toolkit.enums import DEFAULT_BUFFER, SEARCH_BUFFER
17 from prompt_toolkit.filters import (has_focus, has_selection, Condition,
17 from prompt_toolkit.filters import (has_focus, has_selection, Condition,
18 vi_insert_mode, emacs_insert_mode, has_completions, vi_mode)
18 vi_insert_mode, emacs_insert_mode, has_completions, vi_mode)
19 from prompt_toolkit.key_binding.bindings.completion import display_completions_like_readline
19 from prompt_toolkit.key_binding.bindings.completion import display_completions_like_readline
20 from prompt_toolkit.key_binding import KeyBindings
20 from prompt_toolkit.key_binding import KeyBindings
21
21
22 from IPython.utils.decorators import undoc
22 from IPython.utils.decorators import undoc
23
23
24 @undoc
24 @undoc
25 @Condition
25 @Condition
26 def cursor_in_leading_ws():
26 def cursor_in_leading_ws():
27 before = get_app().current_buffer.document.current_line_before_cursor
27 before = get_app().current_buffer.document.current_line_before_cursor
28 return (not before) or before.isspace()
28 return (not before) or before.isspace()
29
29
30
30
31 def create_ipython_shortcuts(shell):
31 def create_ipython_shortcuts(shell):
32 """Set up the prompt_toolkit keyboard shortcuts for IPython"""
32 """Set up the prompt_toolkit keyboard shortcuts for IPython"""
33
33
34 kb = KeyBindings()
34 kb = KeyBindings()
35 insert_mode = vi_insert_mode | emacs_insert_mode
35 insert_mode = vi_insert_mode | emacs_insert_mode
36
36
37 if getattr(shell, 'handle_return', None):
37 if getattr(shell, 'handle_return', None):
38 return_handler = shell.handle_return(shell)
38 return_handler = shell.handle_return(shell)
39 else:
39 else:
40 return_handler = newline_or_execute_outer(shell)
40 return_handler = newline_or_execute_outer(shell)
41
41
42 kb.add('enter', filter=(has_focus(DEFAULT_BUFFER)
42 kb.add('enter', filter=(has_focus(DEFAULT_BUFFER)
43 & ~has_selection
43 & ~has_selection
44 & insert_mode
44 & insert_mode
45 ))(return_handler)
45 ))(return_handler)
46
46
47 kb.add('c-\\')(force_exit)
47 kb.add('c-\\')(force_exit)
48
48
49 kb.add('c-p', filter=(vi_insert_mode & has_focus(DEFAULT_BUFFER))
49 kb.add('c-p', filter=(vi_insert_mode & has_focus(DEFAULT_BUFFER))
50 )(previous_history_or_previous_completion)
50 )(previous_history_or_previous_completion)
51
51
52 kb.add('c-n', filter=(vi_insert_mode & has_focus(DEFAULT_BUFFER))
52 kb.add('c-n', filter=(vi_insert_mode & has_focus(DEFAULT_BUFFER))
53 )(next_history_or_next_completion)
53 )(next_history_or_next_completion)
54
54
55 kb.add('c-g', filter=(has_focus(DEFAULT_BUFFER) & has_completions)
55 kb.add('c-g', filter=(has_focus(DEFAULT_BUFFER) & has_completions)
56 )(dismiss_completion)
56 )(dismiss_completion)
57
57
58 kb.add('c-c', filter=has_focus(DEFAULT_BUFFER))(reset_buffer)
58 kb.add('c-c', filter=has_focus(DEFAULT_BUFFER))(reset_buffer)
59
59
60 kb.add('c-c', filter=has_focus(SEARCH_BUFFER))(reset_search_buffer)
60 kb.add('c-c', filter=has_focus(SEARCH_BUFFER))(reset_search_buffer)
61
61
62 supports_suspend = Condition(lambda: hasattr(signal, 'SIGTSTP'))
62 supports_suspend = Condition(lambda: hasattr(signal, 'SIGTSTP'))
63 kb.add('c-z', filter=supports_suspend)(suspend_to_bg)
63 kb.add('c-z', filter=supports_suspend)(suspend_to_bg)
64
64
65 # Ctrl+I == Tab
65 # Ctrl+I == Tab
66 kb.add('tab', filter=(has_focus(DEFAULT_BUFFER)
66 kb.add('tab', filter=(has_focus(DEFAULT_BUFFER)
67 & ~has_selection
67 & ~has_selection
68 & insert_mode
68 & insert_mode
69 & cursor_in_leading_ws
69 & cursor_in_leading_ws
70 ))(indent_buffer)
70 ))(indent_buffer)
71
71
72 kb.add('c-o', filter=(has_focus(DEFAULT_BUFFER)
72 kb.add('c-o', filter=(has_focus(DEFAULT_BUFFER)
73 & emacs_insert_mode))(newline_autoindent_outer(shell.input_splitter))
73 & emacs_insert_mode))(newline_autoindent_outer(shell.input_splitter))
74
74
75 kb.add('f2', filter=has_focus(DEFAULT_BUFFER))(open_input_in_editor)
75 kb.add('f2', filter=has_focus(DEFAULT_BUFFER))(open_input_in_editor)
76
76
77 if shell.display_completions == 'readlinelike':
77 if shell.display_completions == 'readlinelike':
78 kb.add('c-i', filter=(has_focus(DEFAULT_BUFFER)
78 kb.add('c-i', filter=(has_focus(DEFAULT_BUFFER)
79 & ~has_selection
79 & ~has_selection
80 & insert_mode
80 & insert_mode
81 & ~cursor_in_leading_ws
81 & ~cursor_in_leading_ws
82 ))(display_completions_like_readline)
82 ))(display_completions_like_readline)
83
83
84 if sys.platform == 'win32':
84 if sys.platform == 'win32':
85 kb.add('c-v', filter=(has_focus(DEFAULT_BUFFER) & ~vi_mode))(win_paste)
85 kb.add('c-v', filter=(has_focus(DEFAULT_BUFFER) & ~vi_mode))(win_paste)
86
86
87 return kb
87 return kb
88
88
89
89
90 def newline_or_execute_outer(shell):
90 def newline_or_execute_outer(shell):
91 def newline_or_execute(event):
91 def newline_or_execute(event):
92 """When the user presses return, insert a newline or execute the code."""
92 """When the user presses return, insert a newline or execute the code."""
93 b = event.current_buffer
93 b = event.current_buffer
94 d = b.document
94 d = b.document
95
95
96 if b.complete_state:
96 if b.complete_state:
97 cc = b.complete_state.current_completion
97 cc = b.complete_state.current_completion
98 if cc:
98 if cc:
99 b.apply_completion(cc)
99 b.apply_completion(cc)
100 else:
100 else:
101 b.cancel_completion()
101 b.cancel_completion()
102 return
102 return
103
103
104 # If there's only one line, treat it as if the cursor is at the end.
104 # If there's only one line, treat it as if the cursor is at the end.
105 # See https://github.com/ipython/ipython/issues/10425
105 # See https://github.com/ipython/ipython/issues/10425
106 if d.line_count == 1:
106 if d.line_count == 1:
107 check_text = d.text
107 check_text = d.text
108 else:
108 else:
109 check_text = d.text[:d.cursor_position]
109 check_text = d.text[:d.cursor_position]
110 status, indent = shell.input_splitter.check_complete(check_text + '\n')
110 status, indent = shell.input_splitter.check_complete(check_text + '\n')
111
111
112 if not (d.on_last_line or
112 if not (d.on_last_line or
113 d.cursor_position_row >= d.line_count - d.empty_line_count_at_the_end()
113 d.cursor_position_row >= d.line_count - d.empty_line_count_at_the_end()
114 ):
114 ):
115 b.insert_text('\n' + (' ' * (indent or 0)))
115 if shell.autoindent:
116 b.insert_text('\n' + (' ' * (indent or 0)))
117 else:
118 b.insert_text('\n')
116 return
119 return
117
120
118 if (status != 'incomplete') and b.accept_handler:
121 if (status != 'incomplete') and b.accept_handler:
119 b.validate_and_handle()
122 b.validate_and_handle()
120 else:
123 else:
121 b.insert_text('\n' + (' ' * (indent or 0)))
124 if shell.autoindent:
125 b.insert_text('\n' + (' ' * (indent or 0)))
126 else:
127 b.insert_text('\n')
122 return newline_or_execute
128 return newline_or_execute
123
129
124
130
125 def previous_history_or_previous_completion(event):
131 def previous_history_or_previous_completion(event):
126 """
132 """
127 Control-P in vi edit mode on readline is history next, unlike default prompt toolkit.
133 Control-P in vi edit mode on readline is history next, unlike default prompt toolkit.
128
134
129 If completer is open this still select previous completion.
135 If completer is open this still select previous completion.
130 """
136 """
131 event.current_buffer.auto_up()
137 event.current_buffer.auto_up()
132
138
133
139
134 def next_history_or_next_completion(event):
140 def next_history_or_next_completion(event):
135 """
141 """
136 Control-N in vi edit mode on readline is history previous, unlike default prompt toolkit.
142 Control-N in vi edit mode on readline is history previous, unlike default prompt toolkit.
137
143
138 If completer is open this still select next completion.
144 If completer is open this still select next completion.
139 """
145 """
140 event.current_buffer.auto_down()
146 event.current_buffer.auto_down()
141
147
142
148
143 def dismiss_completion(event):
149 def dismiss_completion(event):
144 b = event.current_buffer
150 b = event.current_buffer
145 if b.complete_state:
151 if b.complete_state:
146 b.cancel_completion()
152 b.cancel_completion()
147
153
148
154
149 def reset_buffer(event):
155 def reset_buffer(event):
150 b = event.current_buffer
156 b = event.current_buffer
151 if b.complete_state:
157 if b.complete_state:
152 b.cancel_completion()
158 b.cancel_completion()
153 else:
159 else:
154 b.reset()
160 b.reset()
155
161
156
162
157 def reset_search_buffer(event):
163 def reset_search_buffer(event):
158 if event.current_buffer.document.text:
164 if event.current_buffer.document.text:
159 event.current_buffer.reset()
165 event.current_buffer.reset()
160 else:
166 else:
161 event.app.layout.focus(DEFAULT_BUFFER)
167 event.app.layout.focus(DEFAULT_BUFFER)
162
168
163 def suspend_to_bg(event):
169 def suspend_to_bg(event):
164 event.app.suspend_to_background()
170 event.app.suspend_to_background()
165
171
166 def force_exit(event):
172 def force_exit(event):
167 """
173 """
168 Force exit (with a non-zero return value)
174 Force exit (with a non-zero return value)
169 """
175 """
170 sys.exit("Quit")
176 sys.exit("Quit")
171
177
172 def indent_buffer(event):
178 def indent_buffer(event):
173 event.current_buffer.insert_text(' ' * 4)
179 event.current_buffer.insert_text(' ' * 4)
174
180
175 @undoc
181 @undoc
176 def newline_with_copy_margin(event):
182 def newline_with_copy_margin(event):
177 """
183 """
178 DEPRECATED since IPython 6.0
184 DEPRECATED since IPython 6.0
179
185
180 See :any:`newline_autoindent_outer` for a replacement.
186 See :any:`newline_autoindent_outer` for a replacement.
181
187
182 Preserve margin and cursor position when using
188 Preserve margin and cursor position when using
183 Control-O to insert a newline in EMACS mode
189 Control-O to insert a newline in EMACS mode
184 """
190 """
185 warnings.warn("`newline_with_copy_margin(event)` is deprecated since IPython 6.0. "
191 warnings.warn("`newline_with_copy_margin(event)` is deprecated since IPython 6.0. "
186 "see `newline_autoindent_outer(shell)(event)` for a replacement.",
192 "see `newline_autoindent_outer(shell)(event)` for a replacement.",
187 DeprecationWarning, stacklevel=2)
193 DeprecationWarning, stacklevel=2)
188
194
189 b = event.current_buffer
195 b = event.current_buffer
190 cursor_start_pos = b.document.cursor_position_col
196 cursor_start_pos = b.document.cursor_position_col
191 b.newline(copy_margin=True)
197 b.newline(copy_margin=True)
192 b.cursor_up(count=1)
198 b.cursor_up(count=1)
193 cursor_end_pos = b.document.cursor_position_col
199 cursor_end_pos = b.document.cursor_position_col
194 if cursor_start_pos != cursor_end_pos:
200 if cursor_start_pos != cursor_end_pos:
195 pos_diff = cursor_start_pos - cursor_end_pos
201 pos_diff = cursor_start_pos - cursor_end_pos
196 b.cursor_right(count=pos_diff)
202 b.cursor_right(count=pos_diff)
197
203
198 def newline_autoindent_outer(inputsplitter) -> Callable[..., None]:
204 def newline_autoindent_outer(inputsplitter) -> Callable[..., None]:
199 """
205 """
200 Return a function suitable for inserting a indented newline after the cursor.
206 Return a function suitable for inserting a indented newline after the cursor.
201
207
202 Fancier version of deprecated ``newline_with_copy_margin`` which should
208 Fancier version of deprecated ``newline_with_copy_margin`` which should
203 compute the correct indentation of the inserted line. That is to say, indent
209 compute the correct indentation of the inserted line. That is to say, indent
204 by 4 extra space after a function definition, class definition, context
210 by 4 extra space after a function definition, class definition, context
205 manager... And dedent by 4 space after ``pass``, ``return``, ``raise ...``.
211 manager... And dedent by 4 space after ``pass``, ``return``, ``raise ...``.
206 """
212 """
207
213
208 def newline_autoindent(event):
214 def newline_autoindent(event):
209 """insert a newline after the cursor indented appropriately."""
215 """insert a newline after the cursor indented appropriately."""
210 b = event.current_buffer
216 b = event.current_buffer
211 d = b.document
217 d = b.document
212
218
213 if b.complete_state:
219 if b.complete_state:
214 b.cancel_completion()
220 b.cancel_completion()
215 text = d.text[:d.cursor_position] + '\n'
221 text = d.text[:d.cursor_position] + '\n'
216 _, indent = inputsplitter.check_complete(text)
222 _, indent = inputsplitter.check_complete(text)
217 b.insert_text('\n' + (' ' * (indent or 0)), move_cursor=False)
223 b.insert_text('\n' + (' ' * (indent or 0)), move_cursor=False)
218
224
219 return newline_autoindent
225 return newline_autoindent
220
226
221
227
222 def open_input_in_editor(event):
228 def open_input_in_editor(event):
223 event.app.current_buffer.tempfile_suffix = ".py"
229 event.app.current_buffer.tempfile_suffix = ".py"
224 event.app.current_buffer.open_in_editor()
230 event.app.current_buffer.open_in_editor()
225
231
226
232
227 if sys.platform == 'win32':
233 if sys.platform == 'win32':
228 from IPython.core.error import TryNext
234 from IPython.core.error import TryNext
229 from IPython.lib.clipboard import (ClipboardEmpty,
235 from IPython.lib.clipboard import (ClipboardEmpty,
230 win32_clipboard_get,
236 win32_clipboard_get,
231 tkinter_clipboard_get)
237 tkinter_clipboard_get)
232
238
233 @undoc
239 @undoc
234 def win_paste(event):
240 def win_paste(event):
235 try:
241 try:
236 text = win32_clipboard_get()
242 text = win32_clipboard_get()
237 except TryNext:
243 except TryNext:
238 try:
244 try:
239 text = tkinter_clipboard_get()
245 text = tkinter_clipboard_get()
240 except (TryNext, ClipboardEmpty):
246 except (TryNext, ClipboardEmpty):
241 return
247 return
242 except ClipboardEmpty:
248 except ClipboardEmpty:
243 return
249 return
244 event.current_buffer.insert_text(text.replace('\t', ' ' * 4))
250 event.current_buffer.insert_text(text.replace('\t', ' ' * 4))
@@ -1,166 +1,165 b''
1 =====================================
1 =====================================
2 Introduction to IPython configuration
2 Introduction to IPython configuration
3 =====================================
3 =====================================
4
4
5 .. _setting_config:
5 .. _setting_config:
6
6
7 Setting configurable options
7 Setting configurable options
8 ============================
8 ============================
9
9
10 Many of IPython's classes have configurable attributes (see
10 Many of IPython's classes have configurable attributes (see
11 :doc:`options/index` for the list). These can be
11 :doc:`options/index` for the list). These can be
12 configured in several ways.
12 configured in several ways.
13
13
14 Python config files
14 Python config files
15 -------------------
15 -------------------
16
16
17 To create the blank config files, run::
17 To create the blank config files, run::
18
18
19 ipython profile create [profilename]
19 ipython profile create [profilename]
20
20
21 If you leave out the profile name, the files will be created for the
21 If you leave out the profile name, the files will be created for the
22 ``default`` profile (see :ref:`profiles`). These will typically be
22 ``default`` profile (see :ref:`profiles`). These will typically be
23 located in :file:`~/.ipython/profile_default/`, and will be named
23 located in :file:`~/.ipython/profile_default/`, and will be named
24 :file:`ipython_config.py`, :file:`ipython_notebook_config.py`, etc.
24 :file:`ipython_config.py`, :file:`ipython_notebook_config.py`, etc.
25 The settings in :file:`ipython_config.py` apply to all IPython commands.
25 The settings in :file:`ipython_config.py` apply to all IPython commands.
26
26
27 The files typically start by getting the root config object::
27 The files typically start by getting the root config object::
28
28
29 c = get_config()
29 c = get_config()
30
30
31 You can then configure class attributes like this::
31 You can then configure class attributes like this::
32
32
33 c.InteractiveShell.automagic = False
33 c.InteractiveShell.automagic = False
34
34
35 Be careful with spelling--incorrect names will simply be ignored, with
35 Be careful with spelling--incorrect names will simply be ignored, with
36 no error.
36 no error.
37
37
38 To add to a collection which may have already been defined elsewhere,
38 To add to a collection which may have already been defined elsewhere,
39 you can use methods like those found on lists, dicts and sets: append,
39 you can use methods like those found on lists, dicts and sets: append,
40 extend, :meth:`~traitlets.config.LazyConfigValue.prepend` (like
40 extend, :meth:`~traitlets.config.LazyConfigValue.prepend` (like
41 extend, but at the front), add and update (which works both for dicts
41 extend, but at the front), add and update (which works both for dicts
42 and sets)::
42 and sets)::
43
43
44 c.InteractiveShellApp.extensions.append('Cython')
44 c.InteractiveShellApp.extensions.append('Cython')
45
45
46 .. versionadded:: 2.0
46 .. versionadded:: 2.0
47 list, dict and set methods for config values
47 list, dict and set methods for config values
48
48
49 Example config file
49 Example config file
50 ```````````````````
50 ```````````````````
51
51
52 ::
52 ::
53
53
54 # sample ipython_config.py
54 # sample ipython_config.py
55 c = get_config()
55 c = get_config()
56
56
57 c.TerminalIPythonApp.display_banner = True
57 c.TerminalIPythonApp.display_banner = True
58 c.InteractiveShellApp.log_level = 20
58 c.InteractiveShellApp.log_level = 20
59 c.InteractiveShellApp.extensions = [
59 c.InteractiveShellApp.extensions = [
60 'myextension'
60 'myextension'
61 ]
61 ]
62 c.InteractiveShellApp.exec_lines = [
62 c.InteractiveShellApp.exec_lines = [
63 'import numpy',
63 'import numpy',
64 'import scipy'
64 'import scipy'
65 ]
65 ]
66 c.InteractiveShellApp.exec_files = [
66 c.InteractiveShellApp.exec_files = [
67 'mycode.py',
67 'mycode.py',
68 'fancy.ipy'
68 'fancy.ipy'
69 ]
69 ]
70 c.InteractiveShell.autoindent = True
71 c.InteractiveShell.colors = 'LightBG'
70 c.InteractiveShell.colors = 'LightBG'
72 c.InteractiveShell.confirm_exit = False
71 c.InteractiveShell.confirm_exit = False
73 c.InteractiveShell.editor = 'nano'
72 c.InteractiveShell.editor = 'nano'
74 c.InteractiveShell.xmode = 'Context'
73 c.InteractiveShell.xmode = 'Context'
75
74
76 c.PrefilterManager.multi_line_specials = True
75 c.PrefilterManager.multi_line_specials = True
77
76
78 c.AliasManager.user_aliases = [
77 c.AliasManager.user_aliases = [
79 ('la', 'ls -al')
78 ('la', 'ls -al')
80 ]
79 ]
81
80
82
81
83 Command line arguments
82 Command line arguments
84 ----------------------
83 ----------------------
85
84
86 Every configurable value can be set from the command line, using this
85 Every configurable value can be set from the command line, using this
87 syntax::
86 syntax::
88
87
89 ipython --ClassName.attribute=value
88 ipython --ClassName.attribute=value
90
89
91 Many frequently used options have short aliases and flags, such as
90 Many frequently used options have short aliases and flags, such as
92 ``--matplotlib`` (to integrate with a matplotlib GUI event loop) or
91 ``--matplotlib`` (to integrate with a matplotlib GUI event loop) or
93 ``--pdb`` (automatic post-mortem debugging of exceptions).
92 ``--pdb`` (automatic post-mortem debugging of exceptions).
94
93
95 To see all of these abbreviated options, run::
94 To see all of these abbreviated options, run::
96
95
97 ipython --help
96 ipython --help
98 ipython notebook --help
97 ipython notebook --help
99 # etc.
98 # etc.
100
99
101 Options specified at the command line, in either format, override
100 Options specified at the command line, in either format, override
102 options set in a configuration file.
101 options set in a configuration file.
103
102
104 The config magic
103 The config magic
105 ----------------
104 ----------------
106
105
107 You can also modify config from inside IPython, using a magic command::
106 You can also modify config from inside IPython, using a magic command::
108
107
109 %config IPCompleter.greedy = True
108 %config IPCompleter.greedy = True
110
109
111 At present, this only affects the current session - changes you make to
110 At present, this only affects the current session - changes you make to
112 config are not saved anywhere. Also, some options are only read when
111 config are not saved anywhere. Also, some options are only read when
113 IPython starts, so they can't be changed like this.
112 IPython starts, so they can't be changed like this.
114
113
115 .. _configure_start_ipython:
114 .. _configure_start_ipython:
116
115
117 Running IPython from Python
116 Running IPython from Python
118 ----------------------------
117 ----------------------------
119
118
120 If you are using :ref:`embedding` to start IPython from a normal
119 If you are using :ref:`embedding` to start IPython from a normal
121 python file, you can set configuration options the same way as in a
120 python file, you can set configuration options the same way as in a
122 config file by creating a traitlets config object and passing it to
121 config file by creating a traitlets config object and passing it to
123 start_ipython like in the example below.
122 start_ipython like in the example below.
124
123
125 .. literalinclude:: ../../../examples/Embedding/start_ipython_config.py
124 .. literalinclude:: ../../../examples/Embedding/start_ipython_config.py
126 :language: python
125 :language: python
127
126
128 .. _profiles:
127 .. _profiles:
129
128
130 Profiles
129 Profiles
131 ========
130 ========
132
131
133 IPython can use multiple profiles, with separate configuration and
132 IPython can use multiple profiles, with separate configuration and
134 history. By default, if you don't specify a profile, IPython always runs
133 history. By default, if you don't specify a profile, IPython always runs
135 in the ``default`` profile. To use a new profile::
134 in the ``default`` profile. To use a new profile::
136
135
137 ipython profile create foo # create the profile foo
136 ipython profile create foo # create the profile foo
138 ipython --profile=foo # start IPython using the new profile
137 ipython --profile=foo # start IPython using the new profile
139
138
140 Profiles are typically stored in :ref:`ipythondir`, but you can also keep
139 Profiles are typically stored in :ref:`ipythondir`, but you can also keep
141 a profile in the current working directory, for example to distribute it
140 a profile in the current working directory, for example to distribute it
142 with a project. To find a profile directory on the filesystem::
141 with a project. To find a profile directory on the filesystem::
143
142
144 ipython locate profile foo
143 ipython locate profile foo
145
144
146 .. _ipythondir:
145 .. _ipythondir:
147
146
148 The IPython directory
147 The IPython directory
149 =====================
148 =====================
150
149
151 IPython stores its files---config, command history and extensions---in
150 IPython stores its files---config, command history and extensions---in
152 the directory :file:`~/.ipython/` by default.
151 the directory :file:`~/.ipython/` by default.
153
152
154 .. envvar:: IPYTHONDIR
153 .. envvar:: IPYTHONDIR
155
154
156 If set, this environment variable should be the path to a directory,
155 If set, this environment variable should be the path to a directory,
157 which IPython will use for user data. IPython will create it if it
156 which IPython will use for user data. IPython will create it if it
158 does not exist.
157 does not exist.
159
158
160 .. option:: --ipython-dir=<path>
159 .. option:: --ipython-dir=<path>
161
160
162 This command line option can also be used to override the default
161 This command line option can also be used to override the default
163 IPython directory.
162 IPython directory.
164
163
165 To see where IPython is looking for the IPython directory, use the command
164 To see where IPython is looking for the IPython directory, use the command
166 ``ipython locate``, or the Python function :func:`IPython.paths.get_ipython_dir`.
165 ``ipython locate``, or the Python function :func:`IPython.paths.get_ipython_dir`.
@@ -1,282 +1,282 b''
1 .. _tutorial:
1 .. _tutorial:
2
2
3 ======================
3 ======================
4 Introducing IPython
4 Introducing IPython
5 ======================
5 ======================
6
6
7 You don't need to know anything beyond Python to start using IPython – just type
7 You don't need to know anything beyond Python to start using IPython – just type
8 commands as you would at the standard Python prompt. But IPython can do much
8 commands as you would at the standard Python prompt. But IPython can do much
9 more than the standard prompt. Some key features are described here. For more
9 more than the standard prompt. Some key features are described here. For more
10 information, check the :ref:`tips page <tips>`, or look at examples in the
10 information, check the :ref:`tips page <tips>`, or look at examples in the
11 `IPython cookbook <https://github.com/ipython/ipython/wiki/Cookbook%3A-Index>`_.
11 `IPython cookbook <https://github.com/ipython/ipython/wiki/Cookbook%3A-Index>`_.
12
12
13 If you haven't done that yet see `how to install ipython <install>`_ .
13 If you haven't done that yet see `how to install ipython <install>`_ .
14
14
15 If you've never used Python before, you might want to look at `the official
15 If you've never used Python before, you might want to look at `the official
16 tutorial <http://docs.python.org/tutorial/>`_ or an alternative, `Dive into
16 tutorial <http://docs.python.org/tutorial/>`_ or an alternative, `Dive into
17 Python <http://diveintopython.net/toc/index.html>`_.
17 Python <http://diveintopython.net/toc/index.html>`_.
18
18
19 Start IPython by issuing the ``ipython`` command from your shell, you should be
19 Start IPython by issuing the ``ipython`` command from your shell, you should be
20 greeted by the following::
20 greeted by the following::
21
21
22 Python 3.6.0
22 Python 3.6.0
23 Type 'copyright', 'credits' or 'license' for more information
23 Type 'copyright', 'credits' or 'license' for more information
24 IPython 6.0.0.dev -- An enhanced Interactive Python. Type '?' for help.
24 IPython 6.0.0.dev -- An enhanced Interactive Python. Type '?' for help.
25
25
26 In [1]:
26 In [1]:
27
27
28
28
29 Unlike the Python REPL, you will see that the input prompt is ``In [N]:``
29 Unlike the Python REPL, you will see that the input prompt is ``In [N]:``
30 instead of ``>>>``. The number ``N`` in the prompt will be used later in this
30 instead of ``>>>``. The number ``N`` in the prompt will be used later in this
31 tutorial but should usually not impact the computation.
31 tutorial but should usually not impact the computation.
32
32
33 You should be able to type single line expressions and press enter to evaluate
33 You should be able to type single line expressions and press enter to evaluate
34 them. If an expression is incomplete, IPython will automatically detect this and
34 them. If an expression is incomplete, IPython will automatically detect this and
35 add a new line when you press :kbd:`Enter` instead of executing right away.
35 add a new line when you press :kbd:`Enter` instead of executing right away.
36
36
37 Feel free to explore multi-line text input. Unlike many other REPLs, with
37 Feel free to explore multi-line text input. Unlike many other REPLs, with
38 IPython you can use the up and down arrow keys when editing multi-line
38 IPython you can use the up and down arrow keys when editing multi-line
39 code blocks.
39 code blocks.
40
40
41 Here is an example of a longer interaction with the IPython REPL,
41 Here is an example of a longer interaction with the IPython REPL,
42 which we often refer to as an IPython *session* ::
42 which we often refer to as an IPython *session* ::
43
43
44 In [1]: print('Hello IPython')
44 In [1]: print('Hello IPython')
45 Hello IPython
45 Hello IPython
46
46
47 In [2]: 21 * 2
47 In [2]: 21 * 2
48 Out[2]: 42
48 Out[2]: 42
49
49
50 In [3]: def say_hello(name):
50 In [3]: def say_hello(name):
51 ...: print('Hello {name}'.format(name=name))
51 ...: print('Hello {name}'.format(name=name))
52 ...:
52 ...:
53
53
54 We won't get into details right now, but you may notice a few differences to
54 We won't get into details right now, but you may notice a few differences to
55 the standard Python REPL. First, your code should be syntax-highlighted as you
55 the standard Python REPL. First, your code should be syntax-highlighted as you
56 type. Second, you will see that some results will have an ``Out[N]:`` prompt,
56 type. Second, you will see that some results will have an ``Out[N]:`` prompt,
57 while some other do not. We'll come to this later.
57 while some other do not. We'll come to this later.
58
58
59 Depending on the exact command you are typing you might realize that sometimes
59 Depending on the exact command you are typing you might realize that sometimes
60 :kbd:`Enter` will add a new line, and sometimes it will execute the current
60 :kbd:`Enter` will add a new line, and sometimes it will execute the current
61 statement. IPython tries to guess what you are doing, so most of the time you
61 statement. IPython tries to guess what you are doing, so most of the time you
62 should not have to care. Though if by any chance IPython does not the right
62 should not have to care. Though if by any chance IPython does not the right
63 thing you can force execution of the current code block by pressing in sequence
63 thing you can force execution of the current code block by pressing in sequence
64 :kbd:`Esc` and :kbd:`Enter`. You can also force the insertion of a new line at
64 :kbd:`Esc` and :kbd:`Enter`. You can also force the insertion of a new line at
65 the position of the cursor by using :kbd:`Ctrl-o`.
65 the position of the cursor by using :kbd:`Ctrl-o`.
66
66
67 The four most helpful commands
67 The four most helpful commands
68 ==============================
68 ==============================
69
69
70 The four most helpful commands, as well as their brief description, is shown
70 The four most helpful commands, as well as their brief description, is shown
71 to you in a banner, every time you start IPython:
71 to you in a banner, every time you start IPython:
72
72
73 ========== =========================================================
73 ========== =========================================================
74 command description
74 command description
75 ========== =========================================================
75 ========== =========================================================
76 ? Introduction and overview of IPython's features.
76 ? Introduction and overview of IPython's features.
77 %quickref Quick reference.
77 %quickref Quick reference.
78 help Python's own help system.
78 help Python's own help system.
79 object? Details about 'object', use 'object??' for extra details.
79 object? Details about 'object', use 'object??' for extra details.
80 ========== =========================================================
80 ========== =========================================================
81
81
82 Tab completion
82 Tab completion
83 ==============
83 ==============
84
84
85 Tab completion, especially for attributes, is a convenient way to explore the
85 Tab completion, especially for attributes, is a convenient way to explore the
86 structure of any object you're dealing with. Simply type ``object_name.<TAB>``
86 structure of any object you're dealing with. Simply type ``object_name.<TAB>``
87 to view the object's attributes. Besides Python objects and keywords, tab
87 to view the object's attributes. Besides Python objects and keywords, tab
88 completion also works on file and directory names.
88 completion also works on file and directory names.
89
89
90 Starting with IPython 6.0, if ``jedi`` is installed, IPython will try to pull
90 Starting with IPython 6.0, if ``jedi`` is installed, IPython will try to pull
91 completions from Jedi as well. This allows to not only inspect currently
91 completions from Jedi as well. This allows to not only inspect currently
92 existing objects, but also to infer completion statically without executing
92 existing objects, but also to infer completion statically without executing
93 code. There is nothing particular need to get this to work, simply use tab
93 code. There is nothing particular need to get this to work, simply use tab
94 completion on more complex expressions like the following::
94 completion on more complex expressions like the following::
95
95
96 >>> data = ['Number of users', 123456]
96 >>> data = ['Number of users', 123456]
97 ... data[0].<tab>
97 ... data[0].<tab>
98
98
99 IPython and Jedi will be able to infer that ``data[0]`` is actually a string
99 IPython and Jedi will be able to infer that ``data[0]`` is actually a string
100 and should show relevant completions like ``upper()``, ``lower()`` and other
100 and should show relevant completions like ``upper()``, ``lower()`` and other
101 string methods. You can use the :kbd:`Tab` key to cycle through completions,
101 string methods. You can use the :kbd:`Tab` key to cycle through completions,
102 and while a completion is highlighted, its type will be shown as well.
102 and while a completion is highlighted, its type will be shown as well.
103 When the type of the completion is a function, the completer will also show the
103 When the type of the completion is a function, the completer will also show the
104 signature of the function when highlighted.
104 signature of the function when highlighted.
105
105
106 Exploring your objects
106 Exploring your objects
107 ======================
107 ======================
108
108
109 Typing ``object_name?`` will print all sorts of details about any object,
109 Typing ``object_name?`` will print all sorts of details about any object,
110 including docstrings, function definition lines (for call arguments) and
110 including docstrings, function definition lines (for call arguments) and
111 constructor details for classes. To get specific information on an object, you
111 constructor details for classes. To get specific information on an object, you
112 can use the magic commands ``%pdoc``, ``%pdef``, ``%psource`` and ``%pfile``
112 can use the magic commands ``%pdoc``, ``%pdef``, ``%psource`` and ``%pfile``
113
113
114 .. _magics_explained:
114 .. _magics_explained:
115
115
116 Magic functions
116 Magic functions
117 ===============
117 ===============
118
118
119 IPython has a set of predefined 'magic functions' that you can call with a
119 IPython has a set of predefined 'magic functions' that you can call with a
120 command line style syntax. There are two kinds of magics, line-oriented and
120 command line style syntax. There are two kinds of magics, line-oriented and
121 cell-oriented. **Line magics** are prefixed with the ``%`` character and work
121 cell-oriented. **Line magics** are prefixed with the ``%`` character and work
122 much like OS command-line calls: they get as an argument the rest of the line,
122 much like OS command-line calls: they get as an argument the rest of the line,
123 where arguments are passed without parentheses or quotes. **Lines magics** can
123 where arguments are passed without parentheses or quotes. **Lines magics** can
124 return results and can be used in the right hand side of an assignment. **Cell
124 return results and can be used in the right hand side of an assignment. **Cell
125 magics** are prefixed with a double ``%%``, and they are functions that get as
125 magics** are prefixed with a double ``%%``, and they are functions that get as
126 an argument not only the rest of the line, but also the lines below it in a
126 an argument not only the rest of the line, but also the lines below it in a
127 separate argument.
127 separate argument.
128
128
129 Magics are useful as convenient functions where Python syntax is not the most
129 Magics are useful as convenient functions where Python syntax is not the most
130 natural one, or when one want to embed invalid python syntax in their work flow.
130 natural one, or when one want to embed invalid python syntax in their work flow.
131
131
132 The following examples show how to call the built-in :magic:`timeit` magic, both
132 The following examples show how to call the built-in :magic:`timeit` magic, both
133 in line and cell mode::
133 in line and cell mode::
134
134
135 In [1]: %timeit range(1000)
135 In [1]: %timeit range(1000)
136 100000 loops, best of 3: 7.76 us per loop
136 100000 loops, best of 3: 7.76 us per loop
137
137
138 In [2]: %%timeit x = range(10000)
138 In [2]: %%timeit x = range(10000)
139 ...: max(x)
139 ...: max(x)
140 ...:
140 ...:
141 1000 loops, best of 3: 223 us per loop
141 1000 loops, best of 3: 223 us per loop
142
142
143 The built-in magics include:
143 The built-in magics include:
144
144
145 - Functions that work with code: :magic:`run`, :magic:`edit`, :magic:`save`,
145 - Functions that work with code: :magic:`run`, :magic:`edit`, :magic:`save`,
146 :magic:`macro`, :magic:`recall`, etc.
146 :magic:`macro`, :magic:`recall`, etc.
147
147
148 - Functions which affect the shell: :magic:`colors`, :magic:`xmode`,
148 - Functions which affect the shell: :magic:`colors`, :magic:`xmode`,
149 :magic:`autoindent`, :magic:`automagic`, etc.
149 :magic:`automagic`, etc.
150
150
151 - Other functions such as :magic:`reset`, :magic:`timeit`,
151 - Other functions such as :magic:`reset`, :magic:`timeit`,
152 :cellmagic:`writefile`, :magic:`load`, or :magic:`paste`.
152 :cellmagic:`writefile`, :magic:`load`, or :magic:`paste`.
153
153
154 You can always call magics using the ``%`` prefix, and if you're calling a line
154 You can always call magics using the ``%`` prefix, and if you're calling a line
155 magic on a line by itself, as long as the identifier is not defined in your
155 magic on a line by itself, as long as the identifier is not defined in your
156 namespace, you can omit even that::
156 namespace, you can omit even that::
157
157
158 run thescript.py
158 run thescript.py
159
159
160 You can toggle this behavior by running the :magic:`automagic` magic. Cell
160 You can toggle this behavior by running the :magic:`automagic` magic. Cell
161 magics must always have the ``%%`` prefix.
161 magics must always have the ``%%`` prefix.
162
162
163 A more detailed explanation of the magic system can be obtained by calling
163 A more detailed explanation of the magic system can be obtained by calling
164 ``%magic``, and for more details on any magic function, call ``%somemagic?`` to
164 ``%magic``, and for more details on any magic function, call ``%somemagic?`` to
165 read its docstring. To see all the available magic functions, call
165 read its docstring. To see all the available magic functions, call
166 ``%lsmagic``.
166 ``%lsmagic``.
167
167
168 .. seealso::
168 .. seealso::
169
169
170 The :ref:`magic` section of the documentation goes more in depth into how
170 The :ref:`magic` section of the documentation goes more in depth into how
171 the magics works and how to define your own, and :doc:`magics` for a list of
171 the magics works and how to define your own, and :doc:`magics` for a list of
172 built-in magics.
172 built-in magics.
173
173
174 `Cell magics`_ example notebook
174 `Cell magics`_ example notebook
175
175
176 Running and Editing
176 Running and Editing
177 -------------------
177 -------------------
178
178
179 The :magic:`run` magic command allows you to run any python script and load all
179 The :magic:`run` magic command allows you to run any python script and load all
180 of its data directly into the interactive namespace. Since the file is re-read
180 of its data directly into the interactive namespace. Since the file is re-read
181 from disk each time, changes you make to it are reflected immediately (unlike
181 from disk each time, changes you make to it are reflected immediately (unlike
182 imported modules, which have to be specifically reloaded). IPython also includes
182 imported modules, which have to be specifically reloaded). IPython also includes
183 :ref:`dreload <dreload>`, a recursive reload function.
183 :ref:`dreload <dreload>`, a recursive reload function.
184
184
185 ``%run`` has special flags for timing the execution of your scripts (-t), or
185 ``%run`` has special flags for timing the execution of your scripts (-t), or
186 for running them under the control of either Python's pdb debugger (-d) or
186 for running them under the control of either Python's pdb debugger (-d) or
187 profiler (-p).
187 profiler (-p).
188
188
189 The :magic:`edit` command gives a reasonable approximation of multi-line editing,
189 The :magic:`edit` command gives a reasonable approximation of multi-line editing,
190 by invoking your favorite editor on the spot. IPython will execute the
190 by invoking your favorite editor on the spot. IPython will execute the
191 code you type in there as if it were typed interactively. Note that for
191 code you type in there as if it were typed interactively. Note that for
192 :magic:`edit` to work, the call to startup your editor has to be a blocking
192 :magic:`edit` to work, the call to startup your editor has to be a blocking
193 call. In a GUI environment, your editor likely will have such an option.
193 call. In a GUI environment, your editor likely will have such an option.
194
194
195 Debugging
195 Debugging
196 ---------
196 ---------
197
197
198 After an exception occurs, you can call :magic:`debug` to jump into the Python
198 After an exception occurs, you can call :magic:`debug` to jump into the Python
199 debugger (pdb) and examine the problem. Alternatively, if you call :magic:`pdb`,
199 debugger (pdb) and examine the problem. Alternatively, if you call :magic:`pdb`,
200 IPython will automatically start the debugger on any uncaught exception. You can
200 IPython will automatically start the debugger on any uncaught exception. You can
201 print variables, see code, execute statements and even walk up and down the call
201 print variables, see code, execute statements and even walk up and down the call
202 stack to track down the true source of the problem. This can be an efficient way
202 stack to track down the true source of the problem. This can be an efficient way
203 to develop and debug code, in many cases eliminating the need for print
203 to develop and debug code, in many cases eliminating the need for print
204 statements or external debugging tools.
204 statements or external debugging tools.
205
205
206 You can also step through a program from the beginning by calling
206 You can also step through a program from the beginning by calling
207 ``%run -d theprogram.py``.
207 ``%run -d theprogram.py``.
208
208
209 History
209 History
210 =======
210 =======
211
211
212 IPython stores both the commands you enter, and the results it produces. You
212 IPython stores both the commands you enter, and the results it produces. You
213 can easily go through previous commands with the up- and down-arrow keys, or
213 can easily go through previous commands with the up- and down-arrow keys, or
214 access your history in more sophisticated ways.
214 access your history in more sophisticated ways.
215
215
216 Input and output history are kept in variables called ``In`` and ``Out``, keyed
216 Input and output history are kept in variables called ``In`` and ``Out``, keyed
217 by the prompt numbers, e.g. ``In[4]``. The last three objects in output history
217 by the prompt numbers, e.g. ``In[4]``. The last three objects in output history
218 are also kept in variables named ``_``, ``__`` and ``___``.
218 are also kept in variables named ``_``, ``__`` and ``___``.
219
219
220 You can use the ``%history`` magic function to examine past input and output.
220 You can use the ``%history`` magic function to examine past input and output.
221 Input history from previous sessions is saved in a database, and IPython can be
221 Input history from previous sessions is saved in a database, and IPython can be
222 configured to save output history.
222 configured to save output history.
223
223
224 Several other magic functions can use your input history, including ``%edit``,
224 Several other magic functions can use your input history, including ``%edit``,
225 ``%rerun``, ``%recall``, ``%macro``, ``%save`` and ``%pastebin``. You can use a
225 ``%rerun``, ``%recall``, ``%macro``, ``%save`` and ``%pastebin``. You can use a
226 standard format to refer to lines::
226 standard format to refer to lines::
227
227
228 %pastebin 3 18-20 ~1/1-5
228 %pastebin 3 18-20 ~1/1-5
229
229
230 This will take line 3 and lines 18 to 20 from the current session, and lines
230 This will take line 3 and lines 18 to 20 from the current session, and lines
231 1-5 from the previous session.
231 1-5 from the previous session.
232
232
233 System shell commands
233 System shell commands
234 =====================
234 =====================
235
235
236 To run any command at the system shell, simply prefix it with ``!``, e.g.::
236 To run any command at the system shell, simply prefix it with ``!``, e.g.::
237
237
238 !ping www.bbc.co.uk
238 !ping www.bbc.co.uk
239
239
240 You can capture the output into a Python list, e.g.: ``files = !ls``. To pass
240 You can capture the output into a Python list, e.g.: ``files = !ls``. To pass
241 the values of Python variables or expressions to system commands, prefix them
241 the values of Python variables or expressions to system commands, prefix them
242 with $: ``!grep -rF $pattern ipython/*`` or wrap in `{braces}`. See :ref:`our
242 with $: ``!grep -rF $pattern ipython/*`` or wrap in `{braces}`. See :ref:`our
243 shell section <system_shell_access>` for more details.
243 shell section <system_shell_access>` for more details.
244
244
245 Define your own system aliases
245 Define your own system aliases
246 ------------------------------
246 ------------------------------
247
247
248 It's convenient to have aliases to the system commands you use most often. This
248 It's convenient to have aliases to the system commands you use most often. This
249 allows you to work seamlessly from inside IPython with the same commands you are
249 allows you to work seamlessly from inside IPython with the same commands you are
250 used to in your system shell. IPython comes with some pre-defined aliases and a
250 used to in your system shell. IPython comes with some pre-defined aliases and a
251 complete system for changing directories, both via a stack (see :magic:`pushd`,
251 complete system for changing directories, both via a stack (see :magic:`pushd`,
252 :magic:`popd` and :magic:`dhist`) and via direct :magic:`cd`. The latter keeps a
252 :magic:`popd` and :magic:`dhist`) and via direct :magic:`cd`. The latter keeps a
253 history of visited directories and allows you to go to any previously visited
253 history of visited directories and allows you to go to any previously visited
254 one.
254 one.
255
255
256
256
257 Configuration
257 Configuration
258 =============
258 =============
259
259
260 Much of IPython can be tweaked through :doc:`configuration </config/intro>`.
260 Much of IPython can be tweaked through :doc:`configuration </config/intro>`.
261 To get started, use the command ``ipython profile create`` to produce the
261 To get started, use the command ``ipython profile create`` to produce the
262 default config files. These will be placed in
262 default config files. These will be placed in
263 :file:`~/.ipython/profile_default`, and contain comments explaining
263 :file:`~/.ipython/profile_default`, and contain comments explaining
264 what the various options do.
264 what the various options do.
265
265
266 Profiles allow you to use IPython for different tasks, keeping separate config
266 Profiles allow you to use IPython for different tasks, keeping separate config
267 files and history for each one. More details in :ref:`the profiles section
267 files and history for each one. More details in :ref:`the profiles section
268 <profiles>`.
268 <profiles>`.
269
269
270 .. _startup_files:
270 .. _startup_files:
271
271
272 Startup Files
272 Startup Files
273 -------------
273 -------------
274
274
275 If you want some code to be run at the beginning of every IPython session, the
275 If you want some code to be run at the beginning of every IPython session, the
276 easiest way is to add Python (.py) or IPython (.ipy) scripts to your
276 easiest way is to add Python (.py) or IPython (.ipy) scripts to your
277 :file:`profile_default/startup/` directory. Files here will be executed as soon
277 :file:`profile_default/startup/` directory. Files here will be executed as soon
278 as the IPython shell is constructed, before any other code or scripts you have
278 as the IPython shell is constructed, before any other code or scripts you have
279 specified. The files will be run in order of their names, so you can control the
279 specified. The files will be run in order of their names, so you can control the
280 ordering with prefixes, like ``10-myimports.py``.
280 ordering with prefixes, like ``10-myimports.py``.
281
281
282 .. include:: ../links.txt
282 .. include:: ../links.txt
General Comments 0
You need to be logged in to leave comments. Login now