像编辑器一样切换到 vim 以交互方式更改 Python 字符串

Switch to vim like editor interactivelly to change a Python string

我有以下源代码:

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

程序在字符串中移动 60 个字符。 我希望有编辑的可能性(在#TODO 地方)以防万一 我想更改刚刚显示的字符串。

是否可以在我按键时打开一个小的vim缓冲区?我会进行编辑,当我按 :w 时,它会更新字符串。我希望 vim 编辑器不要更改终端中字符串的位置(我希望它居中)。

想法:

让我们选择 \o\w 作为我们的目的。 将光标停留在 "TO DO" 或您喜欢的任何其他词上,然后按 \o。 然后,它打开新标签。您可以在新缓冲区中写入任何内容,然后按 \w。它将复制整个内容并关闭缓冲区,然后粘贴到当前缓冲区中的光标位置。

映射

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

不完全是:你不能那样做。程序通常无法读取您打印到屏幕上的内容。

可以制作一个在屏幕上显示文本的程序,并且(知道它写了什么)将该信息传递给编辑器。例如,lynx(使用 curses 的应用程序)在屏幕上显示格式化的 HTML 页面,并提供将表单文本字段的内容传递给编辑器的功能,从中读取更新的文件编辑器并重新显示表单中的信息。

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