10

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?

Manuel Ebert
  • 8,429
  • 4
  • 40
  • 61

4 Answers4

2

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)
Jiri
  • 16,425
  • 6
  • 52
  • 68
1

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.

Christian Witts
  • 11,375
  • 1
  • 33
  • 46
1

I think that with minimal effort you can use urwid library for Python. Unfortunately, this does not satisfy your requirement to use readline/raw_input.

Update: Please see also this answer for other solution.

Community
  • 1
  • 1
Jiri
  • 16,425
  • 6
  • 52
  • 68
0
import readline
# I am using Ctrl+x to insert line break 
# (dont know the symbols and bindings for meta-key or shift-key,  
# let alone 4 shift+enter)

def startup_hook():
    readline.insert_text('» ') # \033[32m»\033[0m

def prmpt():
try:
    readline.parse_and_bind('tab: complete')
    readline.parse_and_bind('set editing-mode vi')
    readline.parse_and_bind('C-x: "\x16\n"') # \x16 is C-v which writes
    readline.set_startup_hook(startup_hook) # the \n without returning
except Exception as e:                      # thus no need 4 appending
    print (e)                              # '#' 2 write multilines
    return                # simply use ctrl-x or other some other bind
while True:             # instead of shift + enter
    try:
        line = raw_input()
        print '%s' % line
    except EOFError:
        print 'EOF signaled, exiting...'
        break

# It can probably be improved more to use meta+key or maybe even shift enter 
# Anyways sry 4 any errors I probably may have made.. first time answering 
Whitehead
  • 13
  • 4