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