在诅咒中显示带有尾随空格的文本

2024-06-16 13:03:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我现在正在做一个文本编辑器,这是我不太明白的奇怪之处之一!你知道吗

我将从一个小的演示脚本开始,它减少了问题

import curses


def c_main(stdscr):
    lines = (
        'welcome to my simulation!',
        'this line has trailing whitespace:    ',
        'q: quit',
        'r: full redraw (removes trailing ws?)',
        '',
    )
    x = y = 0

    while True:
        # RENDERING
        for i, line in enumerate(lines):
            stdscr.insstr(i, 0, lines[i].ljust(curses.COLS))
        # END RENDERING

        stdscr.move(y, x)

        wch = stdscr.get_wch()
        if wch == curses.KEY_RESIZE:
            curses.update_lines_cols()
        elif wch == curses.KEY_RIGHT:
            x += 1
            if x > len(lines[y]):
                x = 0
                y = min(y + 1, len(lines) - 1)
        elif wch == curses.KEY_LEFT:
            if x != 0 or y != 0:
                x -= 1
                if x < 0:
                    y = max(y - 1, 0)
                    x = len(lines[y])
        elif wch == curses.KEY_DOWN:
            y = min(y + 1, len(lines) - 1)
            x = min(x, len(lines[y]))
        elif wch == curses.KEY_UP:
            y = max(y - 1, 0)
            x = min(x, len(lines[y]))
        elif wch == 'r':
            stdscr.move(0, 0)
            for i in range(len(lines)):
                stdscr.insstr(i, 0, ' ' * curses.COLS)
            stdscr.refresh()
        elif wch == 'q':
            return


if __name__ == '__main__':
    exit(curses.wrapper(c_main))

那里的大部分代码都是这样的,你可以用箭头键来演示这个问题。实际的呈现代码用# RENDERING注释标记。你知道吗


演示问题:

  1. python3 demo.py开始脚本
  2. 用鼠标高亮显示第二行--请注意,尾随空格不可高亮显示
  3. 将光标导航到第二行的末尾(最短组合是downdownleft
  4. ,然后按(不确定原因,这是生成可复制指令所必需的)
  5. 离开第二行的末尾(最短的组合是向下
  6. 现在请注意,尾随的空格可以高亮显示
  7. r触发完全重画
  8. 请再次注意,尾随空格不可高亮显示

所以问题是,如何正确地呈现尾随空格,以便从终端粘贴的副本保留该内容(并且不需要用户在那里导航光标)


Tags: key脚本lenifmainlinemincurses