Skip to content

Commit

Permalink
check point, probably won't build
Browse files Browse the repository at this point in the history
  • Loading branch information
matthewdeanmartin committed Apr 4, 2023
1 parent 34225f7 commit 12fb4e2
Show file tree
Hide file tree
Showing 30 changed files with 1,332 additions and 877 deletions.
3 changes: 2 additions & 1 deletion .markdownlintrc
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@
"MD030": false,

// Set list indent level to 4 which Python-Markdown requires
"MD007": { "indent": 4 },
// (mdformat uses 2)
"MD007": { "indent": 2 },

// Code block style
"MD046": { "style": "fenced" },
Expand Down
5 changes: 4 additions & 1 deletion Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ uvicorn = { version = "*", optional = true }
icontract = "*"
# typeguard does not seem to get along with pydantic.
# typeguard = "*"
linkcheckmd = {ref = "b05bac0c852a5f5c0e92a4836d522210daef6823", git = "https://github.com/matthewdeanmartin/linkchecker-markdown"}
pyttsx3 = "*"
mistune = "*"

[dev-packages]
mypy = "*"
Expand All @@ -28,7 +31,7 @@ pytest-cov = "*"
hypothesis = {extras = ["cli"], version = "*"}
types-requests = "*"
pre-commit = "*"
linkcheckmd = "*"
proselint = "*"

[requires]
python_version = "3.11"
1,580 changes: 762 additions & 818 deletions Pipfile.lock

Large diffs are not rendered by default.

35 changes: 18 additions & 17 deletions dedlin/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
--promptless_quit Skip prompt on quit.
--vim_mode User hostile, no feedback.
--verbose Displaying all debugging info.
--blind_mode Optimize for blind users (experimental).
"""
import logging
import logging.config
Expand All @@ -31,7 +32,8 @@
from dedlin.flash import title_screen
from dedlin.logging_utils import configure_logging
from dedlin.main import Dedlin
from dedlin.rich_output import RichPrinter
from dedlin.outputters import talking_outputter, rich_output
from dedlin.outputters.plain import plain_printer

logger = logging.getLogger(__name__)

Expand All @@ -47,6 +49,7 @@ def main() -> None:
quit_safety=not arguments["--promptless_quit"],
vim_mode=bool(arguments["--vim_mode"]),
verbose=bool(arguments["--verbose"]),
blind_mode=bool(arguments["--blind_mode"]),
)
sys.exit(0)

Expand All @@ -59,6 +62,7 @@ def run(
quit_safety: bool = False,
vim_mode: bool = False,
verbose: bool = False,
blind_mode: bool = False
) -> Dedlin:
"""Set up everything except things from command line"""
if verbose:
Expand All @@ -67,13 +71,18 @@ def run(
logger.info("Verbose mode enabled")

if not macro_file_name:
title_screen()

rich_printer = RichPrinter()

def printer(text: Optional[str], end: str = "\n") -> None:
text = "" if text is None else text
rich_printer.print(text, end="")
title_screen(blind_mode)

if blind_mode:
logger.info("Blind mode. UI should talk.")
printer = talking_outputter.printer
echo = True
elif file_name and file_name.endswith(".py") :
logger.info("Rich mode. UI should be colorful.")
printer = rich_output.printer
else:
logger.info("Plain mode. UI should be dull.")
printer = plain_printer

if macro_file_name:
the_command_generator = CommandGenerator(Path(macro_file_name))
Expand All @@ -88,19 +97,11 @@ def document_inputter(prompt: str, text: str = "") -> Generator[str, None, None]
while True:
yield input_with_prefill(prompt, text)

def plain_printer(text: Optional[str], end: str = "\n") -> None:
text = "" if text is None else text
if text.endswith("\n"):
text = text[:-1]
print(text, end="")
else:
print(text, end=end)

dedlin = Dedlin(
inputter=the_command_generator, # InteractiveGenerator(),
insert_document_inputter=SimpleInputter(),
edit_document_inputter=PrefillInputter(),
outputter=printer if file_name and file_name.endswith(".py") else plain_printer,
outputter=printer,
)

# save on crash but hides error info
Expand Down
27 changes: 25 additions & 2 deletions dedlin/basic_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ class Commands(Enum):
QUIT = auto()
EXIT = auto()
TRANSFER = auto()
EXPORT = auto()

# Add text
BROWSE = auto()
Expand All @@ -59,6 +60,28 @@ class Commands(Enum):
INFO = auto()
CRASH = auto()

# print
PRINT = auto()

# Block String commands
INDENT = auto()
DEDENT = auto()

# String commands
TITLE = auto()
SWAPCASE = auto()
CASEFOLD = auto()
CAPITALIZE = auto()
UPPER = auto()
LOWER = auto()
EXPANDTABS = auto()
RJUST = auto()
LJUST = auto()
CENTER = auto()
RSTRIP = auto()
LSTRIP = auto()
STRIP = auto()


@dataclass(frozen=True)
class LineRange:
Expand Down Expand Up @@ -280,7 +303,7 @@ class CommandGeneratorProtocol(Protocol):
current_line: int

def generate(
self,
self,
) -> Generator[Command, None, None]:
"""Generate commands"""
...
Expand All @@ -294,7 +317,7 @@ class StringGeneratorProtocol(Protocol):
default: str

def generate(
self,
self,
) -> Generator[str, None, None]:
"""Generate strings"""
...
14 changes: 7 additions & 7 deletions dedlin/document.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@
from pydantic.dataclasses import dataclass

from dedlin.basic_types import LineRange, Phrases, StringGeneratorProtocol
from dedlin.lorem_data import LOREM_IPSUM
from dedlin.spelling_overlay import check
import dedlin.tools.lorem_data as lorem_data
import dedlin.tools.spelling_overlay as spelling_overlay

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -150,7 +150,7 @@ def spell(self, line_range: LineRange) -> Generator[tuple[str, str], None, None]
self.current_line = line_range.start
for line_text in self.lines[line_range.start - 1 : line_range.end]:
end = "" if line_text[:-1] == "\n" else "\n"
yield f" {self.current_line} : {check(line_text)}", end
yield f" {self.current_line} : {spelling_overlay.check(line_text)}", end
self.current_line += 1

def copy(self, line_range: Optional[LineRange], target_line: int) -> None:
Expand Down Expand Up @@ -338,17 +338,17 @@ def insert(
def lorem(self, line_range: Optional[LineRange]) -> None:
"""Add lorem ipsum to lines"""
if not line_range:
line_range = LineRange(1, len(LOREM_IPSUM) - 1)
line_range = LineRange(1, len(lorem_data.LOREM_IPSUM) - 1)

self.backup()
# TODO: generate from a specified range of Lorem?
lines_to_generate = line_range.start
if lines_to_generate == 0:
lines_to_generate = len(LOREM_IPSUM)
lines_to_generate = len(lorem_data.LOREM_IPSUM)

for i in range(0, lines_to_generate):
if i < len(LOREM_IPSUM):
self.lines.append(LOREM_IPSUM[i])
if i < len(lorem_data.LOREM_IPSUM):
self.lines.append(lorem_data.LOREM_IPSUM[i])
self.dirty = True # this is ugly
logger.debug(f"Generated {lines_to_generate} lines")

Expand Down
23 changes: 20 additions & 3 deletions dedlin/file_system.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
from pathlib import Path
from typing import Optional

from dedlin.tools.export import export_markdown


def read_or_create_file(path: Path) -> list[str]:
"""Attempt to read file, create if it doesn't exist"""
Expand Down Expand Up @@ -38,11 +40,26 @@ def read_file(path: Optional[Path]) -> list[str]:
return lines


def save_and_overwrite(path: Path, lines: list[str]):
def save_and_overwrite(path: Path, lines: list[str], preferred_line_break:str)->None:
"""Save a file and overwrite it"""
if not path:
raise TypeError("No file path")
with open(str(path), "w", encoding="utf-8") as file:
file.seek(0)
# TODO: make this use preferred line break
file.writelines(line + "\n" for line in lines)
file.writelines(line + preferred_line_break for line in lines)


def export(path: Path, lines: list[str], preferred_line_break:str)->None:
"""Save a file and overwrite it"""
if not path:
raise TypeError("No file path")
if path.suffix.lower() == ".html":
html_name = path.rename(path.with_suffix('.html'))
with open(str(html_name), "w", encoding="utf-8") as file:
file.seek(0)
file.write(export_markdown(lines, preferred_line_break))
else:
with open(str(path), "w", encoding="utf-8") as file:
file.seek(0)
# TODO: make this use preferred line break
file.writelines(line + "\n" for line in lines)
7 changes: 4 additions & 3 deletions dedlin/flash.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
from art import tprint


def title_screen() -> None:
def title_screen(user_is_blind:bool) -> None:
"""Flashy title screen"""
print("\033[H\033[J", end="")
tprint("dedlin", font="small", chr_ignore=True)
if not user_is_blind:
print("\033[H\033[J", end="")
tprint("dedlin", font="small", chr_ignore=True)
4 changes: 2 additions & 2 deletions dedlin/history_feature.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,10 @@ def make_sequential_history_file_name(self) -> str:
"""
return f"history{self.count_files_in_history_folder()}.ed"

def write_command_to_history_file(self, command: str) -> None:
def write_command_to_history_file(self, command: str, preferred_line_break:str) -> None:
"""
Write a command to the history file
"""
with open(self.history_file, "a", encoding="utf-8") as file_handle:
file_handle.write(command)
file_handle.write("\n")
file_handle.write(preferred_line_break)
32 changes: 23 additions & 9 deletions dedlin/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from pathlib import Path
from typing import Any, Callable, Optional

import dedlin.help_text as help_text
import dedlin.text.help_text as help_text
from dedlin.basic_types import (
Command,
Commands,
Expand All @@ -20,11 +20,11 @@
from dedlin.command_sources import InMemoryCommandGenerator
from dedlin.document import Document
from dedlin.document_sources import InMemoryInputter, PrefillInputter
from dedlin.file_system import read_or_create_file, save_and_overwrite
import dedlin.file_system as file_system
from dedlin.history_feature import HistoryLog
from dedlin.info_bar import display_info
from dedlin.tools.info_bar import display_info
from dedlin.utils.exceptions import DedlinException
from dedlin.web import fetch_page_as_rows
from dedlin.tools.web import fetch_page_as_rows

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -72,6 +72,11 @@ def __init__(
self.verbose = False
"""Write logging to screen, even if quiet or vim mode is enabled"""

self.blind_mode = True
"""Assume user can't see at all"""

self.preferred_line_break = "\n"

self.file_path: Optional[Path] = None
self.history: list[Command] = []
self.history_log = HistoryLog()
Expand All @@ -94,7 +99,7 @@ def entry_point(self, file_name: Optional[str] = None, macro_file_name: Optional

self.macro_file_name = Path(macro_file_name) if macro_file_name else None
self.file_path = Path(file_name) if file_name else None
lines = read_or_create_file(self.file_path)
lines = file_system.read_or_create_file(self.file_path)

self.doc = Document(
insert_inputter=self.insert_document_inputter,
Expand All @@ -121,7 +126,7 @@ def entry_point(self, file_name: Optional[str] = None, macro_file_name: Optional
self.feedback(f"Invalid command {command}")

self.history.append(command)
self.history_log.write_command_to_history_file(command.format())
self.history_log.write_command_to_history_file(command.format(), self.preferred_line_break)
self.echo_if_needed(command.format())

if command.command == Commands.REDO:
Expand Down Expand Up @@ -270,14 +275,21 @@ def entry_point(self, file_name: Optional[str] = None, macro_file_name: Optional
self.feedback(help_text.SPECIFIC_HELP[command.phrases.first.upper()])
else:
self.feedback("Don't have help for that category")
elif command.command == Commands.EXPORT:
file_system.export(self.doc.lines, self.preferred_line_break)
self.feedback("Exported to")
elif command.command == Commands.UNKNOWN:
self.feedback("Unknown command, type HELP for help")
if self.halt_on_error:
raise Exception(f"Unknown command {command.original_text}")
else:
self.feedback(f"Command {command.command} not implemented")

self.feedback(f"--- Current line is {self.doc.current_line}, {len(self.doc.lines)} lines total ---")
if self.blind_mode:
status = f"Current line {self.doc.current_line} of {len(self.doc.lines)}"
else:
status = f"--- Current line is {self.doc.current_line}, {len(self.doc.lines)} lines total ---"
self.feedback(status)
return 0

def feedback(self, string, end="\n") -> None:
Expand All @@ -304,12 +316,14 @@ def save_document(self, phrases: Optional[Phrases] = None):
if self.doc:
if self.file_path is not None and phrases is not None:
self.file_path = Path(phrases.first)
save_and_overwrite(self.file_path, self.doc.lines)
file_system.save_and_overwrite(self.file_path, self.doc.lines, self.preferred_line_break)
self.doc.dirty = False

def save_macro(self):
"""Save the document to the file"""
save_and_overwrite(Path("history.ed"), [_.original_text for _ in self.history])
file_system.save_and_overwrite(Path("history.ed"),
[_.original_text for _ in self.history],
self.preferred_line_break)

def final_report(self) -> None:
"""Print out the final report"""
Expand Down
Empty file added dedlin/outputters/__init__.py
Empty file.
10 changes: 10 additions & 0 deletions dedlin/outputters/plain.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from typing import Optional


def plain_printer(text: Optional[str], end: str = "\n") -> None:
text = "" if text is None else text
if text.endswith("\n"):
text = text[:-1]
print(text, end="")
else:
print(text, end=end)
Loading

0 comments on commit 12fb4e2

Please sign in to comment.