问题描述
我正在尝试使用 Python 和 Curses 的文本编辑器。这是代码。
import curses
import sys
import argparse
class Cursor:
def __init__(self,row=0,col=0,col_hint=None):
self.row = row
self._col = col
self._col_hint = col if col_hint is None else col_hint
@property
def col(self):
return self._col
@col.setter
def col(self,col):
self._col = col
self._col_hint = col
def up(self,buffer):
if self.row > 0:
self.row -= 1
self._clamp_col(buffer)
def down(self,buffer):
if self.row < len(buffer) - 1:
self.row += 1
self._clamp_col(buffer)
def _clamp_col(self,buffer):
self._col = min(self._col_hint,len(buffer[self.row]))
def left(self,buffer):
if self.col > 0:
self.col -= 1
elif self.row > 0:
self.row -= 1
self.col = len(buffer[self.row])
def right(self,buffer):
if self.col < len(buffer[self.row]):
self.col -= 1
elif self.row < len(buffer) - 1:
self.row += 1
self.col = 0
class Window:
def __init__(self,n_rows,n_cols,col=0):
self.n_rows = n_rows
self.n_cols = n_cols
self.row = row
self.col = col
@property
def bottom(self):
return self.row + self.n_rows - 1
def up(self,cursor):
if cursor.row == self.row - 1 and self.row > 0:
self.row -= 1
def down(self,buffer,cursor):
if cursor.row == self.bottom + 1 and self.bottom < buffer.bottom:
self.row += 1
def translate(self,cursor):
return cursor.row - self.row,cursor.col - self.col
def horizontal_scroll(self,cursor,left_margin=5,right_margin=2):
n_pages = cursor.col // (self.n_cols - right_margin)
self.col = max(n_pages * self.n_cols - right_margin - left_margin,0)
def main(stdscr):
parser = argparse.ArgumentParser()
parser.add_argument("filename")
args = parser.parse_args()
window = Window(curses.LInes - 1,curses.COLS - 1)
cursor = Cursor()
with open(args.filename) as f:
buffer = f.readlines()
while True:
stdscr.erase()
for row,line in enumerate(buffer[window.row:window.row + window.n_rows]):
if row == cursor.row - window.row and window.col > 0:
line = "«" + line[window.col + 1:]
if len(line) > window.n_cols:
line = line[:window.n_cols - 1] + "»"
stdscr.addstr(row,line)
stdscr.move(*window.translate(cursor))
k = stdscr.getkey()
if k == "q":
sys.exit(0)
elif k == "KEY_UP":
cursor.up()
window.up(cursor)
window.horizontal_scroll(cursor)
elif k == "KEY_DOWN":
cursor.down(buffer)
window.down(buffer,cursor)
window.horizontal_scroll(cursor)
elif k == "KEY_LEFT":
cursor.left()
window.up(cursor)
window.horizontal_scroll(cursor)
elif k == "KEY_RIGHT":
cursor.right(buffer)
window.down(buffer,cursor)
window.horizontal_scroll(cursor)
if __name__ == "__main__":
curses.wrapper(main)
我想显示文件的所有内容。它只显示到窗口大小。另外,我无法左右移动光标。你能帮我看看我哪里出错了。谢谢。
以上代码来自https://wasimlorgat.com/editor链接。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)