1

IPython since version 5 onward uses prompt_toolkit instead of readline, and I am trying to use its implementation of this package to enable auto closing of double quotes, parentheses and brackets. I have got as far as this code:

ip = get_ipython()
kb = ip.pt_app.key_bindings
@kb.add('"')
def _(event):
    buffer = event.current_buffer
    buffer.insert_text('"')
    buffer.insert_text('"')

This doesn't work correctly, as it merely inputs the two quotes, with the cursor positioned after them. The buffer object does not seem to have a method for moving the cursor back. There is a document object though, that the buffer contains, which has methods for inserting text before or after the cursor position. So amending the code:

ip = get_ipython()
kb = ip.pt_app.key_bindings
@kb.add('"') 
def _(event): 
    buffer = event.current_buffer 
    doc = buffer.document 
    doc.insert_before('"') 
    doc.insert_after('"')

This produces no output when '"' is pressed on the keyboard. I gather from the prompt_toolkit documentation, that the document should now be rendered to the screen, but I'm lost as to how to get this done. All help appreciated!

Theo d'Or
  • 783
  • 1
  • 4
  • 17

1 Answers1

1

I have found the solution to the immediate problem - my code was missing a parameter:

def _(event):
    buffer = event.current_buffer
    buffer.insert_text('"')
    buffer.insert_text('"', move_cursor=False)

A fuller answer regarding the rendering of the document object would still be appreciated, as that will be required for other related operations, such as deleting the matched quotes.

Theo d'Or
  • 783
  • 1
  • 4
  • 17