xralf
xralf

Reputation: 3642

Switch to vim like editor interactivelly to change a Python string

I have the following source code:

import sys, os
import curses
import textwrap

if __name__ == "__main__":
  curses.setupterm()
  sys.stdout.write(curses.tigetstr('civis'))
  os.system("clear")
  str = "abcdefghijklmnopqrstuvwxyz" * 10 # only example
  for line in textwrap.wrap(str, 60):
    os.system("clear")
    print "\n" * 10
    print line.center(150)
    sys.stdin.read(1) # read one character or #TODO
    #TODO 
    # x = getc() # getc() gets one character from keyboard (already done)
    # if x == "e": # edit
    #    updatedString = runVim(line)
    #    str.replace(line, updatedString)

  sys.stdout.write(curses.tigetstr('cnorm'))

The program moves through the string by 60 characters. I would like to have editing possibility (in the #TODO place) in case I want to change the string just displayed.

Is it possible to open a small vim buffer when I press a key? I would make an edit and when I press :w it would update the string. I would like the vim editor not to change the position of the string in the terminal (I'd like it centered).

Upvotes: 0

Views: 288

Answers (3)

xralf
xralf

Reputation: 3642

def runVim(ln):
  with tempfile.NamedTemporaryFile(suffix=".txt") as tmp:
    tmp.write(ln)
    tmp.flush()
    call(['vim', '+1', '-c set filetype=txt', tmp.name]) # for centering +1 can be changed
    with open(tmp.name, 'r') as f:
      lines = f.read()
  return lines


...
x = getch()
  if x == "e":
    updatedString = runVim(line)
    str = str.replace(line, updatedString)
print str
...

Upvotes: 1

Thomas Dickey
Thomas Dickey

Reputation: 54515

Not exactly: you can't do it that way. Programs generally cannot read what you printed to the screen.

You could make a program which displays text on the screen and (knowing what it wrote) pass that information to an editor. For instance, lynx (an application using curses) displays a formatted HTML page on the screen, and provides a feature which passes the content of a form text-field to an editor, reads the updated file from the editor and redisplays the information in the form.

Upvotes: 0

SibiCoder
SibiCoder

Reputation: 1496

Idea:

Let us choose \o and \w for our purpose. Keep the cursor on "TO DO" or any other word you like and press \o. Then, it opens new tab. You can write anything in new buffer and then press \w. It will copy the whole thing and close the buffer and then pastes in the cursor position in current buffer.

Mapping

   :nmap \o cw<ESC>:tabnew<CR>
   :nmap \w ggvG"wy:tabclose<CR>"wp

Upvotes: 0

Related Questions