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