Search code examples
pythonvimcurses

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).


Solution

  • 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
    ...