help.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. """ help.py: Implement the Idle help menu.
  2. Contents are subject to revision at any time, without notice.
  3. Help => About IDLE: display About Idle dialog
  4. <to be moved here from help_about.py>
  5. Help => IDLE Help: Display help.html with proper formatting.
  6. Doc/library/idle.rst (Sphinx)=> Doc/build/html/library/idle.html
  7. (help.copy_strip)=> Lib/idlelib/help.html
  8. HelpParser - Parse help.html and render to tk Text.
  9. HelpText - Display formatted help.html.
  10. HelpFrame - Contain text, scrollbar, and table-of-contents.
  11. (This will be needed for display in a future tabbed window.)
  12. HelpWindow - Display HelpFrame in a standalone window.
  13. copy_strip - Copy idle.html to help.html, rstripping each line.
  14. show_idlehelp - Create HelpWindow. Called in EditorWindow.help_dialog.
  15. """
  16. from html.parser import HTMLParser
  17. from os.path import abspath, dirname, isfile, join
  18. from platform import python_version
  19. from tkinter import Toplevel, Text, Menu
  20. from tkinter.ttk import Frame, Menubutton, Scrollbar, Style
  21. from tkinter import font as tkfont
  22. from idlelib.config import idleConf
  23. ## About IDLE ##
  24. ## IDLE Help ##
  25. class HelpParser(HTMLParser):
  26. """Render help.html into a text widget.
  27. The overridden handle_xyz methods handle a subset of html tags.
  28. The supplied text should have the needed tag configurations.
  29. The behavior for unsupported tags, such as table, is undefined.
  30. If the tags generated by Sphinx change, this class, especially
  31. the handle_starttag and handle_endtags methods, might have to also.
  32. """
  33. def __init__(self, text):
  34. HTMLParser.__init__(self, convert_charrefs=True)
  35. self.text = text # Text widget we're rendering into.
  36. self.tags = '' # Current block level text tags to apply.
  37. self.chartags = '' # Current character level text tags.
  38. self.show = False # Exclude html page navigation.
  39. self.hdrlink = False # Exclude html header links.
  40. self.level = 0 # Track indentation level.
  41. self.pre = False # Displaying preformatted text?
  42. self.hprefix = '' # Heading prefix (like '25.5'?) to remove.
  43. self.nested_dl = False # In a nested <dl>?
  44. self.simplelist = False # In a simple list (no double spacing)?
  45. self.toc = [] # Pair headers with text indexes for toc.
  46. self.header = '' # Text within header tags for toc.
  47. self.prevtag = None # Previous tag info (opener?, tag).
  48. def indent(self, amt=1):
  49. "Change indent (+1, 0, -1) and tags."
  50. self.level += amt
  51. self.tags = '' if self.level == 0 else 'l'+str(self.level)
  52. def handle_starttag(self, tag, attrs):
  53. "Handle starttags in help.html."
  54. class_ = ''
  55. for a, v in attrs:
  56. if a == 'class':
  57. class_ = v
  58. s = ''
  59. if tag == 'section' and attrs == [('id', 'idle')]:
  60. self.show = True # Start main content.
  61. elif tag == 'div' and class_ == 'clearer':
  62. self.show = False # End main content.
  63. elif tag == 'p' and self.prevtag and not self.prevtag[0]:
  64. # Begin a new block for <p> tags after a closed tag.
  65. # Avoid extra lines, e.g. after <pre> tags.
  66. lastline = self.text.get('end-1c linestart', 'end-1c')
  67. s = '\n\n' if lastline and not lastline.isspace() else '\n'
  68. elif tag == 'span' and class_ == 'pre':
  69. self.chartags = 'pre'
  70. elif tag == 'span' and class_ == 'versionmodified':
  71. self.chartags = 'em'
  72. elif tag == 'em':
  73. self.chartags = 'em'
  74. elif tag in ['ul', 'ol']:
  75. if class_.find('simple') != -1:
  76. s = '\n'
  77. self.simplelist = True
  78. else:
  79. self.simplelist = False
  80. self.indent()
  81. elif tag == 'dl':
  82. if self.level > 0:
  83. self.nested_dl = True
  84. elif tag == 'li':
  85. s = '\n* ' if self.simplelist else '\n\n* '
  86. elif tag == 'dt':
  87. s = '\n\n' if not self.nested_dl else '\n' # Avoid extra line.
  88. self.nested_dl = False
  89. elif tag == 'dd':
  90. self.indent()
  91. s = '\n'
  92. elif tag == 'pre':
  93. self.pre = True
  94. if self.show:
  95. self.text.insert('end', '\n\n')
  96. self.tags = 'preblock'
  97. elif tag == 'a' and class_ == 'headerlink':
  98. self.hdrlink = True
  99. elif tag == 'h1':
  100. self.tags = tag
  101. elif tag in ['h2', 'h3']:
  102. if self.show:
  103. self.header = ''
  104. self.text.insert('end', '\n\n')
  105. self.tags = tag
  106. if self.show:
  107. self.text.insert('end', s, (self.tags, self.chartags))
  108. self.prevtag = (True, tag)
  109. def handle_endtag(self, tag):
  110. "Handle endtags in help.html."
  111. if tag in ['h1', 'h2', 'h3']:
  112. assert self.level == 0
  113. if self.show:
  114. indent = (' ' if tag == 'h3' else
  115. ' ' if tag == 'h2' else
  116. '')
  117. self.toc.append((indent+self.header, self.text.index('insert')))
  118. self.tags = ''
  119. elif tag in ['span', 'em']:
  120. self.chartags = ''
  121. elif tag == 'a':
  122. self.hdrlink = False
  123. elif tag == 'pre':
  124. self.pre = False
  125. self.tags = ''
  126. elif tag in ['ul', 'dd', 'ol']:
  127. self.indent(-1)
  128. self.prevtag = (False, tag)
  129. def handle_data(self, data):
  130. "Handle date segments in help.html."
  131. if self.show and not self.hdrlink:
  132. d = data if self.pre else data.replace('\n', ' ')
  133. if self.tags == 'h1':
  134. try:
  135. self.hprefix = d[0:d.index(' ')]
  136. except ValueError:
  137. self.hprefix = ''
  138. if self.tags in ['h1', 'h2', 'h3']:
  139. if (self.hprefix != '' and
  140. d[0:len(self.hprefix)] == self.hprefix):
  141. d = d[len(self.hprefix):]
  142. self.header += d.strip()
  143. self.text.insert('end', d, (self.tags, self.chartags))
  144. class HelpText(Text):
  145. "Display help.html."
  146. def __init__(self, parent, filename):
  147. "Configure tags and feed file to parser."
  148. uwide = idleConf.GetOption('main', 'EditorWindow', 'width', type='int')
  149. uhigh = idleConf.GetOption('main', 'EditorWindow', 'height', type='int')
  150. uhigh = 3 * uhigh // 4 # Lines average 4/3 of editor line height.
  151. Text.__init__(self, parent, wrap='word', highlightthickness=0,
  152. padx=5, borderwidth=0, width=uwide, height=uhigh)
  153. normalfont = self.findfont(['TkDefaultFont', 'arial', 'helvetica'])
  154. fixedfont = self.findfont(['TkFixedFont', 'monaco', 'courier'])
  155. self['font'] = (normalfont, 12)
  156. self.tag_configure('em', font=(normalfont, 12, 'italic'))
  157. self.tag_configure('h1', font=(normalfont, 20, 'bold'))
  158. self.tag_configure('h2', font=(normalfont, 18, 'bold'))
  159. self.tag_configure('h3', font=(normalfont, 15, 'bold'))
  160. self.tag_configure('pre', font=(fixedfont, 12), background='#f6f6ff')
  161. self.tag_configure('preblock', font=(fixedfont, 10), lmargin1=25,
  162. borderwidth=1, relief='solid', background='#eeffcc')
  163. self.tag_configure('l1', lmargin1=25, lmargin2=25)
  164. self.tag_configure('l2', lmargin1=50, lmargin2=50)
  165. self.tag_configure('l3', lmargin1=75, lmargin2=75)
  166. self.tag_configure('l4', lmargin1=100, lmargin2=100)
  167. self.parser = HelpParser(self)
  168. with open(filename, encoding='utf-8') as f:
  169. contents = f.read()
  170. self.parser.feed(contents)
  171. self['state'] = 'disabled'
  172. def findfont(self, names):
  173. "Return name of first font family derived from names."
  174. for name in names:
  175. if name.lower() in (x.lower() for x in tkfont.names(root=self)):
  176. font = tkfont.Font(name=name, exists=True, root=self)
  177. return font.actual()['family']
  178. elif name.lower() in (x.lower()
  179. for x in tkfont.families(root=self)):
  180. return name
  181. class HelpFrame(Frame):
  182. "Display html text, scrollbar, and toc."
  183. def __init__(self, parent, filename):
  184. Frame.__init__(self, parent)
  185. self.text = text = HelpText(self, filename)
  186. self.style = Style(parent)
  187. self['style'] = 'helpframe.TFrame'
  188. self.style.configure('helpframe.TFrame', background=text['background'])
  189. self.toc = toc = self.toc_menu(text)
  190. self.scroll = scroll = Scrollbar(self, command=text.yview)
  191. text['yscrollcommand'] = scroll.set
  192. self.rowconfigure(0, weight=1)
  193. self.columnconfigure(1, weight=1) # Only expand the text widget.
  194. toc.grid(row=0, column=0, sticky='nw')
  195. text.grid(row=0, column=1, sticky='nsew')
  196. scroll.grid(row=0, column=2, sticky='ns')
  197. def toc_menu(self, text):
  198. "Create table of contents as drop-down menu."
  199. toc = Menubutton(self, text='TOC')
  200. drop = Menu(toc, tearoff=False)
  201. for lbl, dex in text.parser.toc:
  202. drop.add_command(label=lbl, command=lambda dex=dex:text.yview(dex))
  203. toc['menu'] = drop
  204. return toc
  205. class HelpWindow(Toplevel):
  206. "Display frame with rendered html."
  207. def __init__(self, parent, filename, title):
  208. Toplevel.__init__(self, parent)
  209. self.wm_title(title)
  210. self.protocol("WM_DELETE_WINDOW", self.destroy)
  211. HelpFrame(self, filename).grid(column=0, row=0, sticky='nsew')
  212. self.grid_columnconfigure(0, weight=1)
  213. self.grid_rowconfigure(0, weight=1)
  214. def copy_strip():
  215. """Copy idle.html to idlelib/help.html, stripping trailing whitespace.
  216. Files with trailing whitespace cannot be pushed to the git cpython
  217. repository. For 3.x (on Windows), help.html is generated, after
  218. editing idle.rst on the master branch, with
  219. sphinx-build -bhtml . build/html
  220. python_d.exe -c "from idlelib.help import copy_strip; copy_strip()"
  221. Check build/html/library/idle.html, the help.html diff, and the text
  222. displayed by Help => IDLE Help. Add a blurb and create a PR.
  223. It can be worthwhile to occasionally generate help.html without
  224. touching idle.rst. Changes to the master version and to the doc
  225. build system may result in changes that should not changed
  226. the displayed text, but might break HelpParser.
  227. As long as master and maintenance versions of idle.rst remain the
  228. same, help.html can be backported. The internal Python version
  229. number is not displayed. If maintenance idle.rst diverges from
  230. the master version, then instead of backporting help.html from
  231. master, repeat the procedure above to generate a maintenance
  232. version.
  233. """
  234. src = join(abspath(dirname(dirname(dirname(__file__)))),
  235. 'Doc', 'build', 'html', 'library', 'idle.html')
  236. dst = join(abspath(dirname(__file__)), 'help.html')
  237. with open(src, 'rb') as inn,\
  238. open(dst, 'wb') as out:
  239. for line in inn:
  240. out.write(line.rstrip() + b'\n')
  241. print(f'{src} copied to {dst}')
  242. def show_idlehelp(parent):
  243. "Create HelpWindow; called from Idle Help event handler."
  244. filename = join(abspath(dirname(__file__)), 'help.html')
  245. if not isfile(filename):
  246. # Try copy_strip, present message.
  247. return
  248. HelpWindow(parent, filename, 'IDLE Help (%s)' % python_version())
  249. if __name__ == '__main__':
  250. from unittest import main
  251. main('idlelib.idle_test.test_help', verbosity=2, exit=False)
  252. from idlelib.idle_test.htest import run
  253. run(show_idlehelp)