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.

84 lines
2.2 KiB

  1. class Document:
  2. def __init__(self, filename):
  3. self.characters = []
  4. self.cursor = Cursor(self)
  5. if len(filename) == 0:
  6. raise FileNameInvalid("Invalid filename")
  7. else:
  8. self.filename = filename
  9. def insert(self, character):
  10. if not hasattr(character, 'character'):
  11. character = Character(character)
  12. self.characters.insert(self.cursor.position, character)
  13. self.cursor.forward()
  14. def delete(self):
  15. try:
  16. del self.characters[self.cursor.position]
  17. except IndexError:
  18. print("No character to delete")
  19. def save(self):
  20. try:
  21. f = open(self.filename, "w")
  22. f.write(self.string)
  23. f.close()
  24. except IOError:
  25. print("Could not safe file")
  26. @property
  27. def string(self):
  28. return "".join((str(c) for c in self.characters))
  29. class Cursor:
  30. def __init__(self, document):
  31. self.document = document
  32. self.position = 0
  33. def forward(self):
  34. if self.position < len(self.document.characters):
  35. self.position += 1
  36. def back(self):
  37. if self.position > 0:
  38. self.position -= 1
  39. def home(self):
  40. while self.document.characters[self.position - 1].character != "\n":
  41. self.back()
  42. if self.position == 0:
  43. # got to beginning of file before newline
  44. break
  45. def end(self):
  46. while (self.position < len(self.document.characters) and
  47. self.document.characters[self.position].character != "\n"):
  48. self.forward()
  49. class Character:
  50. def __init__(self, character, bold=False, italic=False, underline=False):
  51. if len(character) != 1:
  52. raise CharacterLength("Please insert a single character")
  53. self.character = character
  54. self.bold = bold
  55. self.italic = italic
  56. self.underline = underline
  57. def __str__(self):
  58. bold = "*" if self.bold else ''
  59. italic = "/" if self.italic else ''
  60. underline = "_" if self.underline else ''
  61. return bold + italic + underline + self.character
  62. class FileNameInvalid(Exception):
  63. pass
  64. class CharacterLength(Exception):
  65. pass