format.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. """Format all or a selected region (line slice) of text.
  2. Region formatting options: paragraph, comment block, indent, deindent,
  3. comment, uncomment, tabify, and untabify.
  4. File renamed from paragraph.py with functions added from editor.py.
  5. """
  6. import re
  7. from tkinter.messagebox import askyesno
  8. from tkinter.simpledialog import askinteger
  9. from idlelib.config import idleConf
  10. class FormatParagraph:
  11. """Format a paragraph, comment block, or selection to a max width.
  12. Does basic, standard text formatting, and also understands Python
  13. comment blocks. Thus, for editing Python source code, this
  14. extension is really only suitable for reformatting these comment
  15. blocks or triple-quoted strings.
  16. Known problems with comment reformatting:
  17. * If there is a selection marked, and the first line of the
  18. selection is not complete, the block will probably not be detected
  19. as comments, and will have the normal "text formatting" rules
  20. applied.
  21. * If a comment block has leading whitespace that mixes tabs and
  22. spaces, they will not be considered part of the same block.
  23. * Fancy comments, like this bulleted list, aren't handled :-)
  24. """
  25. def __init__(self, editwin):
  26. self.editwin = editwin
  27. @classmethod
  28. def reload(cls):
  29. cls.max_width = idleConf.GetOption('extensions', 'FormatParagraph',
  30. 'max-width', type='int', default=72)
  31. def close(self):
  32. self.editwin = None
  33. def format_paragraph_event(self, event, limit=None):
  34. """Formats paragraph to a max width specified in idleConf.
  35. If text is selected, format_paragraph_event will start breaking lines
  36. at the max width, starting from the beginning selection.
  37. If no text is selected, format_paragraph_event uses the current
  38. cursor location to determine the paragraph (lines of text surrounded
  39. by blank lines) and formats it.
  40. The length limit parameter is for testing with a known value.
  41. """
  42. limit = self.max_width if limit is None else limit
  43. text = self.editwin.text
  44. first, last = self.editwin.get_selection_indices()
  45. if first and last:
  46. data = text.get(first, last)
  47. comment_header = get_comment_header(data)
  48. else:
  49. first, last, comment_header, data = \
  50. find_paragraph(text, text.index("insert"))
  51. if comment_header:
  52. newdata = reformat_comment(data, limit, comment_header)
  53. else:
  54. newdata = reformat_paragraph(data, limit)
  55. text.tag_remove("sel", "1.0", "end")
  56. if newdata != data:
  57. text.mark_set("insert", first)
  58. text.undo_block_start()
  59. text.delete(first, last)
  60. text.insert(first, newdata)
  61. text.undo_block_stop()
  62. else:
  63. text.mark_set("insert", last)
  64. text.see("insert")
  65. return "break"
  66. FormatParagraph.reload()
  67. def find_paragraph(text, mark):
  68. """Returns the start/stop indices enclosing the paragraph that mark is in.
  69. Also returns the comment format string, if any, and paragraph of text
  70. between the start/stop indices.
  71. """
  72. lineno, col = map(int, mark.split("."))
  73. line = text.get("%d.0" % lineno, "%d.end" % lineno)
  74. # Look for start of next paragraph if the index passed in is a blank line
  75. while text.compare("%d.0" % lineno, "<", "end") and is_all_white(line):
  76. lineno = lineno + 1
  77. line = text.get("%d.0" % lineno, "%d.end" % lineno)
  78. first_lineno = lineno
  79. comment_header = get_comment_header(line)
  80. comment_header_len = len(comment_header)
  81. # Once start line found, search for end of paragraph (a blank line)
  82. while get_comment_header(line)==comment_header and \
  83. not is_all_white(line[comment_header_len:]):
  84. lineno = lineno + 1
  85. line = text.get("%d.0" % lineno, "%d.end" % lineno)
  86. last = "%d.0" % lineno
  87. # Search back to beginning of paragraph (first blank line before)
  88. lineno = first_lineno - 1
  89. line = text.get("%d.0" % lineno, "%d.end" % lineno)
  90. while lineno > 0 and \
  91. get_comment_header(line)==comment_header and \
  92. not is_all_white(line[comment_header_len:]):
  93. lineno = lineno - 1
  94. line = text.get("%d.0" % lineno, "%d.end" % lineno)
  95. first = "%d.0" % (lineno+1)
  96. return first, last, comment_header, text.get(first, last)
  97. # This should perhaps be replaced with textwrap.wrap
  98. def reformat_paragraph(data, limit):
  99. """Return data reformatted to specified width (limit)."""
  100. lines = data.split("\n")
  101. i = 0
  102. n = len(lines)
  103. while i < n and is_all_white(lines[i]):
  104. i = i+1
  105. if i >= n:
  106. return data
  107. indent1 = get_indent(lines[i])
  108. if i+1 < n and not is_all_white(lines[i+1]):
  109. indent2 = get_indent(lines[i+1])
  110. else:
  111. indent2 = indent1
  112. new = lines[:i]
  113. partial = indent1
  114. while i < n and not is_all_white(lines[i]):
  115. # XXX Should take double space after period (etc.) into account
  116. words = re.split(r"(\s+)", lines[i])
  117. for j in range(0, len(words), 2):
  118. word = words[j]
  119. if not word:
  120. continue # Can happen when line ends in whitespace
  121. if len((partial + word).expandtabs()) > limit and \
  122. partial != indent1:
  123. new.append(partial.rstrip())
  124. partial = indent2
  125. partial = partial + word + " "
  126. if j+1 < len(words) and words[j+1] != " ":
  127. partial = partial + " "
  128. i = i+1
  129. new.append(partial.rstrip())
  130. # XXX Should reformat remaining paragraphs as well
  131. new.extend(lines[i:])
  132. return "\n".join(new)
  133. def reformat_comment(data, limit, comment_header):
  134. """Return data reformatted to specified width with comment header."""
  135. # Remove header from the comment lines
  136. lc = len(comment_header)
  137. data = "\n".join(line[lc:] for line in data.split("\n"))
  138. # Reformat to maxformatwidth chars or a 20 char width,
  139. # whichever is greater.
  140. format_width = max(limit - len(comment_header), 20)
  141. newdata = reformat_paragraph(data, format_width)
  142. # re-split and re-insert the comment header.
  143. newdata = newdata.split("\n")
  144. # If the block ends in a \n, we don't want the comment prefix
  145. # inserted after it. (Im not sure it makes sense to reformat a
  146. # comment block that is not made of complete lines, but whatever!)
  147. # Can't think of a clean solution, so we hack away
  148. block_suffix = ""
  149. if not newdata[-1]:
  150. block_suffix = "\n"
  151. newdata = newdata[:-1]
  152. return '\n'.join(comment_header+line for line in newdata) + block_suffix
  153. def is_all_white(line):
  154. """Return True if line is empty or all whitespace."""
  155. return re.match(r"^\s*$", line) is not None
  156. def get_indent(line):
  157. """Return the initial space or tab indent of line."""
  158. return re.match(r"^([ \t]*)", line).group()
  159. def get_comment_header(line):
  160. """Return string with leading whitespace and '#' from line or ''.
  161. A null return indicates that the line is not a comment line. A non-
  162. null return, such as ' #', will be used to find the other lines of
  163. a comment block with the same indent.
  164. """
  165. m = re.match(r"^([ \t]*#*)", line)
  166. if m is None: return ""
  167. return m.group(1)
  168. # Copied from editor.py; importing it would cause an import cycle.
  169. _line_indent_re = re.compile(r'[ \t]*')
  170. def get_line_indent(line, tabwidth):
  171. """Return a line's indentation as (# chars, effective # of spaces).
  172. The effective # of spaces is the length after properly "expanding"
  173. the tabs into spaces, as done by str.expandtabs(tabwidth).
  174. """
  175. m = _line_indent_re.match(line)
  176. return m.end(), len(m.group().expandtabs(tabwidth))
  177. class FormatRegion:
  178. "Format selected text (region)."
  179. def __init__(self, editwin):
  180. self.editwin = editwin
  181. def get_region(self):
  182. """Return line information about the selected text region.
  183. If text is selected, the first and last indices will be
  184. for the selection. If there is no text selected, the
  185. indices will be the current cursor location.
  186. Return a tuple containing (first index, last index,
  187. string representation of text, list of text lines).
  188. """
  189. text = self.editwin.text
  190. first, last = self.editwin.get_selection_indices()
  191. if first and last:
  192. head = text.index(first + " linestart")
  193. tail = text.index(last + "-1c lineend +1c")
  194. else:
  195. head = text.index("insert linestart")
  196. tail = text.index("insert lineend +1c")
  197. chars = text.get(head, tail)
  198. lines = chars.split("\n")
  199. return head, tail, chars, lines
  200. def set_region(self, head, tail, chars, lines):
  201. """Replace the text between the given indices.
  202. Args:
  203. head: Starting index of text to replace.
  204. tail: Ending index of text to replace.
  205. chars: Expected to be string of current text
  206. between head and tail.
  207. lines: List of new lines to insert between head
  208. and tail.
  209. """
  210. text = self.editwin.text
  211. newchars = "\n".join(lines)
  212. if newchars == chars:
  213. text.bell()
  214. return
  215. text.tag_remove("sel", "1.0", "end")
  216. text.mark_set("insert", head)
  217. text.undo_block_start()
  218. text.delete(head, tail)
  219. text.insert(head, newchars)
  220. text.undo_block_stop()
  221. text.tag_add("sel", head, "insert")
  222. def indent_region_event(self, event=None):
  223. "Indent region by indentwidth spaces."
  224. head, tail, chars, lines = self.get_region()
  225. for pos in range(len(lines)):
  226. line = lines[pos]
  227. if line:
  228. raw, effective = get_line_indent(line, self.editwin.tabwidth)
  229. effective = effective + self.editwin.indentwidth
  230. lines[pos] = self.editwin._make_blanks(effective) + line[raw:]
  231. self.set_region(head, tail, chars, lines)
  232. return "break"
  233. def dedent_region_event(self, event=None):
  234. "Dedent region by indentwidth spaces."
  235. head, tail, chars, lines = self.get_region()
  236. for pos in range(len(lines)):
  237. line = lines[pos]
  238. if line:
  239. raw, effective = get_line_indent(line, self.editwin.tabwidth)
  240. effective = max(effective - self.editwin.indentwidth, 0)
  241. lines[pos] = self.editwin._make_blanks(effective) + line[raw:]
  242. self.set_region(head, tail, chars, lines)
  243. return "break"
  244. def comment_region_event(self, event=None):
  245. """Comment out each line in region.
  246. ## is appended to the beginning of each line to comment it out.
  247. """
  248. head, tail, chars, lines = self.get_region()
  249. for pos in range(len(lines) - 1):
  250. line = lines[pos]
  251. lines[pos] = '##' + line
  252. self.set_region(head, tail, chars, lines)
  253. return "break"
  254. def uncomment_region_event(self, event=None):
  255. """Uncomment each line in region.
  256. Remove ## or # in the first positions of a line. If the comment
  257. is not in the beginning position, this command will have no effect.
  258. """
  259. head, tail, chars, lines = self.get_region()
  260. for pos in range(len(lines)):
  261. line = lines[pos]
  262. if not line:
  263. continue
  264. if line[:2] == '##':
  265. line = line[2:]
  266. elif line[:1] == '#':
  267. line = line[1:]
  268. lines[pos] = line
  269. self.set_region(head, tail, chars, lines)
  270. return "break"
  271. def tabify_region_event(self, event=None):
  272. "Convert leading spaces to tabs for each line in selected region."
  273. head, tail, chars, lines = self.get_region()
  274. tabwidth = self._asktabwidth()
  275. if tabwidth is None:
  276. return
  277. for pos in range(len(lines)):
  278. line = lines[pos]
  279. if line:
  280. raw, effective = get_line_indent(line, tabwidth)
  281. ntabs, nspaces = divmod(effective, tabwidth)
  282. lines[pos] = '\t' * ntabs + ' ' * nspaces + line[raw:]
  283. self.set_region(head, tail, chars, lines)
  284. return "break"
  285. def untabify_region_event(self, event=None):
  286. "Expand tabs to spaces for each line in region."
  287. head, tail, chars, lines = self.get_region()
  288. tabwidth = self._asktabwidth()
  289. if tabwidth is None:
  290. return
  291. for pos in range(len(lines)):
  292. lines[pos] = lines[pos].expandtabs(tabwidth)
  293. self.set_region(head, tail, chars, lines)
  294. return "break"
  295. def _asktabwidth(self):
  296. "Return value for tab width."
  297. return askinteger(
  298. "Tab width",
  299. "Columns per tab? (2-16)",
  300. parent=self.editwin.text,
  301. initialvalue=self.editwin.indentwidth,
  302. minvalue=2,
  303. maxvalue=16)
  304. class Indents:
  305. "Change future indents."
  306. def __init__(self, editwin):
  307. self.editwin = editwin
  308. def toggle_tabs_event(self, event):
  309. editwin = self.editwin
  310. usetabs = editwin.usetabs
  311. if askyesno(
  312. "Toggle tabs",
  313. "Turn tabs " + ("on", "off")[usetabs] +
  314. "?\nIndent width " +
  315. ("will be", "remains at")[usetabs] + " 8." +
  316. "\n Note: a tab is always 8 columns",
  317. parent=editwin.text):
  318. editwin.usetabs = not usetabs
  319. # Try to prevent inconsistent indentation.
  320. # User must change indent width manually after using tabs.
  321. editwin.indentwidth = 8
  322. return "break"
  323. def change_indentwidth_event(self, event):
  324. editwin = self.editwin
  325. new = askinteger(
  326. "Indent width",
  327. "New indent width (2-16)\n(Always use 8 when using tabs)",
  328. parent=editwin.text,
  329. initialvalue=editwin.indentwidth,
  330. minvalue=2,
  331. maxvalue=16)
  332. if new and new != editwin.indentwidth and not editwin.usetabs:
  333. editwin.indentwidth = new
  334. return "break"
  335. class Rstrip: # 'Strip Trailing Whitespace" on "Format" menu.
  336. def __init__(self, editwin):
  337. self.editwin = editwin
  338. def do_rstrip(self, event=None):
  339. text = self.editwin.text
  340. undo = self.editwin.undo
  341. undo.undo_block_start()
  342. end_line = int(float(text.index('end')))
  343. for cur in range(1, end_line):
  344. txt = text.get('%i.0' % cur, '%i.end' % cur)
  345. raw = len(txt)
  346. cut = len(txt.rstrip())
  347. # Since text.delete() marks file as changed, even if not,
  348. # only call it when needed to actually delete something.
  349. if cut < raw:
  350. text.delete('%i.%i' % (cur, cut), '%i.end' % cur)
  351. if (text.get('end-2c') == '\n' # File ends with at least 1 newline;
  352. and not hasattr(self.editwin, 'interp')): # & is not Shell.
  353. # Delete extra user endlines.
  354. while (text.index('end-1c') > '1.0' # Stop if file empty.
  355. and text.get('end-3c') == '\n'):
  356. text.delete('end-3c')
  357. # Because tk indexes are slice indexes and never raise,
  358. # a file with only newlines will be emptied.
  359. # patchcheck.py does the same.
  360. undo.undo_block_stop()
  361. if __name__ == "__main__":
  362. from unittest import main
  363. main('idlelib.idle_test.test_format', verbosity=2, exit=False)