переписал на списках списков MyString

rewrite-MyString-class
serr 2025-02-11 11:45:28 +03:00
parent 3e9adc3c11
commit fb17042f98
2 changed files with 20 additions and 17 deletions

View File

@ -17,8 +17,8 @@ class VimModel:
displayColsCount: int
showLineNumbers: bool
lastSearch: tuple[str, int] # tuple (search str, direction)
displayBuffer: List[List[str]]
dump: List[List[str]]
displayBuffer: List[List[MyString]]
dump: List[List[MyString]]
currentLine: int
currentCol: int
scrollY: int
@ -27,8 +27,8 @@ class VimModel:
mode: MyString
inputAfterCursor: bool
keyLog: List[tuple[int, int]] # key log for check combinations (tuples (symbol code, tap unix time))
commandBuffer: List[str] # buffer for command
exchangeBuffer: List[str] # buffer for exchange
commandBuffer: List[MyString] # buffer for command
exchangeBuffer: List[MyString] # buffer for exchange
def __init__(self, displayLinesCount: int, displayColsCount: int):
self.observers = []
@ -79,7 +79,7 @@ class VimModel:
def ModeBar(self) -> str:
modeBar = f"MODE: {self.mode.data()} | FILE: {self.file_path.data()} | LINE: {self.currentLine+1}/{len(self.displayBuffer)}"
if self.mode == MyString("COMMAND"):
modeBar += f" | COMMAND BUFFER: {''.join(self.commandBuffer)}"
modeBar += f" | COMMAND BUFFER: {''.join(item.data() for item in self.commandBuffer)}"
return modeBar
def Scroll(self) -> None:
@ -101,16 +101,16 @@ class VimModel:
self.scrollX = self.currentCol - visible_text_width + 1
def InsertCommandSymbol(self, symbolCode: int) -> None:
self.commandBuffer.append(chr(symbolCode))
self.commandBuffer.append(MyString(chr(symbolCode)))
def InsertSymbol(self, symbolCode: int) -> None:
if self.currentCol <= len(self.displayBuffer[self.currentLine]): # проверяем, не превышает ли индекс колонки длину строки
self.displayBuffer[self.currentLine].insert(self.currentCol, chr(symbolCode))
self.displayBuffer[self.currentLine].insert(self.currentCol, MyString(chr(symbolCode)))
self.currentCol += 1
def InsertSymbolAfterCursor(self, symbolCode: int) -> None:
if self.currentCol <= len(self.displayBuffer[self.currentLine]): # проверяем, не превышает ли индекс колонки длину строки
self.displayBuffer[self.currentLine].insert(self.currentCol, chr(symbolCode))
self.displayBuffer[self.currentLine].insert(self.currentCol, MyString(chr(symbolCode)))
def ToLineStart(self) -> None:
self.currentCol = 0
@ -119,7 +119,7 @@ class VimModel:
self.currentCol = len(self.displayBuffer[self.currentLine])
def ToWordEnd(self) -> None:
line = ''.join(self.displayBuffer[self.currentLine])
line = ''.join(item.data() for item in self.displayBuffer[self.currentLine])
# Находим ближайший непробельный символ
non_space_index = next((i for i, char in enumerate(line[self.currentCol:]) if char != ' '), None)
if non_space_index is not None:
@ -128,7 +128,7 @@ class VimModel:
self.currentCol = right_space_index if right_space_index != -1 else len(line)
def ToWordStart(self) -> None:
line = ''.join(self.displayBuffer[self.currentLine])
line = ''.join(item.data() for item in self.displayBuffer[self.currentLine])
non_space_index = next((i for i in range(self.currentCol - 1, -1, -1) if line[i] != ' '), None)
if non_space_index is not None:
left_space_index = line.rfind(' ', 0, non_space_index)
@ -163,7 +163,7 @@ class VimModel:
def DeleteWord(self) -> None:
start_index, end_index = self.WordUnderCursor()
line = self.displayBuffer[self.currentLine]
if end_index < len(line) and line[end_index] == ' ':
if end_index < len(line) and line[end_index] == MyString(' '):
end_index += 1
self.displayBuffer[self.currentLine] = line[:start_index] + line[end_index:]
self.currentCol = start_index
@ -192,7 +192,7 @@ class VimModel:
def EnterCommand(self):
"""Обработка введенной команды"""
cmd = ''.join(self.commandBuffer)
cmd = ''.join(item.data() for item in self.commandBuffer)
self.commandBuffer.clear()
match cmd:
case "q": # Выход из программы
@ -245,6 +245,8 @@ class VimModel:
self.lastSearch = (self.lastSearch[0], (self.lastSearch[1]+1)%2)
case "e!":
self.displayBuffer = [sublist.copy() for sublist in self.dump]
self.currentCol = 0
self.currentLine = 0
case "set num":
self.showLineNumbers = not self.showLineNumbers
case _:
@ -288,7 +290,7 @@ class VimModel:
def WordUnderCursor(self)-> tuple[int, int]:
"""Возвращает индекс начала и индекс конца слова под курсором"""
line = ''.join(self.displayBuffer[self.currentLine])
line = ''.join(item.data() for item in self.displayBuffer[self.currentLine])
start_index = line.rfind(' ', 0, self.currentCol)
start_index = 0 if start_index == -1 else start_index + 1
end_index = line.find(' ', self.currentCol)
@ -358,7 +360,7 @@ class VimModel:
self.mode = MyString("NORMAL")
try:
with open(file_path.data(), "r") as file:
self.displayBuffer = [list(line.rstrip('\n')) for line in file.readlines()]
self.displayBuffer = [[MyString(char) for char in line.rstrip('\n')] for line in file.readlines()]
self.Dump()
except FileNotFoundError:
print(f"File '{file_path.data()}' not found. Starting with empty buffer.")
@ -374,7 +376,7 @@ class VimModel:
try:
with open(file_path.data(), "w") as file:
for line in self.displayBuffer:
file.write(''.join(line) + '\n')
file.write(''.join(item.data() for item in line) + '\n')
self.Dump()
print(f"In file '{file_path.data()}' written successfully.")
except Exception as e:

View File

@ -1,6 +1,7 @@
from abc import ABC, abstractmethod
import curses
import mvc.models
from mystring import MyString as MyString
class CursesAdapter:
def __init__(self) -> None:
@ -93,7 +94,7 @@ class VimView(Observer):
)
def Render(self,
displayBuffer: list[list[str]],
displayBuffer: list[list[MyString]],
currentLine: int, currentCol: int,
scrollX: int, scrollY: int,
modeBarData: str,
@ -108,7 +109,7 @@ class VimView(Observer):
# Отображение видимой части текста
for i in range(self.curses_adapter.lines - 1):
if i + scrollY < len(displayBuffer):
line = ''.join(displayBuffer[i + scrollY])
line = ''.join(item.data() for item in displayBuffer[i + scrollY])
# Если нужно отображать номера строк, добавляем их перед текстом
if show_line_numbers:
line_number = f"{i + scrollY + 1:6} " # 6 символов на номер строки