Skip to content

Commit b3088c7

Browse files
committed
Merge branch '2.0'
2 parents d01fbe9 + 2d26b58 commit b3088c7

16 files changed

Lines changed: 575 additions & 709 deletions

.travis.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ install:
2222
# Useful for debugging any issues with conda
2323
- conda info -a
2424

25-
- conda create -q -n test-environment python=$CONDA_PY 'prompt_toolkit<2' pygments pyflakes pytest iterm2-tools catimg matplotlib jedi sympy seaborn pudb
25+
- conda create -q -n test-environment python=$CONDA_PY prompt_toolkit pygments pyflakes pytest iterm2-tools catimg matplotlib jedi sympy seaborn pudb
2626
- source activate test-environment
2727

2828
script:

2.0-TODO.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
- Make all keybindings assign a Document
2+
- Figure out how to set the prompt-toolkit exception handler
3+
- Jedi warnings printed to terminal during completion
4+
- Fix tests
5+
- Replace "cli" with "app" in the key bindings
6+
- accept_after_history_backward doesn't work
7+
- Ask about fixing selection

TODO.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141
- Issues pasting multiple prompts with emoji prompts
4242
- Make the command queue not use input
4343
- Should not allow newline inside single quote string, even in multiline
44+
- Forward/backward sexp doesn't work unless it's on a parenthesis
4445
- Print %time time after the output
4546
- Add line profiler magic
4647
- Prompt number not incremented when %pudb exits with traceback

conftest.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# Enable the fixture
2+
from mypython.tests.test_mypython import check_output; check_output

mypython/__init__.py

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,24 @@
1-
from .mypython import (validate_text, PythonSyntaxValidator,
2-
get_continuation_tokens, prompt_style, get_in_prompt_tokens,
3-
get_out_prompt_tokens, NoResult, smart_eval, normalize, startup,
4-
execute_command, run_shell, myhelp, getsource)
1+
from .mypython import (validate_text, PythonSyntaxValidator, prompt_style,
2+
NoResult, smart_eval, normalize, execute_command, run_shell, myhelp,
3+
getsource, Session)
54

6-
__all__ = ['validate_text', 'PythonSyntaxValidator', 'get_continuation_tokens', 'prompt_style',
7-
'get_in_prompt_tokens', 'get_out_prompt_tokens', 'NoResult', 'smart_eval',
8-
'normalize', 'startup', 'execute_command', 'run_shell', 'myhelp', 'getsource']
5+
__all__ = ['validate_text', 'PythonSyntaxValidator', 'prompt_style',
6+
'NoResult', 'smart_eval', 'normalize', 'execute_command',
7+
'run_shell', 'myhelp', 'getsource', 'Session']
98

10-
from .keys import get_registry, custom_bindings_registry, split_prompts
9+
from .keys import get_key_bindings, custom_key_bindings, split_prompts
1110

12-
__all__ += ['get_registry', 'custom_bindings_registry', 'split_prompts']
11+
__all__ += ['get_key_bindings', 'custom_key_bindings', 'split_prompts']
1312

1413
from .theme import OneAMStyle
1514

1615
__all__ += ['OneAMStyle']
1716

1817
from .multiline import (document_is_multiline_python, auto_newline,
19-
TabShouldInsertWhitespaceFilter)
18+
tab_should_insert_whitespace)
2019

2120
__all__ += ['document_is_multiline_python',
22-
'auto_newline', 'TabShouldInsertWhitespaceFilter']
21+
'auto_newline', 'tab_should_insert_whitespace']
2322

2423
from .completion import get_jedi_script_from_document, PythonCompleter
2524

mypython/completion.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,11 +34,11 @@
3434
from .dircompletion import DirCompleter
3535
from .magic import MAGICS
3636

37-
def get_jedi_script_from_document(document, _locals, _globals):
37+
def get_jedi_script_from_document(document, _locals, _globals, session):
3838
import jedi # We keep this import in-line, to improve start-up time.
3939
# Importing Jedi is 'slow'.
4040

41-
full_document = '\n'.join(i for _, i in sorted(_locals['_CLI'].builtins['In'].items()))
41+
full_document = '\n'.join(i for _, i in sorted(session.builtins['In'].items()))
4242
if not full_document.endswith('\n'):
4343
full_document += '\n'
4444

@@ -57,11 +57,12 @@ class PythonCompleter(Completer):
5757
"""
5858
Completer for Python code.
5959
"""
60-
def __init__(self, get_globals, get_locals):
60+
def __init__(self, get_globals, get_locals, session):
6161
super(PythonCompleter, self).__init__()
6262

6363
self.get_globals = get_globals
6464
self.get_locals = get_locals
65+
self.session = session
6566

6667
def _complete_python_while_typing(self, document):
6768
char_before_cursor = document.char_before_cursor
@@ -104,7 +105,8 @@ def get_completions(self, document, complete_event):
104105
else:
105106
break
106107

107-
script = get_jedi_script_from_document(document, self.get_locals(), self.get_globals())
108+
script = get_jedi_script_from_document(document,
109+
self.get_locals(), self.get_globals(), self.session)
108110

109111
if script:
110112
try:

mypython/keys.py

Lines changed: 41 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,21 @@
11
from prompt_toolkit.key_binding.bindings.named_commands import (accept_line,
22
self_insert, backward_delete_char, beginning_of_line)
33
from prompt_toolkit.key_binding.bindings.basic import if_no_repeat
4-
from prompt_toolkit.key_binding.defaults import load_key_bindings
5-
from prompt_toolkit.key_binding.registry import Registry, MergedRegistry
6-
from prompt_toolkit.keys import Keys, Key
4+
from prompt_toolkit.key_binding.bindings.basic import load_basic_bindings
5+
from prompt_toolkit.key_binding.bindings.emacs import load_emacs_bindings, load_emacs_search_bindings
6+
from prompt_toolkit.key_binding.bindings.mouse import load_mouse_bindings
7+
from prompt_toolkit.key_binding.bindings.cpr import load_cpr_bindings
8+
9+
from prompt_toolkit.key_binding import KeyBindings, merge_key_bindings
10+
from prompt_toolkit.keys import Keys, ALL_KEYS
711
from prompt_toolkit.filters import Condition, HasSelection
812
from prompt_toolkit.selection import SelectionState
913
from prompt_toolkit.clipboard import ClipboardData
10-
from prompt_toolkit.terminal.vt100_input import ANSI_SEQUENCES
14+
from prompt_toolkit.input.vt100_parser import ANSI_SEQUENCES
15+
from prompt_toolkit.application.current import get_app
16+
from prompt_toolkit.application import run_in_terminal
1117

12-
from .multiline import (auto_newline, TabShouldInsertWhitespaceFilter,
18+
from .multiline import (auto_newline, tab_should_insert_whitespace,
1319
document_is_multiline_python)
1420
from .tokenize import inside_string, matching_parens
1521
from .theme import emoji
@@ -19,24 +25,21 @@
1925
import sys
2026
import textwrap
2127

22-
def get_registry():
23-
registry = MergedRegistry([
24-
load_key_bindings(
25-
enable_abort_and_exit_bindings=True,
26-
enable_search=True,
27-
# Not using now but may in the future
28-
enable_auto_suggest_bindings=True,
29-
enable_extra_page_navigation=True,
30-
# Custom one defined below, without execute
31-
enable_open_in_editor=False,
32-
enable_system_bindings=True,
33-
),
34-
custom_bindings_registry,
35-
])
28+
def get_key_bindings():
29+
# Based on prompt_toolkit.key_binding.defaults.load_key_bindings()
30+
return merge_key_bindings([
31+
load_basic_bindings(),
32+
33+
load_emacs_bindings(),
34+
load_emacs_search_bindings(),
3635

37-
return registry
36+
load_mouse_bindings(),
37+
load_cpr_bindings(),
3838

39-
r = custom_bindings_registry = Registry()
39+
custom_key_bindings,
40+
])
41+
42+
r = custom_key_bindings = KeyBindings()
4043

4144
@r.add_binding(Keys.Escape, 'p')
4245
def previous_history_search(event):
@@ -276,10 +279,14 @@ def right_multiline(event):
276279

277280
@r.add_binding(Keys.ControlD)
278281
def exit(event):
279-
raise EOFError("Control-D")
282+
event.app.exit(exception=EOFError, style='class:exiting')
283+
284+
@r.add_binding(Keys.ControlC)
285+
def keyboard_interrupt(event):
286+
event.app.exit(exception=KeyboardInterrupt, style='class:aborting')
280287

281288
is_returnable = Condition(
282-
lambda cli: cli.current_buffer.accept_action.is_returnable)
289+
lambda: get_app().current_buffer.is_returnable)
283290

284291
@r.add_binding(Keys.Enter, filter=is_returnable)
285292
def multiline_enter(event):
@@ -320,14 +327,15 @@ def multiline_enter(event):
320327
@r.add_binding(Keys.Enter, filter=is_returnable)
321328
def accept_after_history_backward(event):
322329
pks = event.previous_key_sequence
323-
if pks and getattr(pks[-1], 'accept_next', False) and ((len(pks) == 1 and isinstance(pks[0].key, Key) and pks[0].key.name == "<Up>") \
324-
or (len(pks) == 2 and isinstance(pks[0].key, Key) and pks[0].key.name == "<Escape>"
325-
and isinstance(pks[1].key, str) and pks[1].key in 'pP')):
330+
if pks and getattr(pks[-1], 'accept_next', False) and ((len(pks) == 1 and
331+
pks[0].key == "<Up>") or (len(pks) == 2 and pks[0].key == "<Escape>"
332+
and isinstance(pks[1].key, str) and pks[1].key in 'pP')):
326333
accept_line(event)
327334
else:
328335
multiline_enter(event)
329336

330337
@r.add_binding(Keys.Escape, Keys.Enter)
338+
@r.add_binding(Keys.Escape, Keys.ControlJ)
331339
def insert_newline(event):
332340
auto_newline(event.current_buffer)
333341

@@ -337,12 +345,13 @@ def open_line(event):
337345
event.current_buffer.cursor_left()
338346

339347
# M-[ a g is set to S-Enter in iTerm2 settings
340-
Keys.ShiftEnter = Key("<Shift-Enter>")
348+
Keys.ShiftEnter = "<Shift-Enter>"
349+
ALL_KEYS.append('<Shift-Enter>')
341350
ANSI_SEQUENCES['\x1b[ag'] = Keys.ShiftEnter
342351

343352
r.add_binding(Keys.ShiftEnter)(accept_line)
344353

345-
@r.add_binding(Keys.Tab, filter=TabShouldInsertWhitespaceFilter())
354+
@r.add_binding(Keys.Tab, filter=tab_should_insert_whitespace)
346355
def indent(event):
347356
"""
348357
When tab should insert whitespace, do that instead of completion.
@@ -641,7 +650,7 @@ def osx_paste():
641650
def copy_to_clipboard(event):
642651
if event.current_buffer.document.selection:
643652
from_, to = event.current_buffer.document.selection_range()
644-
event.cli.run_in_terminal(lambda:osx_copy(event.current_buffer.document.text[from_:to + 1]))
653+
run_in_terminal(lambda:osx_copy(event.current_buffer.document.text[from_:to + 1]))
645654

646655
@r.add_binding(Keys.ControlX, Keys.ControlY)
647656
def paste_from_clipboard(event):
@@ -650,13 +659,14 @@ def get_paste():
650659
nonlocal paste_text
651660
paste_text = osx_paste()
652661

653-
event.cli.run_in_terminal(get_paste)
662+
run_in_terminal(get_paste)
654663

655664
event.current_buffer.cut_selection()
656665
event.current_buffer.paste_clipboard_data(ClipboardData(paste_text))
657666

658667
# M-[ a b is set to C-S-/ (C-?) in iTerm2 settings
659-
Keys.ControlQuestionmark = Key("<C-?>")
668+
Keys.ControlQuestionmark = "<C-?>"
669+
ALL_KEYS.append("<C-?>")
660670
ANSI_SEQUENCES['\x1b[ab'] = Keys.ControlQuestionmark
661671

662672
# This won't work until

mypython/magic.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -177,7 +177,7 @@ def history_magic(rest):
177177
import pygments as _pygments
178178
from mypython.theme import OneAMStyle as _OneAMStyle, MyPython3Lexer as _MyPython3Lexer
179179
from mypython.mypython import blue as _blue
180-
_pydoc.pipepager('\\n'.join(_pygments.highlight(i, _MyPython3Lexer(), _pygments.formatters.TerminalTrueColorFormatter(style=_OneAMStyle))+_blue('-'*80) for i in _CLI.current_buffer.history.strings), 'less +G')
180+
_pydoc.pipepager('\\n'.join(_pygments.highlight(i, _MyPython3Lexer(), _pygments.formatters.TerminalTrueColorFormatter(style=_OneAMStyle))+_blue('-'*80) for i in _PROMPT.current_buffer.history.strings), 'less +G')
181181
del _pydoc, _pygments, _OneAMStyle, _MyPython3Lexer, _blue
182182
"""
183183

@@ -196,7 +196,7 @@ def pudb_magic(rest):
196196
import bdb as _bdb
197197
import linecache as _linecache
198198
199-
_filename = '<mypython-pudb-%s>' % _CLI.builtins['PROMPT_NUMBER']
199+
_filename = '<mypython-pudb-%s>' % PROMPT_NUMBER
200200
201201
_pudb._get_debugger().breaks.setdefault(_filename, [1])
202202
# Instantiating the Breakpoint class enables the breakpoint. We can't use

mypython/multiline.py

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,8 @@
3030
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3131
"""
3232

33-
from prompt_toolkit.filters import Filter
33+
from prompt_toolkit.application.current import get_app
34+
from prompt_toolkit.filters.base import Condition
3435

3536
from .tokenize import is_multiline_python
3637

@@ -78,14 +79,11 @@ def auto_newline(buffer):
7879
for x in range(4):
7980
insert_text(' ')
8081

81-
class TabShouldInsertWhitespaceFilter(Filter):
82-
"""
83-
When the 'tab' key is pressed with only whitespace character before the
84-
cursor, insert indentation. Otherwise, do autocompletion.
82+
@Condition
83+
def tab_should_insert_whitespace():
84+
app = get_app()
8585

86-
"""
87-
def __call__(self, cli):
88-
b = cli.current_buffer
89-
before_cursor = b.document.current_line_before_cursor
86+
b = app.current_buffer
87+
before_cursor = b.document.current_line_before_cursor
9088

91-
return bool(not before_cursor or before_cursor.isspace())
89+
return bool(not before_cursor or before_cursor.isspace())

0 commit comments

Comments
 (0)