| 1 |
""" help.py: Implement the Idle help menu. |
| 2 |
Contents are subject to revision at any time, without notice. |
| 3 |
|
| 4 |
|
| 5 |
Help => About IDLE: display About Idle dialog |
| 6 |
|
| 7 |
<to be moved here from help_about.py> |
| 8 |
|
| 9 |
|
| 10 |
Help => IDLE Help: Display help.html with proper formatting. |
| 11 |
Doc/library/idle.rst (Sphinx)=> Doc/build/html/library/idle.html |
| 12 |
(help.copy_strip)=> Lib/idlelib/help.html |
| 13 |
|
| 14 |
HelpParser - Parse help.html and render to tk Text. |
| 15 |
|
| 16 |
HelpText - Display formatted help.html. |
| 17 |
|
| 18 |
HelpFrame - Contain text, scrollbar, and table-of-contents. |
| 19 |
(This will be needed for display in a future tabbed window.) |
| 20 |
|
| 21 |
HelpWindow - Display HelpFrame in a standalone window. |
| 22 |
|
| 23 |
copy_strip - Copy the text part of idle.html to help.html while rstripping each line. |
| 24 |
|
| 25 |
show_idlehelp - Create HelpWindow. Called in EditorWindow.help_dialog. |
| 26 |
|
| 27 |
_get_dochome() - Return path to docs on user's system if present, |
| 28 |
otherwise return link to docs.python.org. |
| 29 |
""" |
| 30 |
import os |
| 31 |
import sys |
| 32 |
from html.parser import HTMLParser |
| 33 |
from os.path import abspath, dirname, isfile, join |
| 34 |
from platform import python_version |
| 35 |
|
| 36 |
from tkinter import Toplevel, Text, Menu |
| 37 |
from tkinter.ttk import Frame, Menubutton, Scrollbar, Style |
| 38 |
from tkinter import font as tkfont |
| 39 |
|
| 40 |
from idlelib.config import idleConf |
| 41 |
from idlelib.colorizer import color_config |
| 42 |
|
| 43 |
## About IDLE ## |
| 44 |
|
| 45 |
|
| 46 |
## IDLE Help ## |
| 47 |
|
| 48 |
class HelpParser(HTMLParser): |
| 49 |
"""Render help.html into a text widget. |
| 50 |
|
| 51 |
The overridden handle_xyz methods handle a subset of html tags. |
| 52 |
The supplied text should have the needed tag configurations. |
| 53 |
The behavior for unsupported tags, such as table, is undefined. |
| 54 |
If the tags generated by Sphinx change, this class, especially |
| 55 |
the handle_starttag and handle_endtags methods, might have to also. |
| 56 |
""" |
| 57 |
def __init__(self, text): |
| 58 |
HTMLParser.__init__(self, convert_charrefs=True) |
| 59 |
self.text = text # Text widget we're rendering into. |
| 60 |
self.tags = '' # Current block level text tags to apply. |
| 61 |
self.chartags = '' # Current character level text tags. |
| 62 |
self.hdrlink = False # Exclude html header links. |
| 63 |
self.level = 0 # Track indentation level. |
| 64 |
self.pre = False # Displaying preformatted text? |
| 65 |
self.hprefix = '' # Heading prefix (like '25.5'?) to remove. |
| 66 |
self.nested_dl = False # In a nested <dl>? |
| 67 |
self.simplelist = False # In a simple list (no double spacing)? |
| 68 |
self.toc = [] # Pair headers with text indexes for toc. |
| 69 |
self.header = '' # Text within header tags for toc. |
| 70 |
self.prevtag = None # Previous tag info (opener?, tag). |
| 71 |
|
| 72 |
def indent(self, amt=1): |
| 73 |
"Change indent (+1, 0, -1) and tags." |
| 74 |
self.level += amt |
| 75 |
self.tags = '' if self.level == 0 else 'l'+str(self.level) |
| 76 |
|
| 77 |
def handle_starttag(self, tag, attrs): |
| 78 |
"Handle starttags in help.html." |
| 79 |
class_ = '' |
| 80 |
for a, v in attrs: |
| 81 |
if a == 'class': |
| 82 |
class_ = v |
| 83 |
s = '' |
| 84 |
if tag == 'p' and self.prevtag and not self.prevtag[0]: |
| 85 |
# Begin a new block for <p> tags after a closed tag. |
| 86 |
# Avoid extra lines, e.g. after <pre> tags. |
| 87 |
lastline = self.text.get('end-1c linestart', 'end-1c') |
| 88 |
s = '\n\n' if lastline and not lastline.isspace() else '\n' |
| 89 |
elif tag == 'span' and class_ == 'pre': |
| 90 |
self.chartags = 'pre' |
| 91 |
elif tag == 'span' and class_ == 'versionmodified': |
| 92 |
self.chartags = 'em' |
| 93 |
elif tag == 'em': |
| 94 |
self.chartags = 'em' |
| 95 |
elif tag in ['ul', 'ol']: |
| 96 |
if class_.find('simple') != -1: |
| 97 |
s = '\n' |
| 98 |
self.simplelist = True |
| 99 |
else: |
| 100 |
self.simplelist = False |
| 101 |
self.indent() |
| 102 |
elif tag == 'dl': |
| 103 |
if self.level > 0: |
| 104 |
self.nested_dl = True |
| 105 |
elif tag == 'li': |
| 106 |
s = '\n* ' |
| 107 |
elif tag == 'dt': |
| 108 |
s = '\n\n' if not self.nested_dl else '\n' # Avoid extra line. |
| 109 |
self.nested_dl = False |
| 110 |
elif tag == 'dd': |
| 111 |
self.indent() |
| 112 |
s = '\n' |
| 113 |
elif tag == 'pre': |
| 114 |
self.pre = True |
| 115 |
self.text.insert('end', '\n\n') |
| 116 |
self.tags = 'preblock' |
| 117 |
elif tag == 'a' and class_ == 'headerlink': |
| 118 |
self.hdrlink = True |
| 119 |
elif tag == 'h1': |
| 120 |
self.tags = tag |
| 121 |
elif tag in ['h2', 'h3']: |
| 122 |
self.header = '' |
| 123 |
self.text.insert('end', '\n\n') |
| 124 |
self.tags = tag |
| 125 |
self.text.insert('end', s, (self.tags, self.chartags)) |
| 126 |
self.prevtag = (True, tag) |
| 127 |
|
| 128 |
def handle_endtag(self, tag): |
| 129 |
"Handle endtags in help.html." |
| 130 |
if tag in ['h1', 'h2', 'h3']: |
| 131 |
assert self.level == 0 |
| 132 |
indent = (' ' if tag == 'h3' else |
| 133 |
' ' if tag == 'h2' else |
| 134 |
'') |
| 135 |
self.toc.append((indent+self.header, self.text.index('insert'))) |
| 136 |
self.tags = '' |
| 137 |
elif tag in ['span', 'em']: |
| 138 |
self.chartags = '' |
| 139 |
elif tag == 'a': |
| 140 |
self.hdrlink = False |
| 141 |
elif tag == 'pre': |
| 142 |
self.pre = False |
| 143 |
self.tags = '' |
| 144 |
elif tag in ['ul', 'dd', 'ol']: |
| 145 |
self.indent(-1) |
| 146 |
self.prevtag = (False, tag) |
| 147 |
|
| 148 |
def handle_data(self, data): |
| 149 |
"Handle date segments in help.html." |
| 150 |
if not self.hdrlink: |
| 151 |
d = data if self.pre else data.replace('\n', ' ') |
| 152 |
if self.tags == 'h1': |
| 153 |
try: |
| 154 |
self.hprefix = d[:d.index(' ')] |
| 155 |
if not self.hprefix.isdigit(): |
| 156 |
self.hprefix = '' |
| 157 |
except ValueError: |
| 158 |
self.hprefix = '' |
| 159 |
if self.tags in ['h1', 'h2', 'h3']: |
| 160 |
if (self.hprefix != '' and |
| 161 |
d[0:len(self.hprefix)] == self.hprefix): |
| 162 |
d = d[len(self.hprefix):] |
| 163 |
self.header += d.strip() |
| 164 |
self.text.insert('end', d, (self.tags, self.chartags)) |
| 165 |
|
| 166 |
|
| 167 |
class HelpText(Text): |
| 168 |
"Display help.html." |
| 169 |
def __init__(self, parent, filename): |
| 170 |
"Configure tags and feed file to parser." |
| 171 |
uwide = idleConf.GetOption('main', 'EditorWindow', 'width', type='int') |
| 172 |
uhigh = idleConf.GetOption('main', 'EditorWindow', 'height', type='int') |
| 173 |
uhigh = 3 * uhigh // 4 # Lines average 4/3 of editor line height. |
| 174 |
Text.__init__(self, parent, wrap='word', highlightthickness=0, |
| 175 |
padx=5, borderwidth=0, width=uwide, height=uhigh) |
| 176 |
|
| 177 |
normalfont = self.findfont(['TkDefaultFont', 'arial', 'helvetica']) |
| 178 |
fixedfont = self.findfont(['TkFixedFont', 'monaco', 'courier']) |
| 179 |
color_config(self) |
| 180 |
self['font'] = (normalfont, 12) |
| 181 |
self.tag_configure('em', font=(normalfont, 12, 'italic')) |
| 182 |
self.tag_configure('h1', font=(normalfont, 20, 'bold')) |
| 183 |
self.tag_configure('h2', font=(normalfont, 18, 'bold')) |
| 184 |
self.tag_configure('h3', font=(normalfont, 15, 'bold')) |
| 185 |
self.tag_configure('pre', font=(fixedfont, 12)) |
| 186 |
preback = self['selectbackground'] |
| 187 |
self.tag_configure('preblock', font=(fixedfont, 10), lmargin1=25, |
| 188 |
background=preback) |
| 189 |
self.tag_configure('l1', lmargin1=25, lmargin2=25) |
| 190 |
self.tag_configure('l2', lmargin1=50, lmargin2=50) |
| 191 |
self.tag_configure('l3', lmargin1=75, lmargin2=75) |
| 192 |
self.tag_configure('l4', lmargin1=100, lmargin2=100) |
| 193 |
|
| 194 |
self.parser = HelpParser(self) |
| 195 |
with open(filename, encoding='utf-8') as f: |
| 196 |
contents = f.read() |
| 197 |
self.parser.feed(contents) |
| 198 |
self['state'] = 'disabled' |
| 199 |
|
| 200 |
def findfont(self, names): |
| 201 |
"Return name of first font family derived from names." |
| 202 |
for name in names: |
| 203 |
if name.lower() in (x.lower() for x in tkfont.names(root=self)): |
| 204 |
font = tkfont.Font(name=name, exists=True, root=self) |
| 205 |
return font.actual()['family'] |
| 206 |
elif name.lower() in (x.lower() |
| 207 |
for x in tkfont.families(root=self)): |
| 208 |
return name |
| 209 |
|
| 210 |
|
| 211 |
class HelpFrame(Frame): |
| 212 |
"Display html text, scrollbar, and toc." |
| 213 |
def __init__(self, parent, filename): |
| 214 |
Frame.__init__(self, parent) |
| 215 |
self.text = text = HelpText(self, filename) |
| 216 |
self.style = Style(parent) |
| 217 |
self['style'] = 'helpframe.TFrame' |
| 218 |
self.style.configure('helpframe.TFrame', background=text['background']) |
| 219 |
self.toc = toc = self.toc_menu(text) |
| 220 |
self.scroll = scroll = Scrollbar(self, command=text.yview) |
| 221 |
text['yscrollcommand'] = scroll.set |
| 222 |
|
| 223 |
self.rowconfigure(0, weight=1) |
| 224 |
self.columnconfigure(1, weight=1) # Only expand the text widget. |
| 225 |
toc.grid(row=0, column=0, sticky='nw') |
| 226 |
text.grid(row=0, column=1, sticky='nsew') |
| 227 |
scroll.grid(row=0, column=2, sticky='ns') |
| 228 |
|
| 229 |
def toc_menu(self, text): |
| 230 |
"Create table of contents as drop-down menu." |
| 231 |
toc = Menubutton(self, text='TOC') |
| 232 |
drop = Menu(toc, tearoff=False) |
| 233 |
for lbl, dex in text.parser.toc: |
| 234 |
drop.add_command(label=lbl, command=lambda dex=dex:text.yview(dex)) |
| 235 |
toc['menu'] = drop |
| 236 |
return toc |
| 237 |
|
| 238 |
|
| 239 |
class HelpWindow(Toplevel): |
| 240 |
"Display frame with rendered html." |
| 241 |
def __init__(self, parent, filename, title): |
| 242 |
Toplevel.__init__(self, parent) |
| 243 |
self.wm_title(title) |
| 244 |
self.protocol("WM_DELETE_WINDOW", self.destroy) |
| 245 |
self.frame = HelpFrame(self, filename) |
| 246 |
self.frame.grid(column=0, row=0, sticky='nsew') |
| 247 |
self.grid_columnconfigure(0, weight=1) |
| 248 |
self.grid_rowconfigure(0, weight=1) |
| 249 |
|
| 250 |
|
| 251 |
def copy_strip(): # pragma: no cover |
| 252 |
"""Copy the text part of idle.html to idlelib/help.html while stripping trailing whitespace. |
| 253 |
|
| 254 |
Files with trailing whitespace cannot be pushed to the git cpython |
| 255 |
repository. For 3.x (on Windows), help.html is generated, after |
| 256 |
editing idle.rst on the master branch, with |
| 257 |
sphinx-build -bhtml . build/html |
| 258 |
python_d.exe -c "from idlelib.help import copy_strip; copy_strip()" |
| 259 |
Check build/html/library/idle.html, the help.html diff, and the text |
| 260 |
displayed by Help => IDLE Help. Add a blurb and create a PR. |
| 261 |
|
| 262 |
It can be worthwhile to occasionally generate help.html without |
| 263 |
touching idle.rst. Changes to the master version and to the doc |
| 264 |
build system may result in changes that should not change |
| 265 |
the displayed text, but might break HelpParser. |
| 266 |
|
| 267 |
As long as master and maintenance versions of idle.rst remain the |
| 268 |
same, help.html can be backported. The internal Python version |
| 269 |
number is not displayed. If maintenance idle.rst diverges from |
| 270 |
the master version, then instead of backporting help.html from |
| 271 |
master, repeat the procedure above to generate a maintenance |
| 272 |
version. |
| 273 |
""" |
| 274 |
src = join(abspath(dirname(dirname(dirname(__file__)))), |
| 275 |
'Doc', 'build', 'html', 'library', 'idle.html') |
| 276 |
dst = join(abspath(dirname(__file__)), 'help.html') |
| 277 |
|
| 278 |
with open(src, 'r', encoding="utf-8") as inn, open(dst, 'w', encoding="utf-8") as out: |
| 279 |
copy = False |
| 280 |
for line in inn: |
| 281 |
if '<section id="idle">' in line: copy = True |
| 282 |
if '<div class="clearer">' in line: break |
| 283 |
if copy: out.write(line.strip() + '\n') |
| 284 |
|
| 285 |
print(f'{src} copied to {dst}') |
| 286 |
|
| 287 |
|
| 288 |
def show_idlehelp(parent): |
| 289 |
"Create HelpWindow; called from Idle Help event handler." |
| 290 |
filename = join(abspath(dirname(__file__)), 'help.html') |
| 291 |
if not isfile(filename): # pragma: no cover |
| 292 |
# Try copy_strip, present message. |
| 293 |
return |
| 294 |
return HelpWindow(parent, filename, 'IDLE Doc (%s)' % python_version()) |
| 295 |
|
| 296 |
|
| 297 |
def _get_dochome(): |
| 298 |
"Return path to local docs if present, otherwise link to docs.python.org." |
| 299 |
|
| 300 |
dochome = os.path.join(sys.base_prefix, 'Doc', 'index.html') |
| 301 |
if sys.platform.count('linux'): |
| 302 |
# look for html docs in a couple of standard places |
| 303 |
pyver = 'python-docs-' + '%s.%s.%s' % sys.version_info[:3] |
| 304 |
if os.path.isdir('/var/www/html/python/'): # rpm package manager |
| 305 |
dochome = '/var/www/html/python/index.html' |
| 306 |
else: |
| 307 |
basepath = '/usr/share/doc/' # dnf/apt package managers |
| 308 |
dochome = os.path.join(basepath, pyver, 'Doc', 'index.html') |
| 309 |
|
| 310 |
elif sys.platform[:3] == 'win': |
| 311 |
import winreg # Windows only, block only executed once. |
| 312 |
docfile = '' |
| 313 |
KEY = (rf"Software\Python\PythonCore\{sys.winver}" |
| 314 |
r"\Help\Main Python Documentation") |
| 315 |
try: |
| 316 |
docfile = winreg.QueryValue(winreg.HKEY_CURRENT_USER, KEY) |
| 317 |
except FileNotFoundError: |
| 318 |
try: |
| 319 |
docfile = winreg.QueryValue(winreg.HKEY_LOCAL_MACHINE, KEY) |
| 320 |
except FileNotFoundError: |
| 321 |
pass |
| 322 |
if os.path.isfile(docfile): |
| 323 |
dochome = docfile |
| 324 |
elif sys.platform == 'darwin': |
| 325 |
# documentation may be stored inside a python framework |
| 326 |
dochome = os.path.join(sys.base_prefix, |
| 327 |
'Resources/English.lproj/Documentation/index.html') |
| 328 |
dochome = os.path.normpath(dochome) |
| 329 |
if os.path.isfile(dochome): |
| 330 |
if sys.platform == 'darwin': |
| 331 |
# Safari requires real file:-URLs |
| 332 |
return 'file://' + dochome |
| 333 |
return dochome |
| 334 |
else: |
| 335 |
return "https://docs.python.org/%d.%d/" % sys.version_info[:2] |
| 336 |
|
| 337 |
|
| 338 |
if __name__ == '__main__': |
| 339 |
from unittest import main |
| 340 |
main('idlelib.idle_test.test_help', verbosity=2, exit=False) |
| 341 |
|
| 342 |
from idlelib.idle_test.htest import run |
| 343 |
run(show_idlehelp) |