Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shift + Return to insert linebreak in python

I'm trying to get the behaviour of typical IM clients that use Return to send a text and Shift + Return to insert a linebreak. Is there a way to achieve that with minimal effort in Python, using e.g. readline and raw_input?

like image 484
Manuel Ebert Avatar asked Jul 05 '12 11:07

Manuel Ebert


People also ask

How do you insert a line break in Python?

In Python, the new line character “\n” is used to create a new line. When inserted in a string all the characters after the character are added to a new line. Essentially the occurrence of the “\n” indicates that the line ends here and the remaining characters would be displayed in a new line.

What is r n in Python?

"\r\n" is the default Windows style for line separator. "\r" is classic Mac style for line separator.

How do you break a long string in Python?

If you have a very long line of code in Python and you'd like to break it up over over multiple lines, if you're inside parentheses, square brackets, or curly braces you can put line breaks wherever you'd like because Python allows for implicit line continuation.


2 Answers

Ok, I heard it can be accomplished also with the readline, in a way.

You can import readline and set in configuration your desired key (Shift+Enter) to a macro that put some special char to the end of the line and newline. Then you can call raw_input in a loop.

Like this:

import readline    
# I am using Ctrl+K to insert line break 
# (dont know what symbol is for shift+enter)
readline.parse_and_bind('C-k: "#\n"')
text = []
line = "#"
while line and line[-1]=='#':
  line = raw_input("> ")
  if line.endswith("#"):
    text.append(line[:-1])
  else:
    text.append(line)

# all lines are in "text" list variable
print "\n".join(text)
like image 115
Jiri Avatar answered Oct 24 '22 18:10

Jiri


I doubt you'd be able to do that just using the readline module as it will not capture the individual keys pressed and rather just processes the character responses from your input driver.

You could do it with PyHook though and if the Shift key is pressed along with the Enter key to inject a new-line into your readline stream.

like image 34
Christian Witts Avatar answered Oct 24 '22 18:10

Christian Witts