Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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.

AutoIndent.py 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. import sys
  2. import tokenize
  3. from pywin import default_scintilla_encoding
  4. from . import PyParse
  5. if sys.version_info < (3,):
  6. # in py2k, tokenize() takes a 'token eater' callback, while
  7. # generate_tokens is a generator that works with str objects.
  8. token_generator = tokenize.generate_tokens
  9. else:
  10. # in py3k tokenize() is the generator working with 'byte' objects, and
  11. # token_generator is the 'undocumented b/w compat' function that
  12. # theoretically works with str objects - but actually seems to fail)
  13. token_generator = tokenize.tokenize
  14. class AutoIndent:
  15. menudefs = [
  16. (
  17. "edit",
  18. [
  19. None,
  20. ("_Indent region", "<<indent-region>>"),
  21. ("_Dedent region", "<<dedent-region>>"),
  22. ("Comment _out region", "<<comment-region>>"),
  23. ("U_ncomment region", "<<uncomment-region>>"),
  24. ("Tabify region", "<<tabify-region>>"),
  25. ("Untabify region", "<<untabify-region>>"),
  26. ("Toggle tabs", "<<toggle-tabs>>"),
  27. ("New indent width", "<<change-indentwidth>>"),
  28. ],
  29. ),
  30. ]
  31. keydefs = {
  32. "<<smart-backspace>>": ["<Key-BackSpace>"],
  33. "<<newline-and-indent>>": ["<Key-Return>", "<KP_Enter>"],
  34. "<<smart-indent>>": ["<Key-Tab>"],
  35. }
  36. windows_keydefs = {
  37. "<<indent-region>>": ["<Control-bracketright>"],
  38. "<<dedent-region>>": ["<Control-bracketleft>"],
  39. "<<comment-region>>": ["<Alt-Key-3>"],
  40. "<<uncomment-region>>": ["<Alt-Key-4>"],
  41. "<<tabify-region>>": ["<Alt-Key-5>"],
  42. "<<untabify-region>>": ["<Alt-Key-6>"],
  43. "<<toggle-tabs>>": ["<Alt-Key-t>"],
  44. "<<change-indentwidth>>": ["<Alt-Key-u>"],
  45. }
  46. unix_keydefs = {
  47. "<<indent-region>>": [
  48. "<Alt-bracketright>",
  49. "<Meta-bracketright>",
  50. "<Control-bracketright>",
  51. ],
  52. "<<dedent-region>>": [
  53. "<Alt-bracketleft>",
  54. "<Meta-bracketleft>",
  55. "<Control-bracketleft>",
  56. ],
  57. "<<comment-region>>": ["<Alt-Key-3>", "<Meta-Key-3>"],
  58. "<<uncomment-region>>": ["<Alt-Key-4>", "<Meta-Key-4>"],
  59. "<<tabify-region>>": ["<Alt-Key-5>", "<Meta-Key-5>"],
  60. "<<untabify-region>>": ["<Alt-Key-6>", "<Meta-Key-6>"],
  61. "<<toggle-tabs>>": ["<Alt-Key-t>"],
  62. "<<change-indentwidth>>": ["<Alt-Key-u>"],
  63. }
  64. # usetabs true -> literal tab characters are used by indent and
  65. # dedent cmds, possibly mixed with spaces if
  66. # indentwidth is not a multiple of tabwidth
  67. # false -> tab characters are converted to spaces by indent
  68. # and dedent cmds, and ditto TAB keystrokes
  69. # indentwidth is the number of characters per logical indent level.
  70. # tabwidth is the display width of a literal tab character.
  71. # CAUTION: telling Tk to use anything other than its default
  72. # tab setting causes it to use an entirely different tabbing algorithm,
  73. # treating tab stops as fixed distances from the left margin.
  74. # Nobody expects this, so for now tabwidth should never be changed.
  75. usetabs = 1
  76. indentwidth = 4
  77. tabwidth = 8 # for IDLE use, must remain 8 until Tk is fixed
  78. # If context_use_ps1 is true, parsing searches back for a ps1 line;
  79. # else searches for a popular (if, def, ...) Python stmt.
  80. context_use_ps1 = 0
  81. # When searching backwards for a reliable place to begin parsing,
  82. # first start num_context_lines[0] lines back, then
  83. # num_context_lines[1] lines back if that didn't work, and so on.
  84. # The last value should be huge (larger than the # of lines in a
  85. # conceivable file).
  86. # Making the initial values larger slows things down more often.
  87. num_context_lines = 50, 500, 5000000
  88. def __init__(self, editwin):
  89. self.editwin = editwin
  90. self.text = editwin.text
  91. def config(self, **options):
  92. for key, value in options.items():
  93. if key == "usetabs":
  94. self.usetabs = value
  95. elif key == "indentwidth":
  96. self.indentwidth = value
  97. elif key == "tabwidth":
  98. self.tabwidth = value
  99. elif key == "context_use_ps1":
  100. self.context_use_ps1 = value
  101. else:
  102. raise KeyError("bad option name: %s" % repr(key))
  103. # If ispythonsource and guess are true, guess a good value for
  104. # indentwidth based on file content (if possible), and if
  105. # indentwidth != tabwidth set usetabs false.
  106. # In any case, adjust the Text widget's view of what a tab
  107. # character means.
  108. def set_indentation_params(self, ispythonsource, guess=1):
  109. if guess and ispythonsource:
  110. i = self.guess_indent()
  111. if 2 <= i <= 8:
  112. self.indentwidth = i
  113. if self.indentwidth != self.tabwidth:
  114. self.usetabs = 0
  115. self.editwin.set_tabwidth(self.tabwidth)
  116. def smart_backspace_event(self, event):
  117. text = self.text
  118. first, last = self.editwin.get_selection_indices()
  119. if first and last:
  120. text.delete(first, last)
  121. text.mark_set("insert", first)
  122. return "break"
  123. # Delete whitespace left, until hitting a real char or closest
  124. # preceding virtual tab stop.
  125. chars = text.get("insert linestart", "insert")
  126. if chars == "":
  127. if text.compare("insert", ">", "1.0"):
  128. # easy: delete preceding newline
  129. text.delete("insert-1c")
  130. else:
  131. text.bell() # at start of buffer
  132. return "break"
  133. if chars[-1] not in " \t":
  134. # easy: delete preceding real char
  135. text.delete("insert-1c")
  136. return "break"
  137. # Ick. It may require *inserting* spaces if we back up over a
  138. # tab character! This is written to be clear, not fast.
  139. have = len(chars.expandtabs(self.tabwidth))
  140. assert have > 0
  141. want = int((have - 1) / self.indentwidth) * self.indentwidth
  142. ncharsdeleted = 0
  143. while 1:
  144. chars = chars[:-1]
  145. ncharsdeleted = ncharsdeleted + 1
  146. have = len(chars.expandtabs(self.tabwidth))
  147. if have <= want or chars[-1] not in " \t":
  148. break
  149. text.undo_block_start()
  150. text.delete("insert-%dc" % ncharsdeleted, "insert")
  151. if have < want:
  152. text.insert("insert", " " * (want - have))
  153. text.undo_block_stop()
  154. return "break"
  155. def smart_indent_event(self, event):
  156. # if intraline selection:
  157. # delete it
  158. # elif multiline selection:
  159. # do indent-region & return
  160. # indent one level
  161. text = self.text
  162. first, last = self.editwin.get_selection_indices()
  163. text.undo_block_start()
  164. try:
  165. if first and last:
  166. if index2line(first) != index2line(last):
  167. return self.indent_region_event(event)
  168. text.delete(first, last)
  169. text.mark_set("insert", first)
  170. prefix = text.get("insert linestart", "insert")
  171. raw, effective = classifyws(prefix, self.tabwidth)
  172. if raw == len(prefix):
  173. # only whitespace to the left
  174. self.reindent_to(effective + self.indentwidth)
  175. else:
  176. if self.usetabs:
  177. pad = "\t"
  178. else:
  179. effective = len(prefix.expandtabs(self.tabwidth))
  180. n = self.indentwidth
  181. pad = " " * (n - effective % n)
  182. text.insert("insert", pad)
  183. text.see("insert")
  184. return "break"
  185. finally:
  186. text.undo_block_stop()
  187. def newline_and_indent_event(self, event):
  188. text = self.text
  189. first, last = self.editwin.get_selection_indices()
  190. text.undo_block_start()
  191. try:
  192. if first and last:
  193. text.delete(first, last)
  194. text.mark_set("insert", first)
  195. line = text.get("insert linestart", "insert")
  196. i, n = 0, len(line)
  197. while i < n and line[i] in " \t":
  198. i = i + 1
  199. if i == n:
  200. # the cursor is in or at leading indentation; just inject
  201. # an empty line at the start and strip space from current line
  202. text.delete("insert - %d chars" % i, "insert")
  203. text.insert("insert linestart", "\n")
  204. return "break"
  205. indent = line[:i]
  206. # strip whitespace before insert point
  207. i = 0
  208. while line and line[-1] in " \t":
  209. line = line[:-1]
  210. i = i + 1
  211. if i:
  212. text.delete("insert - %d chars" % i, "insert")
  213. # strip whitespace after insert point
  214. while text.get("insert") in " \t":
  215. text.delete("insert")
  216. # start new line
  217. text.insert("insert", "\n")
  218. # adjust indentation for continuations and block
  219. # open/close first need to find the last stmt
  220. lno = index2line(text.index("insert"))
  221. y = PyParse.Parser(self.indentwidth, self.tabwidth)
  222. for context in self.num_context_lines:
  223. startat = max(lno - context, 1)
  224. startatindex = repr(startat) + ".0"
  225. rawtext = text.get(startatindex, "insert")
  226. y.set_str(rawtext)
  227. bod = y.find_good_parse_start(
  228. self.context_use_ps1, self._build_char_in_string_func(startatindex)
  229. )
  230. if bod is not None or startat == 1:
  231. break
  232. y.set_lo(bod or 0)
  233. c = y.get_continuation_type()
  234. if c != PyParse.C_NONE:
  235. # The current stmt hasn't ended yet.
  236. if c == PyParse.C_STRING:
  237. # inside a string; just mimic the current indent
  238. text.insert("insert", indent)
  239. elif c == PyParse.C_BRACKET:
  240. # line up with the first (if any) element of the
  241. # last open bracket structure; else indent one
  242. # level beyond the indent of the line with the
  243. # last open bracket
  244. self.reindent_to(y.compute_bracket_indent())
  245. elif c == PyParse.C_BACKSLASH:
  246. # if more than one line in this stmt already, just
  247. # mimic the current indent; else if initial line
  248. # has a start on an assignment stmt, indent to
  249. # beyond leftmost =; else to beyond first chunk of
  250. # non-whitespace on initial line
  251. if y.get_num_lines_in_stmt() > 1:
  252. text.insert("insert", indent)
  253. else:
  254. self.reindent_to(y.compute_backslash_indent())
  255. else:
  256. assert 0, "bogus continuation type " + repr(c)
  257. return "break"
  258. # This line starts a brand new stmt; indent relative to
  259. # indentation of initial line of closest preceding
  260. # interesting stmt.
  261. indent = y.get_base_indent_string()
  262. text.insert("insert", indent)
  263. if y.is_block_opener():
  264. self.smart_indent_event(event)
  265. elif indent and y.is_block_closer():
  266. self.smart_backspace_event(event)
  267. return "break"
  268. finally:
  269. text.see("insert")
  270. text.undo_block_stop()
  271. auto_indent = newline_and_indent_event
  272. # Our editwin provides a is_char_in_string function that works
  273. # with a Tk text index, but PyParse only knows about offsets into
  274. # a string. This builds a function for PyParse that accepts an
  275. # offset.
  276. def _build_char_in_string_func(self, startindex):
  277. def inner(offset, _startindex=startindex, _icis=self.editwin.is_char_in_string):
  278. return _icis(_startindex + "+%dc" % offset)
  279. return inner
  280. def indent_region_event(self, event):
  281. head, tail, chars, lines = self.get_region()
  282. for pos in range(len(lines)):
  283. line = lines[pos]
  284. if line:
  285. raw, effective = classifyws(line, self.tabwidth)
  286. effective = effective + self.indentwidth
  287. lines[pos] = self._make_blanks(effective) + line[raw:]
  288. self.set_region(head, tail, chars, lines)
  289. return "break"
  290. def dedent_region_event(self, event):
  291. head, tail, chars, lines = self.get_region()
  292. for pos in range(len(lines)):
  293. line = lines[pos]
  294. if line:
  295. raw, effective = classifyws(line, self.tabwidth)
  296. effective = max(effective - self.indentwidth, 0)
  297. lines[pos] = self._make_blanks(effective) + line[raw:]
  298. self.set_region(head, tail, chars, lines)
  299. return "break"
  300. def comment_region_event(self, event):
  301. head, tail, chars, lines = self.get_region()
  302. for pos in range(len(lines) - 1):
  303. line = lines[pos]
  304. lines[pos] = "##" + line
  305. self.set_region(head, tail, chars, lines)
  306. def uncomment_region_event(self, event):
  307. head, tail, chars, lines = self.get_region()
  308. for pos in range(len(lines)):
  309. line = lines[pos]
  310. if not line:
  311. continue
  312. if line[:2] == "##":
  313. line = line[2:]
  314. elif line[:1] == "#":
  315. line = line[1:]
  316. lines[pos] = line
  317. self.set_region(head, tail, chars, lines)
  318. def tabify_region_event(self, event):
  319. head, tail, chars, lines = self.get_region()
  320. tabwidth = self._asktabwidth()
  321. for pos in range(len(lines)):
  322. line = lines[pos]
  323. if line:
  324. raw, effective = classifyws(line, tabwidth)
  325. ntabs, nspaces = divmod(effective, tabwidth)
  326. lines[pos] = "\t" * ntabs + " " * nspaces + line[raw:]
  327. self.set_region(head, tail, chars, lines)
  328. def untabify_region_event(self, event):
  329. head, tail, chars, lines = self.get_region()
  330. tabwidth = self._asktabwidth()
  331. for pos in range(len(lines)):
  332. lines[pos] = lines[pos].expandtabs(tabwidth)
  333. self.set_region(head, tail, chars, lines)
  334. def toggle_tabs_event(self, event):
  335. if self.editwin.askyesno(
  336. "Toggle tabs",
  337. "Turn tabs " + ("on", "off")[self.usetabs] + "?",
  338. parent=self.text,
  339. ):
  340. self.usetabs = not self.usetabs
  341. return "break"
  342. # XXX this isn't bound to anything -- see class tabwidth comments
  343. def change_tabwidth_event(self, event):
  344. new = self._asktabwidth()
  345. if new != self.tabwidth:
  346. self.tabwidth = new
  347. self.set_indentation_params(0, guess=0)
  348. return "break"
  349. def change_indentwidth_event(self, event):
  350. new = self.editwin.askinteger(
  351. "Indent width",
  352. "New indent width (1-16)",
  353. parent=self.text,
  354. initialvalue=self.indentwidth,
  355. minvalue=1,
  356. maxvalue=16,
  357. )
  358. if new and new != self.indentwidth:
  359. self.indentwidth = new
  360. return "break"
  361. def get_region(self):
  362. text = self.text
  363. first, last = self.editwin.get_selection_indices()
  364. if first and last:
  365. head = text.index(first + " linestart")
  366. tail = text.index(last + "-1c lineend +1c")
  367. else:
  368. head = text.index("insert linestart")
  369. tail = text.index("insert lineend +1c")
  370. chars = text.get(head, tail)
  371. lines = chars.split("\n")
  372. return head, tail, chars, lines
  373. def set_region(self, head, tail, chars, lines):
  374. text = self.text
  375. newchars = "\n".join(lines)
  376. if newchars == chars:
  377. text.bell()
  378. return
  379. text.tag_remove("sel", "1.0", "end")
  380. text.mark_set("insert", head)
  381. text.undo_block_start()
  382. text.delete(head, tail)
  383. text.insert(head, newchars)
  384. text.undo_block_stop()
  385. text.tag_add("sel", head, "insert")
  386. # Make string that displays as n leading blanks.
  387. def _make_blanks(self, n):
  388. if self.usetabs:
  389. ntabs, nspaces = divmod(n, self.tabwidth)
  390. return "\t" * ntabs + " " * nspaces
  391. else:
  392. return " " * n
  393. # Delete from beginning of line to insert point, then reinsert
  394. # column logical (meaning use tabs if appropriate) spaces.
  395. def reindent_to(self, column):
  396. text = self.text
  397. text.undo_block_start()
  398. if text.compare("insert linestart", "!=", "insert"):
  399. text.delete("insert linestart", "insert")
  400. if column:
  401. text.insert("insert", self._make_blanks(column))
  402. text.undo_block_stop()
  403. def _asktabwidth(self):
  404. return (
  405. self.editwin.askinteger(
  406. "Tab width",
  407. "Spaces per tab?",
  408. parent=self.text,
  409. initialvalue=self.tabwidth,
  410. minvalue=1,
  411. maxvalue=16,
  412. )
  413. or self.tabwidth
  414. )
  415. # Guess indentwidth from text content.
  416. # Return guessed indentwidth. This should not be believed unless
  417. # it's in a reasonable range (e.g., it will be 0 if no indented
  418. # blocks are found).
  419. def guess_indent(self):
  420. opener, indented = IndentSearcher(self.text, self.tabwidth).run()
  421. if opener and indented:
  422. raw, indentsmall = classifyws(opener, self.tabwidth)
  423. raw, indentlarge = classifyws(indented, self.tabwidth)
  424. else:
  425. indentsmall = indentlarge = 0
  426. return indentlarge - indentsmall
  427. # "line.col" -> line, as an int
  428. def index2line(index):
  429. return int(float(index))
  430. # Look at the leading whitespace in s.
  431. # Return pair (# of leading ws characters,
  432. # effective # of leading blanks after expanding
  433. # tabs to width tabwidth)
  434. def classifyws(s, tabwidth):
  435. raw = effective = 0
  436. for ch in s:
  437. if ch == " ":
  438. raw = raw + 1
  439. effective = effective + 1
  440. elif ch == "\t":
  441. raw = raw + 1
  442. effective = (effective // tabwidth + 1) * tabwidth
  443. else:
  444. break
  445. return raw, effective
  446. class IndentSearcher:
  447. # .run() chews over the Text widget, looking for a block opener
  448. # and the stmt following it. Returns a pair,
  449. # (line containing block opener, line containing stmt)
  450. # Either or both may be None.
  451. def __init__(self, text, tabwidth):
  452. self.text = text
  453. self.tabwidth = tabwidth
  454. self.i = self.finished = 0
  455. self.blkopenline = self.indentedline = None
  456. def readline(self):
  457. if self.finished:
  458. val = ""
  459. else:
  460. i = self.i = self.i + 1
  461. mark = repr(i) + ".0"
  462. if self.text.compare(mark, ">=", "end"):
  463. val = ""
  464. else:
  465. val = self.text.get(mark, mark + " lineend+1c")
  466. # hrm - not sure this is correct in py3k - the source code may have
  467. # an encoding declared, but the data will *always* be in
  468. # default_scintilla_encoding - so if anyone looks at the encoding decl
  469. # in the source they will be wrong. I think. Maybe. Or something...
  470. return val.encode(default_scintilla_encoding)
  471. def run(self):
  472. OPENERS = ("class", "def", "for", "if", "try", "while")
  473. INDENT = tokenize.INDENT
  474. NAME = tokenize.NAME
  475. save_tabsize = tokenize.tabsize
  476. tokenize.tabsize = self.tabwidth
  477. try:
  478. try:
  479. for typ, token, start, end, line in token_generator(self.readline):
  480. if typ == NAME and token in OPENERS:
  481. self.blkopenline = line
  482. elif typ == INDENT and self.blkopenline:
  483. self.indentedline = line
  484. break
  485. except (tokenize.TokenError, IndentationError):
  486. # since we cut off the tokenizer early, we can trigger
  487. # spurious errors
  488. pass
  489. finally:
  490. tokenize.tabsize = save_tabsize
  491. return self.blkopenline, self.indentedline