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