##// END OF EJS Templates
Merge pull request #9273 from takluyver/terminal-magics-aliases...
Min RK -
r22129:a3abc138 merge
parent child Browse files
Show More
@@ -1,256 +1,274 b''
1 """IPython terminal interface using prompt_toolkit in place of readline"""
1 """IPython terminal interface using prompt_toolkit in place of readline"""
2 from __future__ import print_function
2 from __future__ import print_function
3
3
4 import os
4 import sys
5 import sys
5
6
6 from IPython.core.interactiveshell import InteractiveShell
7 from IPython.core.interactiveshell import InteractiveShell
7 from IPython.utils.py3compat import PY3, cast_unicode_py2, input
8 from IPython.utils.py3compat import PY3, cast_unicode_py2, input
8 from IPython.utils.terminal import toggle_set_term_title, set_term_title
9 from IPython.utils.terminal import toggle_set_term_title, set_term_title
9 from IPython.utils.process import abbrev_cwd
10 from IPython.utils.process import abbrev_cwd
10 from traitlets import Bool, Unicode, Dict
11 from traitlets import Bool, Unicode, Dict
11
12
12 from prompt_toolkit.completion import Completer, Completion
13 from prompt_toolkit.completion import Completer, Completion
13 from prompt_toolkit.enums import DEFAULT_BUFFER
14 from prompt_toolkit.enums import DEFAULT_BUFFER
14 from prompt_toolkit.filters import HasFocus, HasSelection
15 from prompt_toolkit.filters import HasFocus, HasSelection
15 from prompt_toolkit.history import InMemoryHistory
16 from prompt_toolkit.history import InMemoryHistory
16 from prompt_toolkit.shortcuts import create_prompt_application, create_eventloop
17 from prompt_toolkit.shortcuts import create_prompt_application, create_eventloop
17 from prompt_toolkit.interface import CommandLineInterface
18 from prompt_toolkit.interface import CommandLineInterface
18 from prompt_toolkit.key_binding.manager import KeyBindingManager
19 from prompt_toolkit.key_binding.manager import KeyBindingManager
19 from prompt_toolkit.key_binding.vi_state import InputMode
20 from prompt_toolkit.key_binding.vi_state import InputMode
20 from prompt_toolkit.key_binding.bindings.vi import ViStateFilter
21 from prompt_toolkit.key_binding.bindings.vi import ViStateFilter
21 from prompt_toolkit.keys import Keys
22 from prompt_toolkit.keys import Keys
22 from prompt_toolkit.layout.lexers import PygmentsLexer
23 from prompt_toolkit.layout.lexers import PygmentsLexer
23 from prompt_toolkit.styles import PygmentsStyle
24 from prompt_toolkit.styles import PygmentsStyle
24
25
25 from pygments.styles import get_style_by_name
26 from pygments.styles import get_style_by_name
26 from pygments.lexers import Python3Lexer, PythonLexer
27 from pygments.lexers import Python3Lexer, PythonLexer
27 from pygments.token import Token
28 from pygments.token import Token
28
29
29 from .pt_inputhooks import get_inputhook_func
30 from .pt_inputhooks import get_inputhook_func
30 from .interactiveshell import get_default_editor
31 from .interactiveshell import get_default_editor, TerminalMagics
31
32
32
33
33
34
34 class IPythonPTCompleter(Completer):
35 class IPythonPTCompleter(Completer):
35 """Adaptor to provide IPython completions to prompt_toolkit"""
36 """Adaptor to provide IPython completions to prompt_toolkit"""
36 def __init__(self, ipy_completer):
37 def __init__(self, ipy_completer):
37 self.ipy_completer = ipy_completer
38 self.ipy_completer = ipy_completer
38
39
39 def get_completions(self, document, complete_event):
40 def get_completions(self, document, complete_event):
40 if not document.current_line.strip():
41 if not document.current_line.strip():
41 return
42 return
42
43
43 used, matches = self.ipy_completer.complete(
44 used, matches = self.ipy_completer.complete(
44 line_buffer=document.current_line,
45 line_buffer=document.current_line,
45 cursor_pos=document.cursor_position_col
46 cursor_pos=document.cursor_position_col
46 )
47 )
47 start_pos = -len(used)
48 start_pos = -len(used)
48 for m in matches:
49 for m in matches:
49 yield Completion(m, start_position=start_pos)
50 yield Completion(m, start_position=start_pos)
50
51
51 class TerminalInteractiveShell(InteractiveShell):
52 class TerminalInteractiveShell(InteractiveShell):
52 colors_force = True
53 colors_force = True
53
54
54 pt_cli = None
55 pt_cli = None
55
56
56 vi_mode = Bool(False, config=True,
57 vi_mode = Bool(False, config=True,
57 help="Use vi style keybindings at the prompt",
58 help="Use vi style keybindings at the prompt",
58 )
59 )
59
60
60 mouse_support = Bool(False, config=True,
61 mouse_support = Bool(False, config=True,
61 help="Enable mouse support in the prompt"
62 help="Enable mouse support in the prompt"
62 )
63 )
63
64
64 highlighting_style = Unicode('', config=True,
65 highlighting_style = Unicode('', config=True,
65 help="The name of a Pygments style to use for syntax highlighting"
66 help="The name of a Pygments style to use for syntax highlighting"
66 )
67 )
67
68
68 highlighting_style_overrides = Dict(config=True,
69 highlighting_style_overrides = Dict(config=True,
69 help="Override highlighting format for specific tokens"
70 help="Override highlighting format for specific tokens"
70 )
71 )
71
72
72 editor = Unicode(get_default_editor(), config=True,
73 editor = Unicode(get_default_editor(), config=True,
73 help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
74 help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
74 )
75 )
75
76
76 term_title = Bool(True, config=True,
77 term_title = Bool(True, config=True,
77 help="Automatically set the terminal title"
78 help="Automatically set the terminal title"
78 )
79 )
79 def _term_title_changed(self, name, new_value):
80 def _term_title_changed(self, name, new_value):
80 self.init_term_title()
81 self.init_term_title()
81
82
82 def init_term_title(self):
83 def init_term_title(self):
83 # Enable or disable the terminal title.
84 # Enable or disable the terminal title.
84 if self.term_title:
85 if self.term_title:
85 toggle_set_term_title(True)
86 toggle_set_term_title(True)
86 set_term_title('IPython: ' + abbrev_cwd())
87 set_term_title('IPython: ' + abbrev_cwd())
87 else:
88 else:
88 toggle_set_term_title(False)
89 toggle_set_term_title(False)
89
90
90 def get_prompt_tokens(self, cli):
91 def get_prompt_tokens(self, cli):
91 return [
92 return [
92 (Token.Prompt, 'In ['),
93 (Token.Prompt, 'In ['),
93 (Token.PromptNum, str(self.execution_count)),
94 (Token.PromptNum, str(self.execution_count)),
94 (Token.Prompt, ']: '),
95 (Token.Prompt, ']: '),
95 ]
96 ]
96
97
97 def get_continuation_tokens(self, cli, width):
98 def get_continuation_tokens(self, cli, width):
98 return [
99 return [
99 (Token.Prompt, (' ' * (width - 5)) + '...: '),
100 (Token.Prompt, (' ' * (width - 5)) + '...: '),
100 ]
101 ]
101
102
102 def init_prompt_toolkit_cli(self):
103 def init_prompt_toolkit_cli(self):
103 if not sys.stdin.isatty():
104 if not sys.stdin.isatty():
104 # Piped input - e.g. for tests. Fall back to plain non-interactive
105 # Piped input - e.g. for tests. Fall back to plain non-interactive
105 # output. This is very limited, and only accepts a single line.
106 # output. This is very limited, and only accepts a single line.
106 def prompt():
107 def prompt():
107 return cast_unicode_py2(input('In [%d]: ' % self.execution_count))
108 return cast_unicode_py2(input('In [%d]: ' % self.execution_count))
108 self.prompt_for_code = prompt
109 self.prompt_for_code = prompt
109 return
110 return
110
111
111 kbmanager = KeyBindingManager.for_prompt(enable_vi_mode=self.vi_mode)
112 kbmanager = KeyBindingManager.for_prompt(enable_vi_mode=self.vi_mode)
112 insert_mode = ViStateFilter(kbmanager.get_vi_state, InputMode.INSERT)
113 insert_mode = ViStateFilter(kbmanager.get_vi_state, InputMode.INSERT)
113 # Ctrl+J == Enter, seemingly
114 # Ctrl+J == Enter, seemingly
114 @kbmanager.registry.add_binding(Keys.ControlJ,
115 @kbmanager.registry.add_binding(Keys.ControlJ,
115 filter=(HasFocus(DEFAULT_BUFFER)
116 filter=(HasFocus(DEFAULT_BUFFER)
116 & ~HasSelection()
117 & ~HasSelection()
117 & insert_mode
118 & insert_mode
118 ))
119 ))
119 def _(event):
120 def _(event):
120 b = event.current_buffer
121 b = event.current_buffer
121 d = b.document
122 d = b.document
122 if not (d.on_last_line or d.cursor_position_row >= d.line_count
123 if not (d.on_last_line or d.cursor_position_row >= d.line_count
123 - d.empty_line_count_at_the_end()):
124 - d.empty_line_count_at_the_end()):
124 b.newline()
125 b.newline()
125 return
126 return
126
127
127 status, indent = self.input_splitter.check_complete(d.text)
128 status, indent = self.input_splitter.check_complete(d.text)
128
129
129 if (status != 'incomplete') and b.accept_action.is_returnable:
130 if (status != 'incomplete') and b.accept_action.is_returnable:
130 b.accept_action.validate_and_handle(event.cli, b)
131 b.accept_action.validate_and_handle(event.cli, b)
131 else:
132 else:
132 b.insert_text('\n' + (' ' * (indent or 0)))
133 b.insert_text('\n' + (' ' * (indent or 0)))
133
134
134 @kbmanager.registry.add_binding(Keys.ControlC)
135 @kbmanager.registry.add_binding(Keys.ControlC)
135 def _(event):
136 def _(event):
136 event.current_buffer.reset()
137 event.current_buffer.reset()
137
138
138 # Pre-populate history from IPython's history database
139 # Pre-populate history from IPython's history database
139 history = InMemoryHistory()
140 history = InMemoryHistory()
140 last_cell = u""
141 last_cell = u""
141 for _, _, cell in self.history_manager.get_tail(self.history_load_length,
142 for _, _, cell in self.history_manager.get_tail(self.history_load_length,
142 include_latest=True):
143 include_latest=True):
143 # Ignore blank lines and consecutive duplicates
144 # Ignore blank lines and consecutive duplicates
144 cell = cell.rstrip()
145 cell = cell.rstrip()
145 if cell and (cell != last_cell):
146 if cell and (cell != last_cell):
146 history.append(cell)
147 history.append(cell)
147
148
148 style_overrides = {
149 style_overrides = {
149 Token.Prompt: '#009900',
150 Token.Prompt: '#009900',
150 Token.PromptNum: '#00ff00 bold',
151 Token.PromptNum: '#00ff00 bold',
151 }
152 }
152 if self.highlighting_style:
153 if self.highlighting_style:
153 style_cls = get_style_by_name(self.highlighting_style)
154 style_cls = get_style_by_name(self.highlighting_style)
154 else:
155 else:
155 style_cls = get_style_by_name('default')
156 style_cls = get_style_by_name('default')
156 # The default theme needs to be visible on both a dark background
157 # The default theme needs to be visible on both a dark background
157 # and a light background, because we can't tell what the terminal
158 # and a light background, because we can't tell what the terminal
158 # looks like. These tweaks to the default theme help with that.
159 # looks like. These tweaks to the default theme help with that.
159 style_overrides.update({
160 style_overrides.update({
160 Token.Number: '#007700',
161 Token.Number: '#007700',
161 Token.Operator: 'noinherit',
162 Token.Operator: 'noinherit',
162 Token.String: '#BB6622',
163 Token.String: '#BB6622',
163 Token.Name.Function: '#2080D0',
164 Token.Name.Function: '#2080D0',
164 Token.Name.Class: 'bold #2080D0',
165 Token.Name.Class: 'bold #2080D0',
165 Token.Name.Namespace: 'bold #2080D0',
166 Token.Name.Namespace: 'bold #2080D0',
166 })
167 })
167 style_overrides.update(self.highlighting_style_overrides)
168 style_overrides.update(self.highlighting_style_overrides)
168 style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls,
169 style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls,
169 style_dict=style_overrides)
170 style_dict=style_overrides)
170
171
171 app = create_prompt_application(multiline=True,
172 app = create_prompt_application(multiline=True,
172 lexer=PygmentsLexer(Python3Lexer if PY3 else PythonLexer),
173 lexer=PygmentsLexer(Python3Lexer if PY3 else PythonLexer),
173 get_prompt_tokens=self.get_prompt_tokens,
174 get_prompt_tokens=self.get_prompt_tokens,
174 get_continuation_tokens=self.get_continuation_tokens,
175 get_continuation_tokens=self.get_continuation_tokens,
175 key_bindings_registry=kbmanager.registry,
176 key_bindings_registry=kbmanager.registry,
176 history=history,
177 history=history,
177 completer=IPythonPTCompleter(self.Completer),
178 completer=IPythonPTCompleter(self.Completer),
178 enable_history_search=True,
179 enable_history_search=True,
179 style=style,
180 style=style,
180 mouse_support=self.mouse_support,
181 mouse_support=self.mouse_support,
181 )
182 )
182
183
183 self.pt_cli = CommandLineInterface(app,
184 self.pt_cli = CommandLineInterface(app,
184 eventloop=create_eventloop(self.inputhook))
185 eventloop=create_eventloop(self.inputhook))
185
186
186 def prompt_for_code(self):
187 def prompt_for_code(self):
187 document = self.pt_cli.run(pre_run=self.pre_prompt)
188 document = self.pt_cli.run(pre_run=self.pre_prompt)
188 return document.text
189 return document.text
189
190
190 def init_io(self):
191 def init_io(self):
191 if sys.platform not in {'win32', 'cli'}:
192 if sys.platform not in {'win32', 'cli'}:
192 return
193 return
193
194
194 import colorama
195 import colorama
195 colorama.init()
196 colorama.init()
196
197
197 # For some reason we make these wrappers around stdout/stderr.
198 # For some reason we make these wrappers around stdout/stderr.
198 # For now, we need to reset them so all output gets coloured.
199 # For now, we need to reset them so all output gets coloured.
199 # https://github.com/ipython/ipython/issues/8669
200 # https://github.com/ipython/ipython/issues/8669
200 from IPython.utils import io
201 from IPython.utils import io
201 io.stdout = io.IOStream(sys.stdout)
202 io.stdout = io.IOStream(sys.stdout)
202 io.stderr = io.IOStream(sys.stderr)
203 io.stderr = io.IOStream(sys.stderr)
203
204
205 def init_magics(self):
206 super(TerminalInteractiveShell, self).init_magics()
207 self.register_magics(TerminalMagics)
208
209 def init_alias(self):
210 # The parent class defines aliases that can be safely used with any
211 # frontend.
212 super(TerminalInteractiveShell, self).init_alias()
213
214 # Now define aliases that only make sense on the terminal, because they
215 # need direct access to the console in a way that we can't emulate in
216 # GUI or web frontend
217 if os.name == 'posix':
218 for cmd in ['clear', 'more', 'less', 'man']:
219 self.alias_manager.soft_define_alias(cmd, cmd)
220
221
204 def __init__(self, *args, **kwargs):
222 def __init__(self, *args, **kwargs):
205 super(TerminalInteractiveShell, self).__init__(*args, **kwargs)
223 super(TerminalInteractiveShell, self).__init__(*args, **kwargs)
206 self.init_prompt_toolkit_cli()
224 self.init_prompt_toolkit_cli()
207 self.init_term_title()
225 self.init_term_title()
208 self.keep_running = True
226 self.keep_running = True
209
227
210 def ask_exit(self):
228 def ask_exit(self):
211 self.keep_running = False
229 self.keep_running = False
212
230
213 rl_next_input = None
231 rl_next_input = None
214
232
215 def pre_prompt(self):
233 def pre_prompt(self):
216 if self.rl_next_input:
234 if self.rl_next_input:
217 self.pt_cli.application.buffer.text = cast_unicode_py2(self.rl_next_input)
235 self.pt_cli.application.buffer.text = cast_unicode_py2(self.rl_next_input)
218 self.rl_next_input = None
236 self.rl_next_input = None
219
237
220 def interact(self):
238 def interact(self):
221 while self.keep_running:
239 while self.keep_running:
222 print(self.separate_in, end='')
240 print(self.separate_in, end='')
223
241
224 try:
242 try:
225 code = self.prompt_for_code()
243 code = self.prompt_for_code()
226 except EOFError:
244 except EOFError:
227 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'):
245 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'):
228 self.ask_exit()
246 self.ask_exit()
229
247
230 else:
248 else:
231 if code:
249 if code:
232 self.run_cell(code, store_history=True)
250 self.run_cell(code, store_history=True)
233
251
234 def mainloop(self):
252 def mainloop(self):
235 # An extra layer of protection in case someone mashing Ctrl-C breaks
253 # An extra layer of protection in case someone mashing Ctrl-C breaks
236 # out of our internal code.
254 # out of our internal code.
237 while True:
255 while True:
238 try:
256 try:
239 self.interact()
257 self.interact()
240 break
258 break
241 except KeyboardInterrupt:
259 except KeyboardInterrupt:
242 print("\nKeyboardInterrupt escaped interact()\n")
260 print("\nKeyboardInterrupt escaped interact()\n")
243
261
244 _inputhook = None
262 _inputhook = None
245 def inputhook(self, context):
263 def inputhook(self, context):
246 if self._inputhook is not None:
264 if self._inputhook is not None:
247 self._inputhook(context)
265 self._inputhook(context)
248
266
249 def enable_gui(self, gui=None):
267 def enable_gui(self, gui=None):
250 if gui:
268 if gui:
251 self._inputhook = get_inputhook_func(gui)
269 self._inputhook = get_inputhook_func(gui)
252 else:
270 else:
253 self._inputhook = None
271 self._inputhook = None
254
272
255 if __name__ == '__main__':
273 if __name__ == '__main__':
256 TerminalInteractiveShell.instance().interact()
274 TerminalInteractiveShell.instance().interact()
General Comments 0
You need to be logged in to leave comments. Login now