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