Learning by doing: Reading books and trying to understand the (code) examples
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

65 lines
1.7 KiB

  1. class Document:
  2. def __init__(self):
  3. self.characters = []
  4. self.cursor = Cursor(self)
  5. self.filename = ""
  6. def insert(self, character):
  7. if not hasattr(character, 'character'):
  8. character = Character(character)
  9. self.characters.insert(self.cursor.position, character)
  10. self.cursor.forward()
  11. def delete(self):
  12. del self.characters[self.cursor.position]
  13. def save(self):
  14. f = open(self.filename, "w")
  15. f.write("".join(self.characters))
  16. f.close()
  17. @property
  18. def string(self):
  19. return "".join((str(c) for c in self.characters))
  20. class Cursor:
  21. def __init__(self, document):
  22. self.document = document
  23. self.position = 0
  24. def forward(self):
  25. self.position += 1
  26. def back(self):
  27. self.position -= 1
  28. def home(self):
  29. while self.document.characters[self.position - 1].character != "\n":
  30. self.position -= 1
  31. if self.position == 0:
  32. # got to beginning of file before newline
  33. break
  34. def end(self):
  35. while (self.position < len(self.document.characters) and
  36. self.document.characters[self.position].character != "\n"):
  37. self.position += 1
  38. class Character:
  39. def __init__(self, character, bold=False, italic=False, underline=False):
  40. assert len(character) == 1
  41. self.character = character
  42. self.bold = bold
  43. self.italic = italic
  44. self.underline = underline
  45. def __str__(self):
  46. bold = "*" if self.bold else ''
  47. italic = "/" if self.italic else ''
  48. underline = "_" if self.underline else ''
  49. return bold + italic + underline + self.character