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.

83 lines
2.4 KiB

26 years ago
26 years ago
26 years ago
  1. import string
  2. import re
  3. ###$ event <<expand-word>>
  4. ###$ win <Alt-slash>
  5. ###$ unix <Alt-slash>
  6. class AutoExpand:
  7. menudefs = [
  8. ('edit', [
  9. ('E_xpand Word', '<<expand-word>>'),
  10. ]),
  11. ]
  12. wordchars = string.ascii_letters + string.digits + "_"
  13. def __init__(self, editwin):
  14. self.text = editwin.text
  15. self.state = None
  16. def expand_word_event(self, event):
  17. curinsert = self.text.index("insert")
  18. curline = self.text.get("insert linestart", "insert lineend")
  19. if not self.state:
  20. words = self.getwords()
  21. index = 0
  22. else:
  23. words, index, insert, line = self.state
  24. if insert != curinsert or line != curline:
  25. words = self.getwords()
  26. index = 0
  27. if not words:
  28. self.text.bell()
  29. return "break"
  30. word = self.getprevword()
  31. self.text.delete("insert - %d chars" % len(word), "insert")
  32. newword = words[index]
  33. index = (index + 1) % len(words)
  34. if index == 0:
  35. self.text.bell() # Warn we cycled around
  36. self.text.insert("insert", newword)
  37. curinsert = self.text.index("insert")
  38. curline = self.text.get("insert linestart", "insert lineend")
  39. self.state = words, index, curinsert, curline
  40. return "break"
  41. def getwords(self):
  42. word = self.getprevword()
  43. if not word:
  44. return []
  45. before = self.text.get("1.0", "insert wordstart")
  46. wbefore = re.findall(r"\b" + word + r"\w+\b", before)
  47. del before
  48. after = self.text.get("insert wordend", "end")
  49. wafter = re.findall(r"\b" + word + r"\w+\b", after)
  50. del after
  51. if not wbefore and not wafter:
  52. return []
  53. words = []
  54. dict = {}
  55. # search backwards through words before
  56. wbefore.reverse()
  57. for w in wbefore:
  58. if dict.get(w):
  59. continue
  60. words.append(w)
  61. dict[w] = w
  62. # search onwards through words after
  63. for w in wafter:
  64. if dict.get(w):
  65. continue
  66. words.append(w)
  67. dict[w] = w
  68. words.append(word)
  69. return words
  70. def getprevword(self):
  71. line = self.text.get("insert linestart", "insert")
  72. i = len(line)
  73. while i > 0 and line[i-1] in self.wordchars:
  74. i = i-1
  75. return line[i:]