add LineStream class

This commit is contained in:
Maximilian Keßler 2022-02-06 18:12:30 +01:00
parent a5a3ec0dfa
commit 9ae70fae13

View file

@ -1,5 +1,63 @@
from typing import List, TextIO
from pathlib import Path
from .pytex_formatter import PyTeXFormatter from .pytex_formatter import PyTeXFormatter
from .macros import Macro
class LineStream:
def __init__(self, filename: Path):
self._file = filename
self._handle = open(filename, 'r')
self._cached_lines: List[str] = []
def current_line(self):
return self.future_line(0)
def set_line(self, line):
self.set_future_line(0, line)
def pop_line(self) -> str:
self.reserve_lines(1)
line = self._cached_lines[0]
self._cached_lines = self._cached_lines[1:]
return line
def push_line(self, line):
self.push_lines([line])
def push_lines(self, lines: List[str]):
self._cached_lines = lines + self._cached_lines
def future_line(self, pos: int):
self.reserve_lines(pos + 1)
return self._cached_lines[pos]
def set_future_line(self, line, pos):
self.reserve_lines(pos + 1)
self._cached_lines[pos] = line
def reserve_lines(self, num_lines):
for i in range(0, num_lines - len(self._cached_lines) -1):
self._cached_lines.append(
self._handle.readline()
)
if self._cached_lines[-1] == '':
self._handle.close()
class TexFormatter(PyTeXFormatter): class TexFormatter(PyTeXFormatter):
pass def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._macros: List[Macro] = []
self._output_file: TextIO = None
def _handle_macro(self, macro: Macro):
self._current_line = macro.apply(self._current_line, self)
def _shipout_line(self):
self.write_line(self._current_line.rstrip())
def write_line(self, line: str):
self._output_file.writelines([line])