domandinho
domandinho

Reputation: 1320

ipython - force executing of expression in any cursor position

I have ipython 5.3.0 and when i am in the middle of expression (cursor is marked as <cursor>), for example:

In [69]: x = np.arange(<cursor>1, 21, 2).reshape(2, 5)

Than pressing enter causes split this line into two lines.

In [69]: x = np.arange(                       
    ...: 1, 21, 2).reshape(2, 5)

But when i have cursor in other place for example:

 In [69]: x = np.<cursor>arange(1, 21, 2).reshape(2, 5)

It executes expression.

Which keyboard shortcut forces execution of expression without taking care of cursor position?

I tried CTRL + ENTER or SHIFT + ENTER but no one of them working for first example.

Upvotes: 3

Views: 201

Answers (1)

ivan_pozdeev
ivan_pozdeev

Reputation: 35998

This was fixed in IPython 5.4. Earlier, there's no way short of patching/monkey-patching at startup, but there's an easy workaround.

Here's the relevant logic from 5.4.1, in IPython/terminal/shortcuts.py. The fragment with a comment referring to the issue on the first link is the fix.

def newline_or_execute_outer(shell):
    def newline_or_execute(event):
        """When the user presses return, insert a newline or execute the code."""
        b = event.current_buffer
        d = b.document

        if b.complete_state:
            cc = b.complete_state.current_completion
            if cc:
                b.apply_completion(cc)
            else:
                b.cancel_completion()
            return

        # If there's only one line, treat it as if the cursor is at the end.
        # See https://github.com/ipython/ipython/issues/10425
        if d.line_count == 1:
            check_text = d.text
        else:
            check_text = d.text[:d.cursor_position]
        status, indent = shell.input_splitter.check_complete(check_text + '\n')

        if not (d.on_last_line or
                d.cursor_position_row >= d.line_count - d.empty_line_count_at_the_end()
                ):
            b.insert_text('\n' + (' ' * (indent or 0)))
            return

        if (status != 'incomplete') and b.accept_action.is_returnable:
            b.accept_action.validate_and_handle(event.cli, b)
        else:
            b.insert_text('\n' + (' ' * (indent or 0)))
    return newline_or_execute

As you can see, the action depends on the cursor's position relevant to a code's token.

So, if you have a complete statement, you can force execution by simply pressing End before Enter.

Upvotes: 1

Related Questions