##// END OF EJS Templates
Re-enable continuation prompts...
Thomas Kluyver -
Show More
@@ -1,240 +1,238
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 82 (Token.Prompt, (' ' * (width - 2)) + ': '),
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 # The line below is waiting for a new release of
158 # prompt_toolkit (> 0.57)
159 #get_continuation_tokens=self.get_continuation_tokens,
157 get_continuation_tokens=self.get_continuation_tokens,
160 158 key_bindings_registry=kbmanager.registry,
161 159 history=history,
162 160 completer=IPythonPTCompleter(self.Completer),
163 161 enable_history_search=True,
164 162 style=style,
165 163 mouse_support=self.mouse_support,
166 164 )
167 165
168 166 self.pt_cli = CommandLineInterface(app,
169 167 eventloop=create_eventloop(self.inputhook))
170 168
171 169 def prompt_for_code(self):
172 170 document = self.pt_cli.run(pre_run=self.pre_prompt)
173 171 return document.text
174 172
175 173 def init_io(self):
176 174 if sys.platform not in {'win32', 'cli'}:
177 175 return
178 176
179 177 import colorama
180 178 colorama.init()
181 179
182 180 # For some reason we make these wrappers around stdout/stderr.
183 181 # For now, we need to reset them so all output gets coloured.
184 182 # https://github.com/ipython/ipython/issues/8669
185 183 from IPython.utils import io
186 184 io.stdout = io.IOStream(sys.stdout)
187 185 io.stderr = io.IOStream(sys.stderr)
188 186
189 187 def __init__(self, *args, **kwargs):
190 188 super(TerminalInteractiveShell, self).__init__(*args, **kwargs)
191 189 self.init_prompt_toolkit_cli()
192 190 self.keep_running = True
193 191
194 192 def ask_exit(self):
195 193 self.keep_running = False
196 194
197 195 rl_next_input = None
198 196
199 197 def pre_prompt(self):
200 198 if self.rl_next_input:
201 199 self.pt_cli.application.buffer.text = cast_unicode_py2(self.rl_next_input)
202 200 self.rl_next_input = None
203 201
204 202 def interact(self):
205 203 while self.keep_running:
206 204 print(self.separate_in, end='')
207 205
208 206 try:
209 207 code = self.prompt_for_code()
210 208 except EOFError:
211 209 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'):
212 210 self.ask_exit()
213 211
214 212 else:
215 213 if code:
216 214 self.run_cell(code, store_history=True)
217 215
218 216 def mainloop(self):
219 217 # An extra layer of protection in case someone mashing Ctrl-C breaks
220 218 # out of our internal code.
221 219 while True:
222 220 try:
223 221 self.interact()
224 222 break
225 223 except KeyboardInterrupt:
226 224 print("\nKeyboardInterrupt escaped interact()\n")
227 225
228 226 _inputhook = None
229 227 def inputhook(self, context):
230 228 if self._inputhook is not None:
231 229 self._inputhook(context)
232 230
233 231 def enable_gui(self, gui=None):
234 232 if gui:
235 233 self._inputhook = get_inputhook_func(gui)
236 234 else:
237 235 self._inputhook = None
238 236
239 237 if __name__ == '__main__':
240 238 TerminalInteractiveShell.instance().interact()
@@ -1,295 +1,295
1 1 #!/usr/bin/env python
2 2 # -*- coding: utf-8 -*-
3 3 """Setup script for IPython.
4 4
5 5 Under Posix environments it works like a typical setup.py script.
6 6 Under Windows, the command sdist is not supported, since IPython
7 7 requires utilities which are not available under Windows."""
8 8
9 9 #-----------------------------------------------------------------------------
10 10 # Copyright (c) 2008-2011, IPython Development Team.
11 11 # Copyright (c) 2001-2007, Fernando Perez <fernando.perez@colorado.edu>
12 12 # Copyright (c) 2001, Janko Hauser <jhauser@zscout.de>
13 13 # Copyright (c) 2001, Nathaniel Gray <n8gray@caltech.edu>
14 14 #
15 15 # Distributed under the terms of the Modified BSD License.
16 16 #
17 17 # The full license is in the file COPYING.rst, distributed with this software.
18 18 #-----------------------------------------------------------------------------
19 19
20 20 #-----------------------------------------------------------------------------
21 21 # Minimal Python version sanity check
22 22 #-----------------------------------------------------------------------------
23 23 from __future__ import print_function
24 24
25 25 import sys
26 26
27 27 # This check is also made in IPython/__init__, don't forget to update both when
28 28 # changing Python version requirements.
29 29 v = sys.version_info
30 30 if v[:2] < (2,7) or (v[0] >= 3 and v[:2] < (3,3)):
31 31 error = "ERROR: IPython requires Python version 2.7 or 3.3 or above."
32 32 print(error, file=sys.stderr)
33 33 sys.exit(1)
34 34
35 35 PY3 = (sys.version_info[0] >= 3)
36 36
37 37 # At least we're on the python version we need, move on.
38 38
39 39 #-------------------------------------------------------------------------------
40 40 # Imports
41 41 #-------------------------------------------------------------------------------
42 42
43 43 # Stdlib imports
44 44 import os
45 45
46 46 from glob import glob
47 47
48 48 # BEFORE importing distutils, remove MANIFEST. distutils doesn't properly
49 49 # update it when the contents of directories change.
50 50 if os.path.exists('MANIFEST'): os.remove('MANIFEST')
51 51
52 52 from distutils.core import setup
53 53
54 54 # Our own imports
55 55 from setupbase import target_update
56 56
57 57 from setupbase import (
58 58 setup_args,
59 59 find_packages,
60 60 find_package_data,
61 61 check_package_data_first,
62 62 find_entry_points,
63 63 build_scripts_entrypt,
64 64 find_data_files,
65 65 git_prebuild,
66 66 install_symlinked,
67 67 install_lib_symlink,
68 68 install_scripts_for_symlink,
69 69 unsymlink,
70 70 )
71 71
72 72 isfile = os.path.isfile
73 73 pjoin = os.path.join
74 74
75 75 #-------------------------------------------------------------------------------
76 76 # Handle OS specific things
77 77 #-------------------------------------------------------------------------------
78 78
79 79 if os.name in ('nt','dos'):
80 80 os_name = 'windows'
81 81 else:
82 82 os_name = os.name
83 83
84 84 # Under Windows, 'sdist' has not been supported. Now that the docs build with
85 85 # Sphinx it might work, but let's not turn it on until someone confirms that it
86 86 # actually works.
87 87 if os_name == 'windows' and 'sdist' in sys.argv:
88 88 print('The sdist command is not available under Windows. Exiting.')
89 89 sys.exit(1)
90 90
91 91
92 92 #-------------------------------------------------------------------------------
93 93 # Things related to the IPython documentation
94 94 #-------------------------------------------------------------------------------
95 95
96 96 # update the manuals when building a source dist
97 97 if len(sys.argv) >= 2 and sys.argv[1] in ('sdist','bdist_rpm'):
98 98
99 99 # List of things to be updated. Each entry is a triplet of args for
100 100 # target_update()
101 101 to_update = [
102 102 ('docs/man/ipython.1.gz',
103 103 ['docs/man/ipython.1'],
104 104 'cd docs/man && gzip -9c ipython.1 > ipython.1.gz'),
105 105 ]
106 106
107 107
108 108 [ target_update(*t) for t in to_update ]
109 109
110 110 #---------------------------------------------------------------------------
111 111 # Find all the packages, package data, and data_files
112 112 #---------------------------------------------------------------------------
113 113
114 114 packages = find_packages()
115 115 package_data = find_package_data()
116 116
117 117 data_files = find_data_files()
118 118
119 119 setup_args['packages'] = packages
120 120 setup_args['package_data'] = package_data
121 121 setup_args['data_files'] = data_files
122 122
123 123 #---------------------------------------------------------------------------
124 124 # custom distutils commands
125 125 #---------------------------------------------------------------------------
126 126 # imports here, so they are after setuptools import if there was one
127 127 from distutils.command.sdist import sdist
128 128 from distutils.command.upload import upload
129 129
130 130 class UploadWindowsInstallers(upload):
131 131
132 132 description = "Upload Windows installers to PyPI (only used from tools/release_windows.py)"
133 133 user_options = upload.user_options + [
134 134 ('files=', 'f', 'exe file (or glob) to upload')
135 135 ]
136 136 def initialize_options(self):
137 137 upload.initialize_options(self)
138 138 meta = self.distribution.metadata
139 139 base = '{name}-{version}'.format(
140 140 name=meta.get_name(),
141 141 version=meta.get_version()
142 142 )
143 143 self.files = os.path.join('dist', '%s.*.exe' % base)
144 144
145 145 def run(self):
146 146 for dist_file in glob(self.files):
147 147 self.upload_file('bdist_wininst', 'any', dist_file)
148 148
149 149 setup_args['cmdclass'] = {
150 150 'build_py': \
151 151 check_package_data_first(git_prebuild('IPython')),
152 152 'sdist' : git_prebuild('IPython', sdist),
153 153 'upload_wininst' : UploadWindowsInstallers,
154 154 'symlink': install_symlinked,
155 155 'install_lib_symlink': install_lib_symlink,
156 156 'install_scripts_sym': install_scripts_for_symlink,
157 157 'unsymlink': unsymlink,
158 158 }
159 159
160 160
161 161 #---------------------------------------------------------------------------
162 162 # Handle scripts, dependencies, and setuptools specific things
163 163 #---------------------------------------------------------------------------
164 164
165 165 # For some commands, use setuptools. Note that we do NOT list install here!
166 166 # If you want a setuptools-enhanced install, just run 'setupegg.py install'
167 167 needs_setuptools = set(('develop', 'release', 'bdist_egg', 'bdist_rpm',
168 168 'bdist', 'bdist_dumb', 'bdist_wininst', 'bdist_wheel',
169 169 'egg_info', 'easy_install', 'upload', 'install_egg_info',
170 170 ))
171 171
172 172 if len(needs_setuptools.intersection(sys.argv)) > 0:
173 173 import setuptools
174 174
175 175 # This dict is used for passing extra arguments that are setuptools
176 176 # specific to setup
177 177 setuptools_extra_args = {}
178 178
179 179 # setuptools requirements
180 180
181 181 extras_require = dict(
182 182 parallel = ['ipyparallel'],
183 183 qtconsole = ['qtconsole'],
184 184 doc = ['Sphinx>=1.3'],
185 185 test = ['nose>=0.10.1', 'requests', 'testpath', 'pygments'],
186 186 terminal = [],
187 187 kernel = ['ipykernel'],
188 188 nbformat = ['nbformat'],
189 189 notebook = ['notebook', 'ipywidgets'],
190 190 nbconvert = ['nbconvert'],
191 191 )
192 192 install_requires = [
193 193 'setuptools>=18.5',
194 194 'decorator',
195 195 'pickleshare',
196 196 'simplegeneric>0.8',
197 197 'traitlets',
198 'prompt_toolkit', # We will require > 0.57 once a new release is made
198 'prompt_toolkit>=0.58',
199 199 ]
200 200
201 201 # Platform-specific dependencies:
202 202 # This is the correct way to specify these,
203 203 # but requires pip >= 6. pip < 6 ignores these.
204 204
205 205 extras_require.update({
206 206 ':sys_platform != "win32"': ['pexpect'],
207 207 ':sys_platform == "darwin"': ['appnope'],
208 208 'test:python_version == "2.7"': ['mock'],
209 209 })
210 210 # FIXME: re-specify above platform dependencies for pip < 6
211 211 # These would result in non-portable bdists.
212 212 if not any(arg.startswith('bdist') for arg in sys.argv):
213 213 if sys.version_info < (3, 3):
214 214 extras_require['test'].append('mock')
215 215
216 216 if sys.platform == 'darwin':
217 217 install_requires.extend(['appnope'])
218 218 have_readline = False
219 219 try:
220 220 import readline
221 221 except ImportError:
222 222 pass
223 223 else:
224 224 if 'libedit' not in readline.__doc__:
225 225 have_readline = True
226 226 if not have_readline:
227 227 install_requires.extend(['gnureadline'])
228 228
229 229 if sys.platform.startswith('win'):
230 230 extras_require['terminal'].append('pyreadline>=2.0')
231 231 else:
232 232 install_requires.append('pexpect')
233 233
234 234 # workaround pypa/setuptools#147, where setuptools misspells
235 235 # platform_python_implementation as python_implementation
236 236 if 'setuptools' in sys.modules:
237 237 for key in list(extras_require):
238 238 if 'platform_python_implementation' in key:
239 239 new_key = key.replace('platform_python_implementation', 'python_implementation')
240 240 extras_require[new_key] = extras_require.pop(key)
241 241
242 242 everything = set()
243 243 for key, deps in extras_require.items():
244 244 if ':' not in key:
245 245 everything.update(deps)
246 246 extras_require['all'] = everything
247 247
248 248 if 'setuptools' in sys.modules:
249 249 setuptools_extra_args['zip_safe'] = False
250 250 setuptools_extra_args['entry_points'] = {
251 251 'console_scripts': find_entry_points(),
252 252 'pygments.lexers': [
253 253 'ipythonconsole = IPython.lib.lexers:IPythonConsoleLexer',
254 254 'ipython = IPython.lib.lexers:IPythonLexer',
255 255 'ipython3 = IPython.lib.lexers:IPython3Lexer',
256 256 ],
257 257 }
258 258 setup_args['extras_require'] = extras_require
259 259 requires = setup_args['install_requires'] = install_requires
260 260
261 261 # Script to be run by the windows binary installer after the default setup
262 262 # routine, to add shortcuts and similar windows-only things. Windows
263 263 # post-install scripts MUST reside in the scripts/ dir, otherwise distutils
264 264 # doesn't find them.
265 265 if 'bdist_wininst' in sys.argv:
266 266 if len(sys.argv) > 2 and \
267 267 ('sdist' in sys.argv or 'bdist_rpm' in sys.argv):
268 268 print("ERROR: bdist_wininst must be run alone. Exiting.", file=sys.stderr)
269 269 sys.exit(1)
270 270 setup_args['data_files'].append(
271 271 ['Scripts', ('scripts/ipython.ico', 'scripts/ipython_nb.ico')])
272 272 setup_args['scripts'] = [pjoin('scripts','ipython_win_post_install.py')]
273 273 setup_args['options'] = {"bdist_wininst":
274 274 {"install_script":
275 275 "ipython_win_post_install.py"}}
276 276
277 277 else:
278 278 # scripts has to be a non-empty list, or install_scripts isn't called
279 279 setup_args['scripts'] = [e.split('=')[0].strip() for e in find_entry_points()]
280 280
281 281 setup_args['cmdclass']['build_scripts'] = build_scripts_entrypt
282 282
283 283 #---------------------------------------------------------------------------
284 284 # Do the actual setup now
285 285 #---------------------------------------------------------------------------
286 286
287 287 setup_args.update(setuptools_extra_args)
288 288
289 289
290 290
291 291 def main():
292 292 setup(**setup_args)
293 293
294 294 if __name__ == '__main__':
295 295 main()
General Comments 0
You need to be logged in to leave comments. Login now