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

View File

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