config.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  1. """idlelib.config -- Manage IDLE configuration information.
  2. The comments at the beginning of config-main.def describe the
  3. configuration files and the design implemented to update user
  4. configuration information. In particular, user configuration choices
  5. which duplicate the defaults will be removed from the user's
  6. configuration files, and if a user file becomes empty, it will be
  7. deleted.
  8. The configuration database maps options to values. Conceptually, the
  9. database keys are tuples (config-type, section, item). As implemented,
  10. there are separate dicts for default and user values. Each has
  11. config-type keys 'main', 'extensions', 'highlight', and 'keys'. The
  12. value for each key is a ConfigParser instance that maps section and item
  13. to values. For 'main' and 'extensions', user values override
  14. default values. For 'highlight' and 'keys', user sections augment the
  15. default sections (and must, therefore, have distinct names).
  16. Throughout this module there is an emphasis on returning usable defaults
  17. when a problem occurs in returning a requested configuration value back to
  18. idle. This is to allow IDLE to continue to function in spite of errors in
  19. the retrieval of config information. When a default is returned instead of
  20. a requested config value, a message is printed to stderr to aid in
  21. configuration problem notification and resolution.
  22. """
  23. # TODOs added Oct 2014, tjr
  24. from configparser import ConfigParser
  25. import os
  26. import sys
  27. from tkinter.font import Font
  28. import idlelib
  29. class InvalidConfigType(Exception): pass
  30. class InvalidConfigSet(Exception): pass
  31. class InvalidTheme(Exception): pass
  32. class IdleConfParser(ConfigParser):
  33. """
  34. A ConfigParser specialised for idle configuration file handling
  35. """
  36. def __init__(self, cfgFile, cfgDefaults=None):
  37. """
  38. cfgFile - string, fully specified configuration file name
  39. """
  40. self.file = cfgFile # This is currently '' when testing.
  41. ConfigParser.__init__(self, defaults=cfgDefaults, strict=False)
  42. def Get(self, section, option, type=None, default=None, raw=False):
  43. """
  44. Get an option value for given section/option or return default.
  45. If type is specified, return as type.
  46. """
  47. # TODO Use default as fallback, at least if not None
  48. # Should also print Warning(file, section, option).
  49. # Currently may raise ValueError
  50. if not self.has_option(section, option):
  51. return default
  52. if type == 'bool':
  53. return self.getboolean(section, option)
  54. elif type == 'int':
  55. return self.getint(section, option)
  56. else:
  57. return self.get(section, option, raw=raw)
  58. def GetOptionList(self, section):
  59. "Return a list of options for given section, else []."
  60. if self.has_section(section):
  61. return self.options(section)
  62. else: #return a default value
  63. return []
  64. def Load(self):
  65. "Load the configuration file from disk."
  66. if self.file:
  67. self.read(self.file)
  68. class IdleUserConfParser(IdleConfParser):
  69. """
  70. IdleConfigParser specialised for user configuration handling.
  71. """
  72. def SetOption(self, section, option, value):
  73. """Return True if option is added or changed to value, else False.
  74. Add section if required. False means option already had value.
  75. """
  76. if self.has_option(section, option):
  77. if self.get(section, option) == value:
  78. return False
  79. else:
  80. self.set(section, option, value)
  81. return True
  82. else:
  83. if not self.has_section(section):
  84. self.add_section(section)
  85. self.set(section, option, value)
  86. return True
  87. def RemoveOption(self, section, option):
  88. """Return True if option is removed from section, else False.
  89. False if either section does not exist or did not have option.
  90. """
  91. if self.has_section(section):
  92. return self.remove_option(section, option)
  93. return False
  94. def AddSection(self, section):
  95. "If section doesn't exist, add it."
  96. if not self.has_section(section):
  97. self.add_section(section)
  98. def RemoveEmptySections(self):
  99. "Remove any sections that have no options."
  100. for section in self.sections():
  101. if not self.GetOptionList(section):
  102. self.remove_section(section)
  103. def IsEmpty(self):
  104. "Return True if no sections after removing empty sections."
  105. self.RemoveEmptySections()
  106. return not self.sections()
  107. def Save(self):
  108. """Update user configuration file.
  109. If self not empty after removing empty sections, write the file
  110. to disk. Otherwise, remove the file from disk if it exists.
  111. """
  112. fname = self.file
  113. if fname and fname[0] != '#':
  114. if not self.IsEmpty():
  115. try:
  116. cfgFile = open(fname, 'w')
  117. except OSError:
  118. os.unlink(fname)
  119. cfgFile = open(fname, 'w')
  120. with cfgFile:
  121. self.write(cfgFile)
  122. elif os.path.exists(self.file):
  123. os.remove(self.file)
  124. class IdleConf:
  125. """Hold config parsers for all idle config files in singleton instance.
  126. Default config files, self.defaultCfg --
  127. for config_type in self.config_types:
  128. (idle install dir)/config-{config-type}.def
  129. User config files, self.userCfg --
  130. for config_type in self.config_types:
  131. (user home dir)/.idlerc/config-{config-type}.cfg
  132. """
  133. def __init__(self, _utest=False):
  134. self.config_types = ('main', 'highlight', 'keys', 'extensions')
  135. self.defaultCfg = {}
  136. self.userCfg = {}
  137. self.cfg = {} # TODO use to select userCfg vs defaultCfg
  138. # self.blink_off_time = <first editor text>['insertofftime']
  139. # See https:/bugs.python.org/issue4630, msg356516.
  140. if not _utest:
  141. self.CreateConfigHandlers()
  142. self.LoadCfgFiles()
  143. def CreateConfigHandlers(self):
  144. "Populate default and user config parser dictionaries."
  145. idledir = os.path.dirname(__file__)
  146. self.userdir = userdir = '' if idlelib.testing else self.GetUserCfgDir()
  147. for cfg_type in self.config_types:
  148. self.defaultCfg[cfg_type] = IdleConfParser(
  149. os.path.join(idledir, f'config-{cfg_type}.def'))
  150. self.userCfg[cfg_type] = IdleUserConfParser(
  151. os.path.join(userdir or '#', f'config-{cfg_type}.cfg'))
  152. def GetUserCfgDir(self):
  153. """Return a filesystem directory for storing user config files.
  154. Creates it if required.
  155. """
  156. cfgDir = '.idlerc'
  157. userDir = os.path.expanduser('~')
  158. if userDir != '~': # expanduser() found user home dir
  159. if not os.path.exists(userDir):
  160. if not idlelib.testing:
  161. warn = ('\n Warning: os.path.expanduser("~") points to\n ' +
  162. userDir + ',\n but the path does not exist.')
  163. try:
  164. print(warn, file=sys.stderr)
  165. except OSError:
  166. pass
  167. userDir = '~'
  168. if userDir == "~": # still no path to home!
  169. # traditionally IDLE has defaulted to os.getcwd(), is this adequate?
  170. userDir = os.getcwd()
  171. userDir = os.path.join(userDir, cfgDir)
  172. if not os.path.exists(userDir):
  173. try:
  174. os.mkdir(userDir)
  175. except OSError:
  176. if not idlelib.testing:
  177. warn = ('\n Warning: unable to create user config directory\n' +
  178. userDir + '\n Check path and permissions.\n Exiting!\n')
  179. try:
  180. print(warn, file=sys.stderr)
  181. except OSError:
  182. pass
  183. raise SystemExit
  184. # TODO continue without userDIr instead of exit
  185. return userDir
  186. def GetOption(self, configType, section, option, default=None, type=None,
  187. warn_on_default=True, raw=False):
  188. """Return a value for configType section option, or default.
  189. If type is not None, return a value of that type. Also pass raw
  190. to the config parser. First try to return a valid value
  191. (including type) from a user configuration. If that fails, try
  192. the default configuration. If that fails, return default, with a
  193. default of None.
  194. Warn if either user or default configurations have an invalid value.
  195. Warn if default is returned and warn_on_default is True.
  196. """
  197. try:
  198. if self.userCfg[configType].has_option(section, option):
  199. return self.userCfg[configType].Get(section, option,
  200. type=type, raw=raw)
  201. except ValueError:
  202. warning = ('\n Warning: config.py - IdleConf.GetOption -\n'
  203. ' invalid %r value for configuration option %r\n'
  204. ' from section %r: %r' %
  205. (type, option, section,
  206. self.userCfg[configType].Get(section, option, raw=raw)))
  207. _warn(warning, configType, section, option)
  208. try:
  209. if self.defaultCfg[configType].has_option(section,option):
  210. return self.defaultCfg[configType].Get(
  211. section, option, type=type, raw=raw)
  212. except ValueError:
  213. pass
  214. #returning default, print warning
  215. if warn_on_default:
  216. warning = ('\n Warning: config.py - IdleConf.GetOption -\n'
  217. ' problem retrieving configuration option %r\n'
  218. ' from section %r.\n'
  219. ' returning default value: %r' %
  220. (option, section, default))
  221. _warn(warning, configType, section, option)
  222. return default
  223. def SetOption(self, configType, section, option, value):
  224. """Set section option to value in user config file."""
  225. self.userCfg[configType].SetOption(section, option, value)
  226. def GetSectionList(self, configSet, configType):
  227. """Return sections for configSet configType configuration.
  228. configSet must be either 'user' or 'default'
  229. configType must be in self.config_types.
  230. """
  231. if not (configType in self.config_types):
  232. raise InvalidConfigType('Invalid configType specified')
  233. if configSet == 'user':
  234. cfgParser = self.userCfg[configType]
  235. elif configSet == 'default':
  236. cfgParser=self.defaultCfg[configType]
  237. else:
  238. raise InvalidConfigSet('Invalid configSet specified')
  239. return cfgParser.sections()
  240. def GetHighlight(self, theme, element):
  241. """Return dict of theme element highlight colors.
  242. The keys are 'foreground' and 'background'. The values are
  243. tkinter color strings for configuring backgrounds and tags.
  244. """
  245. cfg = ('default' if self.defaultCfg['highlight'].has_section(theme)
  246. else 'user')
  247. theme_dict = self.GetThemeDict(cfg, theme)
  248. fore = theme_dict[element + '-foreground']
  249. if element == 'cursor':
  250. element = 'normal'
  251. back = theme_dict[element + '-background']
  252. return {"foreground": fore, "background": back}
  253. def GetThemeDict(self, type, themeName):
  254. """Return {option:value} dict for elements in themeName.
  255. type - string, 'default' or 'user' theme type
  256. themeName - string, theme name
  257. Values are loaded over ultimate fallback defaults to guarantee
  258. that all theme elements are present in a newly created theme.
  259. """
  260. if type == 'user':
  261. cfgParser = self.userCfg['highlight']
  262. elif type == 'default':
  263. cfgParser = self.defaultCfg['highlight']
  264. else:
  265. raise InvalidTheme('Invalid theme type specified')
  266. # Provide foreground and background colors for each theme
  267. # element (other than cursor) even though some values are not
  268. # yet used by idle, to allow for their use in the future.
  269. # Default values are generally black and white.
  270. # TODO copy theme from a class attribute.
  271. theme ={'normal-foreground':'#000000',
  272. 'normal-background':'#ffffff',
  273. 'keyword-foreground':'#000000',
  274. 'keyword-background':'#ffffff',
  275. 'builtin-foreground':'#000000',
  276. 'builtin-background':'#ffffff',
  277. 'comment-foreground':'#000000',
  278. 'comment-background':'#ffffff',
  279. 'string-foreground':'#000000',
  280. 'string-background':'#ffffff',
  281. 'definition-foreground':'#000000',
  282. 'definition-background':'#ffffff',
  283. 'hilite-foreground':'#000000',
  284. 'hilite-background':'gray',
  285. 'break-foreground':'#ffffff',
  286. 'break-background':'#000000',
  287. 'hit-foreground':'#ffffff',
  288. 'hit-background':'#000000',
  289. 'error-foreground':'#ffffff',
  290. 'error-background':'#000000',
  291. 'context-foreground':'#000000',
  292. 'context-background':'#ffffff',
  293. 'linenumber-foreground':'#000000',
  294. 'linenumber-background':'#ffffff',
  295. #cursor (only foreground can be set)
  296. 'cursor-foreground':'#000000',
  297. #shell window
  298. 'stdout-foreground':'#000000',
  299. 'stdout-background':'#ffffff',
  300. 'stderr-foreground':'#000000',
  301. 'stderr-background':'#ffffff',
  302. 'console-foreground':'#000000',
  303. 'console-background':'#ffffff',
  304. }
  305. for element in theme:
  306. if not (cfgParser.has_option(themeName, element) or
  307. # Skip warning for new elements.
  308. element.startswith(('context-', 'linenumber-'))):
  309. # Print warning that will return a default color
  310. warning = ('\n Warning: config.IdleConf.GetThemeDict'
  311. ' -\n problem retrieving theme element %r'
  312. '\n from theme %r.\n'
  313. ' returning default color: %r' %
  314. (element, themeName, theme[element]))
  315. _warn(warning, 'highlight', themeName, element)
  316. theme[element] = cfgParser.Get(
  317. themeName, element, default=theme[element])
  318. return theme
  319. def CurrentTheme(self):
  320. "Return the name of the currently active text color theme."
  321. return self.current_colors_and_keys('Theme')
  322. def CurrentKeys(self):
  323. """Return the name of the currently active key set."""
  324. return self.current_colors_and_keys('Keys')
  325. def current_colors_and_keys(self, section):
  326. """Return the currently active name for Theme or Keys section.
  327. idlelib.config-main.def ('default') includes these sections
  328. [Theme]
  329. default= 1
  330. name= IDLE Classic
  331. name2=
  332. [Keys]
  333. default= 1
  334. name=
  335. name2=
  336. Item 'name2', is used for built-in ('default') themes and keys
  337. added after 2015 Oct 1 and 2016 July 1. This kludge is needed
  338. because setting 'name' to a builtin not defined in older IDLEs
  339. to display multiple error messages or quit.
  340. See https://bugs.python.org/issue25313.
  341. When default = True, 'name2' takes precedence over 'name',
  342. while older IDLEs will just use name. When default = False,
  343. 'name2' may still be set, but it is ignored.
  344. """
  345. cfgname = 'highlight' if section == 'Theme' else 'keys'
  346. default = self.GetOption('main', section, 'default',
  347. type='bool', default=True)
  348. name = ''
  349. if default:
  350. name = self.GetOption('main', section, 'name2', default='')
  351. if not name:
  352. name = self.GetOption('main', section, 'name', default='')
  353. if name:
  354. source = self.defaultCfg if default else self.userCfg
  355. if source[cfgname].has_section(name):
  356. return name
  357. return "IDLE Classic" if section == 'Theme' else self.default_keys()
  358. @staticmethod
  359. def default_keys():
  360. if sys.platform[:3] == 'win':
  361. return 'IDLE Classic Windows'
  362. elif sys.platform == 'darwin':
  363. return 'IDLE Classic OSX'
  364. else:
  365. return 'IDLE Modern Unix'
  366. def GetExtensions(self, active_only=True,
  367. editor_only=False, shell_only=False):
  368. """Return extensions in default and user config-extensions files.
  369. If active_only True, only return active (enabled) extensions
  370. and optionally only editor or shell extensions.
  371. If active_only False, return all extensions.
  372. """
  373. extns = self.RemoveKeyBindNames(
  374. self.GetSectionList('default', 'extensions'))
  375. userExtns = self.RemoveKeyBindNames(
  376. self.GetSectionList('user', 'extensions'))
  377. for extn in userExtns:
  378. if extn not in extns: #user has added own extension
  379. extns.append(extn)
  380. for extn in ('AutoComplete','CodeContext',
  381. 'FormatParagraph','ParenMatch'):
  382. extns.remove(extn)
  383. # specific exclusions because we are storing config for mainlined old
  384. # extensions in config-extensions.def for backward compatibility
  385. if active_only:
  386. activeExtns = []
  387. for extn in extns:
  388. if self.GetOption('extensions', extn, 'enable', default=True,
  389. type='bool'):
  390. #the extension is enabled
  391. if editor_only or shell_only: # TODO both True contradict
  392. if editor_only:
  393. option = "enable_editor"
  394. else:
  395. option = "enable_shell"
  396. if self.GetOption('extensions', extn,option,
  397. default=True, type='bool',
  398. warn_on_default=False):
  399. activeExtns.append(extn)
  400. else:
  401. activeExtns.append(extn)
  402. return activeExtns
  403. else:
  404. return extns
  405. def RemoveKeyBindNames(self, extnNameList):
  406. "Return extnNameList with keybinding section names removed."
  407. return [n for n in extnNameList if not n.endswith(('_bindings', '_cfgBindings'))]
  408. def GetExtnNameForEvent(self, virtualEvent):
  409. """Return the name of the extension binding virtualEvent, or None.
  410. virtualEvent - string, name of the virtual event to test for,
  411. without the enclosing '<< >>'
  412. """
  413. extName = None
  414. vEvent = '<<' + virtualEvent + '>>'
  415. for extn in self.GetExtensions(active_only=0):
  416. for event in self.GetExtensionKeys(extn):
  417. if event == vEvent:
  418. extName = extn # TODO return here?
  419. return extName
  420. def GetExtensionKeys(self, extensionName):
  421. """Return dict: {configurable extensionName event : active keybinding}.
  422. Events come from default config extension_cfgBindings section.
  423. Keybindings come from GetCurrentKeySet() active key dict,
  424. where previously used bindings are disabled.
  425. """
  426. keysName = extensionName + '_cfgBindings'
  427. activeKeys = self.GetCurrentKeySet()
  428. extKeys = {}
  429. if self.defaultCfg['extensions'].has_section(keysName):
  430. eventNames = self.defaultCfg['extensions'].GetOptionList(keysName)
  431. for eventName in eventNames:
  432. event = '<<' + eventName + '>>'
  433. binding = activeKeys[event]
  434. extKeys[event] = binding
  435. return extKeys
  436. def __GetRawExtensionKeys(self,extensionName):
  437. """Return dict {configurable extensionName event : keybinding list}.
  438. Events come from default config extension_cfgBindings section.
  439. Keybindings list come from the splitting of GetOption, which
  440. tries user config before default config.
  441. """
  442. keysName = extensionName+'_cfgBindings'
  443. extKeys = {}
  444. if self.defaultCfg['extensions'].has_section(keysName):
  445. eventNames = self.defaultCfg['extensions'].GetOptionList(keysName)
  446. for eventName in eventNames:
  447. binding = self.GetOption(
  448. 'extensions', keysName, eventName, default='').split()
  449. event = '<<' + eventName + '>>'
  450. extKeys[event] = binding
  451. return extKeys
  452. def GetExtensionBindings(self, extensionName):
  453. """Return dict {extensionName event : active or defined keybinding}.
  454. Augment self.GetExtensionKeys(extensionName) with mapping of non-
  455. configurable events (from default config) to GetOption splits,
  456. as in self.__GetRawExtensionKeys.
  457. """
  458. bindsName = extensionName + '_bindings'
  459. extBinds = self.GetExtensionKeys(extensionName)
  460. #add the non-configurable bindings
  461. if self.defaultCfg['extensions'].has_section(bindsName):
  462. eventNames = self.defaultCfg['extensions'].GetOptionList(bindsName)
  463. for eventName in eventNames:
  464. binding = self.GetOption(
  465. 'extensions', bindsName, eventName, default='').split()
  466. event = '<<' + eventName + '>>'
  467. extBinds[event] = binding
  468. return extBinds
  469. def GetKeyBinding(self, keySetName, eventStr):
  470. """Return the keybinding list for keySetName eventStr.
  471. keySetName - name of key binding set (config-keys section).
  472. eventStr - virtual event, including brackets, as in '<<event>>'.
  473. """
  474. eventName = eventStr[2:-2] #trim off the angle brackets
  475. binding = self.GetOption('keys', keySetName, eventName, default='',
  476. warn_on_default=False).split()
  477. return binding
  478. def GetCurrentKeySet(self):
  479. "Return CurrentKeys with 'darwin' modifications."
  480. result = self.GetKeySet(self.CurrentKeys())
  481. if sys.platform == "darwin":
  482. # macOS (OS X) Tk variants do not support the "Alt"
  483. # keyboard modifier. Replace it with "Option".
  484. # TODO (Ned?): the "Option" modifier does not work properly
  485. # for Cocoa Tk and XQuartz Tk so we should not use it
  486. # in the default 'OSX' keyset.
  487. for k, v in result.items():
  488. v2 = [ x.replace('<Alt-', '<Option-') for x in v ]
  489. if v != v2:
  490. result[k] = v2
  491. return result
  492. def GetKeySet(self, keySetName):
  493. """Return event-key dict for keySetName core plus active extensions.
  494. If a binding defined in an extension is already in use, the
  495. extension binding is disabled by being set to ''
  496. """
  497. keySet = self.GetCoreKeys(keySetName)
  498. activeExtns = self.GetExtensions(active_only=1)
  499. for extn in activeExtns:
  500. extKeys = self.__GetRawExtensionKeys(extn)
  501. if extKeys: #the extension defines keybindings
  502. for event in extKeys:
  503. if extKeys[event] in keySet.values():
  504. #the binding is already in use
  505. extKeys[event] = '' #disable this binding
  506. keySet[event] = extKeys[event] #add binding
  507. return keySet
  508. def IsCoreBinding(self, virtualEvent):
  509. """Return True if the virtual event is one of the core idle key events.
  510. virtualEvent - string, name of the virtual event to test for,
  511. without the enclosing '<< >>'
  512. """
  513. return ('<<'+virtualEvent+'>>') in self.GetCoreKeys()
  514. # TODO make keyBindings a file or class attribute used for test above
  515. # and copied in function below.
  516. former_extension_events = { # Those with user-configurable keys.
  517. '<<force-open-completions>>', '<<expand-word>>',
  518. '<<force-open-calltip>>', '<<flash-paren>>', '<<format-paragraph>>',
  519. '<<run-module>>', '<<check-module>>', '<<zoom-height>>',
  520. '<<run-custom>>',
  521. }
  522. def GetCoreKeys(self, keySetName=None):
  523. """Return dict of core virtual-key keybindings for keySetName.
  524. The default keySetName None corresponds to the keyBindings base
  525. dict. If keySetName is not None, bindings from the config
  526. file(s) are loaded _over_ these defaults, so if there is a
  527. problem getting any core binding there will be an 'ultimate last
  528. resort fallback' to the CUA-ish bindings defined here.
  529. """
  530. keyBindings={
  531. '<<copy>>': ['<Control-c>', '<Control-C>'],
  532. '<<cut>>': ['<Control-x>', '<Control-X>'],
  533. '<<paste>>': ['<Control-v>', '<Control-V>'],
  534. '<<beginning-of-line>>': ['<Control-a>', '<Home>'],
  535. '<<center-insert>>': ['<Control-l>'],
  536. '<<close-all-windows>>': ['<Control-q>'],
  537. '<<close-window>>': ['<Alt-F4>'],
  538. '<<do-nothing>>': ['<Control-x>'],
  539. '<<end-of-file>>': ['<Control-d>'],
  540. '<<python-docs>>': ['<F1>'],
  541. '<<python-context-help>>': ['<Shift-F1>'],
  542. '<<history-next>>': ['<Alt-n>'],
  543. '<<history-previous>>': ['<Alt-p>'],
  544. '<<interrupt-execution>>': ['<Control-c>'],
  545. '<<view-restart>>': ['<F6>'],
  546. '<<restart-shell>>': ['<Control-F6>'],
  547. '<<open-class-browser>>': ['<Alt-c>'],
  548. '<<open-module>>': ['<Alt-m>'],
  549. '<<open-new-window>>': ['<Control-n>'],
  550. '<<open-window-from-file>>': ['<Control-o>'],
  551. '<<plain-newline-and-indent>>': ['<Control-j>'],
  552. '<<print-window>>': ['<Control-p>'],
  553. '<<redo>>': ['<Control-y>'],
  554. '<<remove-selection>>': ['<Escape>'],
  555. '<<save-copy-of-window-as-file>>': ['<Alt-Shift-S>'],
  556. '<<save-window-as-file>>': ['<Alt-s>'],
  557. '<<save-window>>': ['<Control-s>'],
  558. '<<select-all>>': ['<Alt-a>'],
  559. '<<toggle-auto-coloring>>': ['<Control-slash>'],
  560. '<<undo>>': ['<Control-z>'],
  561. '<<find-again>>': ['<Control-g>', '<F3>'],
  562. '<<find-in-files>>': ['<Alt-F3>'],
  563. '<<find-selection>>': ['<Control-F3>'],
  564. '<<find>>': ['<Control-f>'],
  565. '<<replace>>': ['<Control-h>'],
  566. '<<goto-line>>': ['<Alt-g>'],
  567. '<<smart-backspace>>': ['<Key-BackSpace>'],
  568. '<<newline-and-indent>>': ['<Key-Return>', '<Key-KP_Enter>'],
  569. '<<smart-indent>>': ['<Key-Tab>'],
  570. '<<indent-region>>': ['<Control-Key-bracketright>'],
  571. '<<dedent-region>>': ['<Control-Key-bracketleft>'],
  572. '<<comment-region>>': ['<Alt-Key-3>'],
  573. '<<uncomment-region>>': ['<Alt-Key-4>'],
  574. '<<tabify-region>>': ['<Alt-Key-5>'],
  575. '<<untabify-region>>': ['<Alt-Key-6>'],
  576. '<<toggle-tabs>>': ['<Alt-Key-t>'],
  577. '<<change-indentwidth>>': ['<Alt-Key-u>'],
  578. '<<del-word-left>>': ['<Control-Key-BackSpace>'],
  579. '<<del-word-right>>': ['<Control-Key-Delete>'],
  580. '<<force-open-completions>>': ['<Control-Key-space>'],
  581. '<<expand-word>>': ['<Alt-Key-slash>'],
  582. '<<force-open-calltip>>': ['<Control-Key-backslash>'],
  583. '<<flash-paren>>': ['<Control-Key-0>'],
  584. '<<format-paragraph>>': ['<Alt-Key-q>'],
  585. '<<run-module>>': ['<Key-F5>'],
  586. '<<run-custom>>': ['<Shift-Key-F5>'],
  587. '<<check-module>>': ['<Alt-Key-x>'],
  588. '<<zoom-height>>': ['<Alt-Key-2>'],
  589. }
  590. if keySetName:
  591. if not (self.userCfg['keys'].has_section(keySetName) or
  592. self.defaultCfg['keys'].has_section(keySetName)):
  593. warning = (
  594. '\n Warning: config.py - IdleConf.GetCoreKeys -\n'
  595. ' key set %r is not defined, using default bindings.' %
  596. (keySetName,)
  597. )
  598. _warn(warning, 'keys', keySetName)
  599. else:
  600. for event in keyBindings:
  601. binding = self.GetKeyBinding(keySetName, event)
  602. if binding:
  603. keyBindings[event] = binding
  604. # Otherwise return default in keyBindings.
  605. elif event not in self.former_extension_events:
  606. warning = (
  607. '\n Warning: config.py - IdleConf.GetCoreKeys -\n'
  608. ' problem retrieving key binding for event %r\n'
  609. ' from key set %r.\n'
  610. ' returning default value: %r' %
  611. (event, keySetName, keyBindings[event])
  612. )
  613. _warn(warning, 'keys', keySetName, event)
  614. return keyBindings
  615. def GetExtraHelpSourceList(self, configSet):
  616. """Return list of extra help sources from a given configSet.
  617. Valid configSets are 'user' or 'default'. Return a list of tuples of
  618. the form (menu_item , path_to_help_file , option), or return the empty
  619. list. 'option' is the sequence number of the help resource. 'option'
  620. values determine the position of the menu items on the Help menu,
  621. therefore the returned list must be sorted by 'option'.
  622. """
  623. helpSources = []
  624. if configSet == 'user':
  625. cfgParser = self.userCfg['main']
  626. elif configSet == 'default':
  627. cfgParser = self.defaultCfg['main']
  628. else:
  629. raise InvalidConfigSet('Invalid configSet specified')
  630. options=cfgParser.GetOptionList('HelpFiles')
  631. for option in options:
  632. value=cfgParser.Get('HelpFiles', option, default=';')
  633. if value.find(';') == -1: #malformed config entry with no ';'
  634. menuItem = '' #make these empty
  635. helpPath = '' #so value won't be added to list
  636. else: #config entry contains ';' as expected
  637. value=value.split(';')
  638. menuItem=value[0].strip()
  639. helpPath=value[1].strip()
  640. if menuItem and helpPath: #neither are empty strings
  641. helpSources.append( (menuItem,helpPath,option) )
  642. helpSources.sort(key=lambda x: x[2])
  643. return helpSources
  644. def GetAllExtraHelpSourcesList(self):
  645. """Return a list of the details of all additional help sources.
  646. Tuples in the list are those of GetExtraHelpSourceList.
  647. """
  648. allHelpSources = (self.GetExtraHelpSourceList('default') +
  649. self.GetExtraHelpSourceList('user') )
  650. return allHelpSources
  651. def GetFont(self, root, configType, section):
  652. """Retrieve a font from configuration (font, font-size, font-bold)
  653. Intercept the special value 'TkFixedFont' and substitute
  654. the actual font, factoring in some tweaks if needed for
  655. appearance sakes.
  656. The 'root' parameter can normally be any valid Tkinter widget.
  657. Return a tuple (family, size, weight) suitable for passing
  658. to tkinter.Font
  659. """
  660. family = self.GetOption(configType, section, 'font', default='courier')
  661. size = self.GetOption(configType, section, 'font-size', type='int',
  662. default='10')
  663. bold = self.GetOption(configType, section, 'font-bold', default=0,
  664. type='bool')
  665. if (family == 'TkFixedFont'):
  666. f = Font(name='TkFixedFont', exists=True, root=root)
  667. actualFont = Font.actual(f)
  668. family = actualFont['family']
  669. size = actualFont['size']
  670. if size <= 0:
  671. size = 10 # if font in pixels, ignore actual size
  672. bold = actualFont['weight'] == 'bold'
  673. return (family, size, 'bold' if bold else 'normal')
  674. def LoadCfgFiles(self):
  675. "Load all configuration files."
  676. for key in self.defaultCfg:
  677. self.defaultCfg[key].Load()
  678. self.userCfg[key].Load() #same keys
  679. def SaveUserCfgFiles(self):
  680. "Write all loaded user configuration files to disk."
  681. for key in self.userCfg:
  682. self.userCfg[key].Save()
  683. idleConf = IdleConf()
  684. _warned = set()
  685. def _warn(msg, *key):
  686. key = (msg,) + key
  687. if key not in _warned:
  688. try:
  689. print(msg, file=sys.stderr)
  690. except OSError:
  691. pass
  692. _warned.add(key)
  693. class ConfigChanges(dict):
  694. """Manage a user's proposed configuration option changes.
  695. Names used across multiple methods:
  696. page -- one of the 4 top-level dicts representing a
  697. .idlerc/config-x.cfg file.
  698. config_type -- name of a page.
  699. section -- a section within a page/file.
  700. option -- name of an option within a section.
  701. value -- value for the option.
  702. Methods
  703. add_option: Add option and value to changes.
  704. save_option: Save option and value to config parser.
  705. save_all: Save all the changes to the config parser and file.
  706. delete_section: If section exists,
  707. delete from changes, userCfg, and file.
  708. clear: Clear all changes by clearing each page.
  709. """
  710. def __init__(self):
  711. "Create a page for each configuration file"
  712. self.pages = [] # List of unhashable dicts.
  713. for config_type in idleConf.config_types:
  714. self[config_type] = {}
  715. self.pages.append(self[config_type])
  716. def add_option(self, config_type, section, item, value):
  717. "Add item/value pair for config_type and section."
  718. page = self[config_type]
  719. value = str(value) # Make sure we use a string.
  720. if section not in page:
  721. page[section] = {}
  722. page[section][item] = value
  723. @staticmethod
  724. def save_option(config_type, section, item, value):
  725. """Return True if the configuration value was added or changed.
  726. Helper for save_all.
  727. """
  728. if idleConf.defaultCfg[config_type].has_option(section, item):
  729. if idleConf.defaultCfg[config_type].Get(section, item) == value:
  730. # The setting equals a default setting, remove it from user cfg.
  731. return idleConf.userCfg[config_type].RemoveOption(section, item)
  732. # If we got here, set the option.
  733. return idleConf.userCfg[config_type].SetOption(section, item, value)
  734. def save_all(self):
  735. """Save configuration changes to the user config file.
  736. Clear self in preparation for additional changes.
  737. Return changed for testing.
  738. """
  739. idleConf.userCfg['main'].Save()
  740. changed = False
  741. for config_type in self:
  742. cfg_type_changed = False
  743. page = self[config_type]
  744. for section in page:
  745. if section == 'HelpFiles': # Remove it for replacement.
  746. idleConf.userCfg['main'].remove_section('HelpFiles')
  747. cfg_type_changed = True
  748. for item, value in page[section].items():
  749. if self.save_option(config_type, section, item, value):
  750. cfg_type_changed = True
  751. if cfg_type_changed:
  752. idleConf.userCfg[config_type].Save()
  753. changed = True
  754. for config_type in ['keys', 'highlight']:
  755. # Save these even if unchanged!
  756. idleConf.userCfg[config_type].Save()
  757. self.clear()
  758. # ConfigDialog caller must add the following call
  759. # self.save_all_changed_extensions() # Uses a different mechanism.
  760. return changed
  761. def delete_section(self, config_type, section):
  762. """Delete a section from self, userCfg, and file.
  763. Used to delete custom themes and keysets.
  764. """
  765. if section in self[config_type]:
  766. del self[config_type][section]
  767. configpage = idleConf.userCfg[config_type]
  768. configpage.remove_section(section)
  769. configpage.Save()
  770. def clear(self):
  771. """Clear all 4 pages.
  772. Called in save_all after saving to idleConf.
  773. XXX Mark window *title* when there are changes; unmark here.
  774. """
  775. for page in self.pages:
  776. page.clear()
  777. # TODO Revise test output, write expanded unittest
  778. def _dump(): # htest # (not really, but ignore in coverage)
  779. from zlib import crc32
  780. line, crc = 0, 0
  781. def sprint(obj):
  782. global line, crc
  783. txt = str(obj)
  784. line += 1
  785. crc = crc32(txt.encode(encoding='utf-8'), crc)
  786. print(txt)
  787. #print('***', line, crc, '***') # Uncomment for diagnosis.
  788. def dumpCfg(cfg):
  789. print('\n', cfg, '\n') # Cfg has variable '0xnnnnnnnn' address.
  790. for key in sorted(cfg.keys()):
  791. sections = cfg[key].sections()
  792. sprint(key)
  793. sprint(sections)
  794. for section in sections:
  795. options = cfg[key].options(section)
  796. sprint(section)
  797. sprint(options)
  798. for option in options:
  799. sprint(option + ' = ' + cfg[key].Get(section, option))
  800. dumpCfg(idleConf.defaultCfg)
  801. dumpCfg(idleConf.userCfg)
  802. print('\nlines = ', line, ', crc = ', crc, sep='')
  803. if __name__ == '__main__':
  804. from unittest import main
  805. main('idlelib.idle_test.test_config', verbosity=2, exit=False)
  806. # Run revised _dump() as htest?