jpayne@68: """ help.py: Implement the Idle help menu. jpayne@68: Contents are subject to revision at any time, without notice. jpayne@68: jpayne@68: jpayne@68: Help => About IDLE: display About Idle dialog jpayne@68: jpayne@68: jpayne@68: jpayne@68: jpayne@68: Help => IDLE Help: Display help.html with proper formatting. jpayne@68: Doc/library/idle.rst (Sphinx)=> Doc/build/html/library/idle.html jpayne@68: (help.copy_strip)=> Lib/idlelib/help.html jpayne@68: jpayne@68: HelpParser - Parse help.html and render to tk Text. jpayne@68: jpayne@68: HelpText - Display formatted help.html. jpayne@68: jpayne@68: HelpFrame - Contain text, scrollbar, and table-of-contents. jpayne@68: (This will be needed for display in a future tabbed window.) jpayne@68: jpayne@68: HelpWindow - Display HelpFrame in a standalone window. jpayne@68: jpayne@68: copy_strip - Copy idle.html to help.html, rstripping each line. jpayne@68: jpayne@68: show_idlehelp - Create HelpWindow. Called in EditorWindow.help_dialog. jpayne@68: """ jpayne@68: from html.parser import HTMLParser jpayne@68: from os.path import abspath, dirname, isfile, join jpayne@68: from platform import python_version jpayne@68: jpayne@68: from tkinter import Toplevel, Frame, Text, Menu jpayne@68: from tkinter.ttk import Menubutton, Scrollbar jpayne@68: from tkinter import font as tkfont jpayne@68: jpayne@68: from idlelib.config import idleConf jpayne@68: jpayne@68: ## About IDLE ## jpayne@68: jpayne@68: jpayne@68: ## IDLE Help ## jpayne@68: jpayne@68: class HelpParser(HTMLParser): jpayne@68: """Render help.html into a text widget. jpayne@68: jpayne@68: The overridden handle_xyz methods handle a subset of html tags. jpayne@68: The supplied text should have the needed tag configurations. jpayne@68: The behavior for unsupported tags, such as table, is undefined. jpayne@68: If the tags generated by Sphinx change, this class, especially jpayne@68: the handle_starttag and handle_endtags methods, might have to also. jpayne@68: """ jpayne@68: def __init__(self, text): jpayne@68: HTMLParser.__init__(self, convert_charrefs=True) jpayne@68: self.text = text # Text widget we're rendering into. jpayne@68: self.tags = '' # Current block level text tags to apply. jpayne@68: self.chartags = '' # Current character level text tags. jpayne@68: self.show = False # Exclude html page navigation. jpayne@68: self.hdrlink = False # Exclude html header links. jpayne@68: self.level = 0 # Track indentation level. jpayne@68: self.pre = False # Displaying preformatted text? jpayne@68: self.hprefix = '' # Heading prefix (like '25.5'?) to remove. jpayne@68: self.nested_dl = False # In a nested
? jpayne@68: self.simplelist = False # In a simple list (no double spacing)? jpayne@68: self.toc = [] # Pair headers with text indexes for toc. jpayne@68: self.header = '' # Text within header tags for toc. jpayne@68: self.prevtag = None # Previous tag info (opener?, tag). jpayne@68: jpayne@68: def indent(self, amt=1): jpayne@68: "Change indent (+1, 0, -1) and tags." jpayne@68: self.level += amt jpayne@68: self.tags = '' if self.level == 0 else 'l'+str(self.level) jpayne@68: jpayne@68: def handle_starttag(self, tag, attrs): jpayne@68: "Handle starttags in help.html." jpayne@68: class_ = '' jpayne@68: for a, v in attrs: jpayne@68: if a == 'class': jpayne@68: class_ = v jpayne@68: s = '' jpayne@68: if tag == 'div' and class_ == 'section': jpayne@68: self.show = True # Start main content. jpayne@68: elif tag == 'div' and class_ == 'sphinxsidebar': jpayne@68: self.show = False # End main content. jpayne@68: elif tag == 'p' and self.prevtag and not self.prevtag[0]: jpayne@68: # Begin a new block for

tags after a closed tag. jpayne@68: # Avoid extra lines, e.g. after

 tags.
jpayne@68:             lastline = self.text.get('end-1c linestart', 'end-1c')
jpayne@68:             s = '\n\n' if lastline and not lastline.isspace() else '\n'
jpayne@68:         elif tag == 'span' and class_ == 'pre':
jpayne@68:             self.chartags = 'pre'
jpayne@68:         elif tag == 'span' and class_ == 'versionmodified':
jpayne@68:             self.chartags = 'em'
jpayne@68:         elif tag == 'em':
jpayne@68:             self.chartags = 'em'
jpayne@68:         elif tag in ['ul', 'ol']:
jpayne@68:             if class_.find('simple') != -1:
jpayne@68:                 s = '\n'
jpayne@68:                 self.simplelist = True
jpayne@68:             else:
jpayne@68:                 self.simplelist = False
jpayne@68:             self.indent()
jpayne@68:         elif tag == 'dl':
jpayne@68:             if self.level > 0:
jpayne@68:                 self.nested_dl = True
jpayne@68:         elif tag == 'li':
jpayne@68:             s = '\n* ' if self.simplelist else '\n\n* '
jpayne@68:         elif tag == 'dt':
jpayne@68:             s = '\n\n' if not self.nested_dl else '\n'  # Avoid extra line.
jpayne@68:             self.nested_dl = False
jpayne@68:         elif tag == 'dd':
jpayne@68:             self.indent()
jpayne@68:             s = '\n'
jpayne@68:         elif tag == 'pre':
jpayne@68:             self.pre = True
jpayne@68:             if self.show:
jpayne@68:                 self.text.insert('end', '\n\n')
jpayne@68:             self.tags = 'preblock'
jpayne@68:         elif tag == 'a' and class_ == 'headerlink':
jpayne@68:             self.hdrlink = True
jpayne@68:         elif tag == 'h1':
jpayne@68:             self.tags = tag
jpayne@68:         elif tag in ['h2', 'h3']:
jpayne@68:             if self.show:
jpayne@68:                 self.header = ''
jpayne@68:                 self.text.insert('end', '\n\n')
jpayne@68:             self.tags = tag
jpayne@68:         if self.show:
jpayne@68:             self.text.insert('end', s, (self.tags, self.chartags))
jpayne@68:         self.prevtag = (True, tag)
jpayne@68: 
jpayne@68:     def handle_endtag(self, tag):
jpayne@68:         "Handle endtags in help.html."
jpayne@68:         if tag in ['h1', 'h2', 'h3']:
jpayne@68:             assert self.level == 0
jpayne@68:             if self.show:
jpayne@68:                 indent = ('        ' if tag == 'h3' else
jpayne@68:                           '    ' if tag == 'h2' else
jpayne@68:                           '')
jpayne@68:                 self.toc.append((indent+self.header, self.text.index('insert')))
jpayne@68:             self.tags = ''
jpayne@68:         elif tag in ['span', 'em']:
jpayne@68:             self.chartags = ''
jpayne@68:         elif tag == 'a':
jpayne@68:             self.hdrlink = False
jpayne@68:         elif tag == 'pre':
jpayne@68:             self.pre = False
jpayne@68:             self.tags = ''
jpayne@68:         elif tag in ['ul', 'dd', 'ol']:
jpayne@68:             self.indent(-1)
jpayne@68:         self.prevtag = (False, tag)
jpayne@68: 
jpayne@68:     def handle_data(self, data):
jpayne@68:         "Handle date segments in help.html."
jpayne@68:         if self.show and not self.hdrlink:
jpayne@68:             d = data if self.pre else data.replace('\n', ' ')
jpayne@68:             if self.tags == 'h1':
jpayne@68:                 try:
jpayne@68:                     self.hprefix = d[0:d.index(' ')]
jpayne@68:                 except ValueError:
jpayne@68:                     self.hprefix = ''
jpayne@68:             if self.tags in ['h1', 'h2', 'h3']:
jpayne@68:                 if (self.hprefix != '' and
jpayne@68:                     d[0:len(self.hprefix)] == self.hprefix):
jpayne@68:                     d = d[len(self.hprefix):]
jpayne@68:                 self.header += d.strip()
jpayne@68:             self.text.insert('end', d, (self.tags, self.chartags))
jpayne@68: 
jpayne@68: 
jpayne@68: class HelpText(Text):
jpayne@68:     "Display help.html."
jpayne@68:     def __init__(self, parent, filename):
jpayne@68:         "Configure tags and feed file to parser."
jpayne@68:         uwide = idleConf.GetOption('main', 'EditorWindow', 'width', type='int')
jpayne@68:         uhigh = idleConf.GetOption('main', 'EditorWindow', 'height', type='int')
jpayne@68:         uhigh = 3 * uhigh // 4  # Lines average 4/3 of editor line height.
jpayne@68:         Text.__init__(self, parent, wrap='word', highlightthickness=0,
jpayne@68:                       padx=5, borderwidth=0, width=uwide, height=uhigh)
jpayne@68: 
jpayne@68:         normalfont = self.findfont(['TkDefaultFont', 'arial', 'helvetica'])
jpayne@68:         fixedfont = self.findfont(['TkFixedFont', 'monaco', 'courier'])
jpayne@68:         self['font'] = (normalfont, 12)
jpayne@68:         self.tag_configure('em', font=(normalfont, 12, 'italic'))
jpayne@68:         self.tag_configure('h1', font=(normalfont, 20, 'bold'))
jpayne@68:         self.tag_configure('h2', font=(normalfont, 18, 'bold'))
jpayne@68:         self.tag_configure('h3', font=(normalfont, 15, 'bold'))
jpayne@68:         self.tag_configure('pre', font=(fixedfont, 12), background='#f6f6ff')
jpayne@68:         self.tag_configure('preblock', font=(fixedfont, 10), lmargin1=25,
jpayne@68:                 borderwidth=1, relief='solid', background='#eeffcc')
jpayne@68:         self.tag_configure('l1', lmargin1=25, lmargin2=25)
jpayne@68:         self.tag_configure('l2', lmargin1=50, lmargin2=50)
jpayne@68:         self.tag_configure('l3', lmargin1=75, lmargin2=75)
jpayne@68:         self.tag_configure('l4', lmargin1=100, lmargin2=100)
jpayne@68: 
jpayne@68:         self.parser = HelpParser(self)
jpayne@68:         with open(filename, encoding='utf-8') as f:
jpayne@68:             contents = f.read()
jpayne@68:         self.parser.feed(contents)
jpayne@68:         self['state'] = 'disabled'
jpayne@68: 
jpayne@68:     def findfont(self, names):
jpayne@68:         "Return name of first font family derived from names."
jpayne@68:         for name in names:
jpayne@68:             if name.lower() in (x.lower() for x in tkfont.names(root=self)):
jpayne@68:                 font = tkfont.Font(name=name, exists=True, root=self)
jpayne@68:                 return font.actual()['family']
jpayne@68:             elif name.lower() in (x.lower()
jpayne@68:                                   for x in tkfont.families(root=self)):
jpayne@68:                 return name
jpayne@68: 
jpayne@68: 
jpayne@68: class HelpFrame(Frame):
jpayne@68:     "Display html text, scrollbar, and toc."
jpayne@68:     def __init__(self, parent, filename):
jpayne@68:         Frame.__init__(self, parent)
jpayne@68:         self.text = text = HelpText(self, filename)
jpayne@68:         self['background'] = text['background']
jpayne@68:         self.toc = toc = self.toc_menu(text)
jpayne@68:         self.scroll = scroll = Scrollbar(self, command=text.yview)
jpayne@68:         text['yscrollcommand'] = scroll.set
jpayne@68: 
jpayne@68:         self.rowconfigure(0, weight=1)
jpayne@68:         self.columnconfigure(1, weight=1)  # Only expand the text widget.
jpayne@68:         toc.grid(row=0, column=0, sticky='nw')
jpayne@68:         text.grid(row=0, column=1, sticky='nsew')
jpayne@68:         scroll.grid(row=0, column=2, sticky='ns')
jpayne@68: 
jpayne@68:     def toc_menu(self, text):
jpayne@68:         "Create table of contents as drop-down menu."
jpayne@68:         toc = Menubutton(self, text='TOC')
jpayne@68:         drop = Menu(toc, tearoff=False)
jpayne@68:         for lbl, dex in text.parser.toc:
jpayne@68:             drop.add_command(label=lbl, command=lambda dex=dex:text.yview(dex))
jpayne@68:         toc['menu'] = drop
jpayne@68:         return toc
jpayne@68: 
jpayne@68: 
jpayne@68: class HelpWindow(Toplevel):
jpayne@68:     "Display frame with rendered html."
jpayne@68:     def __init__(self, parent, filename, title):
jpayne@68:         Toplevel.__init__(self, parent)
jpayne@68:         self.wm_title(title)
jpayne@68:         self.protocol("WM_DELETE_WINDOW", self.destroy)
jpayne@68:         HelpFrame(self, filename).grid(column=0, row=0, sticky='nsew')
jpayne@68:         self.grid_columnconfigure(0, weight=1)
jpayne@68:         self.grid_rowconfigure(0, weight=1)
jpayne@68: 
jpayne@68: 
jpayne@68: def copy_strip():
jpayne@68:     """Copy idle.html to idlelib/help.html, stripping trailing whitespace.
jpayne@68: 
jpayne@68:     Files with trailing whitespace cannot be pushed to the git cpython
jpayne@68:     repository.  For 3.x (on Windows), help.html is generated, after
jpayne@68:     editing idle.rst on the master branch, with
jpayne@68:       sphinx-build -bhtml . build/html
jpayne@68:       python_d.exe -c "from idlelib.help import copy_strip; copy_strip()"
jpayne@68:     Check build/html/library/idle.html, the help.html diff, and the text
jpayne@68:     displayed by Help => IDLE Help.  Add a blurb and create a PR.
jpayne@68: 
jpayne@68:     It can be worthwhile to occasionally generate help.html without
jpayne@68:     touching idle.rst.  Changes to the master version and to the doc
jpayne@68:     build system may result in changes that should not changed
jpayne@68:     the displayed text, but might break HelpParser.
jpayne@68: 
jpayne@68:     As long as master and maintenance versions of idle.rst remain the
jpayne@68:     same, help.html can be backported.  The internal Python version
jpayne@68:     number is not displayed.  If maintenance idle.rst diverges from
jpayne@68:     the master version, then instead of backporting help.html from
jpayne@68:     master, repeat the procedure above to generate a maintenance
jpayne@68:     version.
jpayne@68:     """
jpayne@68:     src = join(abspath(dirname(dirname(dirname(__file__)))),
jpayne@68:             'Doc', 'build', 'html', 'library', 'idle.html')
jpayne@68:     dst = join(abspath(dirname(__file__)), 'help.html')
jpayne@68:     with open(src, 'rb') as inn,\
jpayne@68:          open(dst, 'wb') as out:
jpayne@68:         for line in inn:
jpayne@68:             out.write(line.rstrip() + b'\n')
jpayne@68:     print(f'{src} copied to {dst}')
jpayne@68: 
jpayne@68: def show_idlehelp(parent):
jpayne@68:     "Create HelpWindow; called from Idle Help event handler."
jpayne@68:     filename = join(abspath(dirname(__file__)), 'help.html')
jpayne@68:     if not isfile(filename):
jpayne@68:         # Try copy_strip, present message.
jpayne@68:         return
jpayne@68:     HelpWindow(parent, filename, 'IDLE Help (%s)' % python_version())
jpayne@68: 
jpayne@68: if __name__ == '__main__':
jpayne@68:     from unittest import main
jpayne@68:     main('idlelib.idle_test.test_help', verbosity=2, exit=False)
jpayne@68: 
jpayne@68:     from idlelib.idle_test.htest import run
jpayne@68:     run(show_idlehelp)