configHandler.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761
  1. """Provides access to stored IDLE configuration information.
  2. Refer to the comments at the beginning of config-main.def for a description of
  3. the available configuration files and the design implemented to update user
  4. configuration information. In particular, user configuration choices which
  5. duplicate the defaults will be removed from the user's configuration files,
  6. and if a file becomes empty, it will be deleted.
  7. The contents of the user files may be altered using the Options/Configure IDLE
  8. menu to access the configuration GUI (configDialog.py), or manually.
  9. Throughout this module there is an emphasis on returning useable defaults
  10. when a problem occurs in returning a requested configuration value back to
  11. idle. This is to allow IDLE to continue to function in spite of errors in
  12. the retrieval of config information. When a default is returned instead of
  13. a requested config value, a message is printed to stderr to aid in
  14. configuration problem notification and resolution.
  15. """
  16. # TODOs added Oct 2014, tjr
  17. from __future__ import print_function
  18. import os
  19. import sys
  20. from ConfigParser import ConfigParser
  21. from Tkinter import TkVersion
  22. from tkFont import Font, nametofont
  23. class InvalidConfigType(Exception): pass
  24. class InvalidConfigSet(Exception): pass
  25. class InvalidFgBg(Exception): pass
  26. class InvalidTheme(Exception): pass
  27. class IdleConfParser(ConfigParser):
  28. """
  29. A ConfigParser specialised for idle configuration file handling
  30. """
  31. def __init__(self, cfgFile, cfgDefaults=None):
  32. """
  33. cfgFile - string, fully specified configuration file name
  34. """
  35. self.file = cfgFile
  36. ConfigParser.__init__(self, defaults=cfgDefaults)
  37. def Get(self, section, option, type=None, default=None, raw=False):
  38. """
  39. Get an option value for given section/option or return default.
  40. If type is specified, return as type.
  41. """
  42. # TODO Use default as fallback, at least if not None
  43. # Should also print Warning(file, section, option).
  44. # Currently may raise ValueError
  45. if not self.has_option(section, option):
  46. return default
  47. if type == 'bool':
  48. return self.getboolean(section, option)
  49. elif type == 'int':
  50. return self.getint(section, option)
  51. else:
  52. return self.get(section, option, raw=raw)
  53. def GetOptionList(self, section):
  54. "Return a list of options for given section, else []."
  55. if self.has_section(section):
  56. return self.options(section)
  57. else: #return a default value
  58. return []
  59. def Load(self):
  60. "Load the configuration file from disk."
  61. self.read(self.file)
  62. class IdleUserConfParser(IdleConfParser):
  63. """
  64. IdleConfigParser specialised for user configuration handling.
  65. """
  66. def AddSection(self, section):
  67. "If section doesn't exist, add it."
  68. if not self.has_section(section):
  69. self.add_section(section)
  70. def RemoveEmptySections(self):
  71. "Remove any sections that have no options."
  72. for section in self.sections():
  73. if not self.GetOptionList(section):
  74. self.remove_section(section)
  75. def IsEmpty(self):
  76. "Return True if no sections after removing empty sections."
  77. self.RemoveEmptySections()
  78. return not self.sections()
  79. def RemoveOption(self, section, option):
  80. """Return True if option is removed from section, else False.
  81. False if either section does not exist or did not have option.
  82. """
  83. if self.has_section(section):
  84. return self.remove_option(section, option)
  85. return False
  86. def SetOption(self, section, option, value):
  87. """Return True if option is added or changed to value, else False.
  88. Add section if required. False means option already had value.
  89. """
  90. if self.has_option(section, option):
  91. if self.get(section, option) == value:
  92. return False
  93. else:
  94. self.set(section, option, value)
  95. return True
  96. else:
  97. if not self.has_section(section):
  98. self.add_section(section)
  99. self.set(section, option, value)
  100. return True
  101. def RemoveFile(self):
  102. "Remove user config file self.file from disk if it exists."
  103. if os.path.exists(self.file):
  104. os.remove(self.file)
  105. def Save(self):
  106. """Update user configuration file.
  107. Remove empty sections. If resulting config isn't empty, write the file
  108. to disk. If config is empty, remove the file from disk if it exists.
  109. """
  110. if not self.IsEmpty():
  111. fname = self.file
  112. try:
  113. cfgFile = open(fname, 'w')
  114. except IOError:
  115. os.unlink(fname)
  116. cfgFile = open(fname, 'w')
  117. with cfgFile:
  118. self.write(cfgFile)
  119. else:
  120. self.RemoveFile()
  121. class IdleConf:
  122. """Hold config parsers for all idle config files in singleton instance.
  123. Default config files, self.defaultCfg --
  124. for config_type in self.config_types:
  125. (idle install dir)/config-{config-type}.def
  126. User config files, self.userCfg --
  127. for config_type in self.config_types:
  128. (user home dir)/.idlerc/config-{config-type}.cfg
  129. """
  130. def __init__(self):
  131. self.config_types = ('main', 'extensions', 'highlight', 'keys')
  132. self.defaultCfg = {}
  133. self.userCfg = {}
  134. self.cfg = {} # TODO use to select userCfg vs defaultCfg
  135. self.CreateConfigHandlers()
  136. self.LoadCfgFiles()
  137. def CreateConfigHandlers(self):
  138. "Populate default and user config parser dictionaries."
  139. #build idle install path
  140. if __name__ != '__main__': # we were imported
  141. idleDir=os.path.dirname(__file__)
  142. else: # we were exec'ed (for testing only)
  143. idleDir=os.path.abspath(sys.path[0])
  144. userDir=self.GetUserCfgDir()
  145. defCfgFiles = {}
  146. usrCfgFiles = {}
  147. # TODO eliminate these temporaries by combining loops
  148. for cfgType in self.config_types: #build config file names
  149. defCfgFiles[cfgType] = os.path.join(
  150. idleDir, 'config-' + cfgType + '.def')
  151. usrCfgFiles[cfgType] = os.path.join(
  152. userDir, 'config-' + cfgType + '.cfg')
  153. for cfgType in self.config_types: #create config parsers
  154. self.defaultCfg[cfgType] = IdleConfParser(defCfgFiles[cfgType])
  155. self.userCfg[cfgType] = IdleUserConfParser(usrCfgFiles[cfgType])
  156. def GetUserCfgDir(self):
  157. """Return a filesystem directory for storing user config files.
  158. Creates it if required.
  159. """
  160. cfgDir = '.idlerc'
  161. userDir = os.path.expanduser('~')
  162. if userDir != '~': # expanduser() found user home dir
  163. if not os.path.exists(userDir):
  164. warn = ('\n Warning: os.path.expanduser("~") points to\n ' +
  165. userDir + ',\n but the path does not exist.')
  166. try:
  167. print(warn, file=sys.stderr)
  168. except IOError:
  169. pass
  170. userDir = '~'
  171. if userDir == "~": # still no path to home!
  172. # traditionally IDLE has defaulted to os.getcwd(), is this adequate?
  173. userDir = os.getcwd()
  174. userDir = os.path.join(userDir, cfgDir)
  175. if not os.path.exists(userDir):
  176. try:
  177. os.mkdir(userDir)
  178. except (OSError, IOError):
  179. warn = ('\n Warning: unable to create user config directory\n' +
  180. userDir + '\n Check path and permissions.\n Exiting!\n')
  181. print(warn, file=sys.stderr)
  182. raise SystemExit
  183. # TODO continue without userDIr instead of exit
  184. return userDir
  185. def GetOption(self, configType, section, option, default=None, type=None,
  186. warn_on_default=True, raw=False):
  187. """Return a value for configType section option, or default.
  188. If type is not None, return a value of that type. Also pass raw
  189. to the config parser. First try to return a valid value
  190. (including type) from a user configuration. If that fails, try
  191. the default configuration. If that fails, return default, with a
  192. default of None.
  193. Warn if either user or default configurations have an invalid value.
  194. Warn if default is returned and warn_on_default is True.
  195. """
  196. try:
  197. if self.userCfg[configType].has_option(section, option):
  198. return self.userCfg[configType].Get(section, option,
  199. type=type, raw=raw)
  200. except ValueError:
  201. warning = ('\n Warning: configHandler.py - IdleConf.GetOption -\n'
  202. ' invalid %r value for configuration option %r\n'
  203. ' from section %r: %r' %
  204. (type, option, section,
  205. self.userCfg[configType].Get(section, option, raw=raw)))
  206. try:
  207. print(warning, file=sys.stderr)
  208. except IOError:
  209. pass
  210. try:
  211. if self.defaultCfg[configType].has_option(section,option):
  212. return self.defaultCfg[configType].Get(
  213. section, option, type=type, raw=raw)
  214. except ValueError:
  215. pass
  216. #returning default, print warning
  217. if warn_on_default:
  218. warning = ('\n Warning: configHandler.py - IdleConf.GetOption -\n'
  219. ' problem retrieving configuration option %r\n'
  220. ' from section %r.\n'
  221. ' returning default value: %r' %
  222. (option, section, default))
  223. try:
  224. print(warning, file=sys.stderr)
  225. except IOError:
  226. pass
  227. return default
  228. def SetOption(self, configType, section, option, value):
  229. """Set section option to value in user config file."""
  230. self.userCfg[configType].SetOption(section, option, value)
  231. def GetSectionList(self, configSet, configType):
  232. """Return sections for configSet configType configuration.
  233. configSet must be either 'user' or 'default'
  234. configType must be in self.config_types.
  235. """
  236. if not (configType in self.config_types):
  237. raise InvalidConfigType('Invalid configType specified')
  238. if configSet == 'user':
  239. cfgParser = self.userCfg[configType]
  240. elif configSet == 'default':
  241. cfgParser=self.defaultCfg[configType]
  242. else:
  243. raise InvalidConfigSet('Invalid configSet specified')
  244. return cfgParser.sections()
  245. def GetHighlight(self, theme, element, fgBg=None):
  246. """Return individual theme element highlight color(s).
  247. fgBg - string ('fg' or 'bg') or None.
  248. If None, return a dictionary containing fg and bg colors with
  249. keys 'foreground' and 'background'. Otherwise, only return
  250. fg or bg color, as specified. Colors are intended to be
  251. appropriate for passing to Tkinter in, e.g., a tag_config call).
  252. """
  253. if self.defaultCfg['highlight'].has_section(theme):
  254. themeDict = self.GetThemeDict('default', theme)
  255. else:
  256. themeDict = self.GetThemeDict('user', theme)
  257. fore = themeDict[element + '-foreground']
  258. if element == 'cursor': # There is no config value for cursor bg
  259. back = themeDict['normal-background']
  260. else:
  261. back = themeDict[element + '-background']
  262. highlight = {"foreground": fore, "background": back}
  263. if not fgBg: # Return dict of both colors
  264. return highlight
  265. else: # Return specified color only
  266. if fgBg == 'fg':
  267. return highlight["foreground"]
  268. if fgBg == 'bg':
  269. return highlight["background"]
  270. else:
  271. raise InvalidFgBg('Invalid fgBg specified')
  272. def GetThemeDict(self, type, themeName):
  273. """Return {option:value} dict for elements in themeName.
  274. type - string, 'default' or 'user' theme type
  275. themeName - string, theme name
  276. Values are loaded over ultimate fallback defaults to guarantee
  277. that all theme elements are present in a newly created theme.
  278. """
  279. if type == 'user':
  280. cfgParser = self.userCfg['highlight']
  281. elif type == 'default':
  282. cfgParser = self.defaultCfg['highlight']
  283. else:
  284. raise InvalidTheme('Invalid theme type specified')
  285. # Provide foreground and background colors for each theme
  286. # element (other than cursor) even though some values are not
  287. # yet used by idle, to allow for their use in the future.
  288. # Default values are generally black and white.
  289. # TODO copy theme from a class attribute.
  290. theme ={'normal-foreground':'#000000',
  291. 'normal-background':'#ffffff',
  292. 'keyword-foreground':'#000000',
  293. 'keyword-background':'#ffffff',
  294. 'builtin-foreground':'#000000',
  295. 'builtin-background':'#ffffff',
  296. 'comment-foreground':'#000000',
  297. 'comment-background':'#ffffff',
  298. 'string-foreground':'#000000',
  299. 'string-background':'#ffffff',
  300. 'definition-foreground':'#000000',
  301. 'definition-background':'#ffffff',
  302. 'hilite-foreground':'#000000',
  303. 'hilite-background':'gray',
  304. 'break-foreground':'#ffffff',
  305. 'break-background':'#000000',
  306. 'hit-foreground':'#ffffff',
  307. 'hit-background':'#000000',
  308. 'error-foreground':'#ffffff',
  309. 'error-background':'#000000',
  310. #cursor (only foreground can be set)
  311. 'cursor-foreground':'#000000',
  312. #shell window
  313. 'stdout-foreground':'#000000',
  314. 'stdout-background':'#ffffff',
  315. 'stderr-foreground':'#000000',
  316. 'stderr-background':'#ffffff',
  317. 'console-foreground':'#000000',
  318. 'console-background':'#ffffff' }
  319. for element in theme:
  320. if not cfgParser.has_option(themeName, element):
  321. # Print warning that will return a default color
  322. warning = ('\n Warning: configHandler.IdleConf.GetThemeDict'
  323. ' -\n problem retrieving theme element %r'
  324. '\n from theme %r.\n'
  325. ' returning default color: %r' %
  326. (element, themeName, theme[element]))
  327. try:
  328. print(warning, file=sys.stderr)
  329. except IOError:
  330. pass
  331. theme[element] = cfgParser.Get(
  332. themeName, element, default=theme[element])
  333. return theme
  334. def CurrentTheme(self):
  335. """Return the name of the currently active text color theme.
  336. idlelib.config-main.def includes this section
  337. [Theme]
  338. default= 1
  339. name= IDLE Classic
  340. name2=
  341. # name2 set in user config-main.cfg for themes added after 2015 Oct 1
  342. Item name2 is needed because setting name to a new builtin
  343. causes older IDLEs to display multiple error messages or quit.
  344. See https://bugs.python.org/issue25313.
  345. When default = True, name2 takes precedence over name,
  346. while older IDLEs will just use name.
  347. """
  348. default = self.GetOption('main', 'Theme', 'default',
  349. type='bool', default=True)
  350. if default:
  351. theme = self.GetOption('main', 'Theme', 'name2', default='')
  352. if default and not theme or not default:
  353. theme = self.GetOption('main', 'Theme', 'name', default='')
  354. source = self.defaultCfg if default else self.userCfg
  355. if source['highlight'].has_section(theme):
  356. return theme
  357. else:
  358. return "IDLE Classic"
  359. def CurrentKeys(self):
  360. "Return the name of the currently active key set."
  361. return self.GetOption('main', 'Keys', 'name', default='')
  362. def GetExtensions(self, active_only=True, editor_only=False, shell_only=False):
  363. """Return extensions in default and user config-extensions files.
  364. If active_only True, only return active (enabled) extensions
  365. and optionally only editor or shell extensions.
  366. If active_only False, return all extensions.
  367. """
  368. extns = self.RemoveKeyBindNames(
  369. self.GetSectionList('default', 'extensions'))
  370. userExtns = self.RemoveKeyBindNames(
  371. self.GetSectionList('user', 'extensions'))
  372. for extn in userExtns:
  373. if extn not in extns: #user has added own extension
  374. extns.append(extn)
  375. if active_only:
  376. activeExtns = []
  377. for extn in extns:
  378. if self.GetOption('extensions', extn, 'enable', default=True,
  379. type='bool'):
  380. #the extension is enabled
  381. if editor_only or shell_only: # TODO if both, contradictory
  382. if editor_only:
  383. option = "enable_editor"
  384. else:
  385. option = "enable_shell"
  386. if self.GetOption('extensions', extn,option,
  387. default=True, type='bool',
  388. warn_on_default=False):
  389. activeExtns.append(extn)
  390. else:
  391. activeExtns.append(extn)
  392. return activeExtns
  393. else:
  394. return extns
  395. def RemoveKeyBindNames(self, extnNameList):
  396. "Return extnNameList with keybinding section names removed."
  397. # TODO Easier to return filtered copy with list comp
  398. names = extnNameList
  399. kbNameIndicies = []
  400. for name in names:
  401. if name.endswith(('_bindings', '_cfgBindings')):
  402. kbNameIndicies.append(names.index(name))
  403. kbNameIndicies.sort(reverse=True)
  404. for index in kbNameIndicies: #delete each keybinding section name
  405. del(names[index])
  406. return names
  407. def GetExtnNameForEvent(self, virtualEvent):
  408. """Return the name of the extension binding virtualEvent, or None.
  409. virtualEvent - string, name of the virtual event to test for,
  410. without the enclosing '<< >>'
  411. """
  412. extName = None
  413. vEvent = '<<' + virtualEvent + '>>'
  414. for extn in self.GetExtensions(active_only=0):
  415. for event in self.GetExtensionKeys(extn):
  416. if event == vEvent:
  417. extName = extn # TODO return here?
  418. return extName
  419. def GetExtensionKeys(self, extensionName):
  420. """Return dict: {configurable extensionName event : active keybinding}.
  421. Events come from default config extension_cfgBindings section.
  422. Keybindings come from GetCurrentKeySet() active key dict,
  423. where previously used bindings are disabled.
  424. """
  425. keysName = extensionName + '_cfgBindings'
  426. activeKeys = self.GetCurrentKeySet()
  427. extKeys = {}
  428. if self.defaultCfg['extensions'].has_section(keysName):
  429. eventNames = self.defaultCfg['extensions'].GetOptionList(keysName)
  430. for eventName in eventNames:
  431. event = '<<' + eventName + '>>'
  432. binding = activeKeys[event]
  433. extKeys[event] = binding
  434. return extKeys
  435. def __GetRawExtensionKeys(self,extensionName):
  436. """Return dict {configurable extensionName event : keybinding list}.
  437. Events come from default config extension_cfgBindings section.
  438. Keybindings list come from the splitting of GetOption, which
  439. tries user config before default config.
  440. """
  441. keysName = extensionName+'_cfgBindings'
  442. extKeys = {}
  443. if self.defaultCfg['extensions'].has_section(keysName):
  444. eventNames = self.defaultCfg['extensions'].GetOptionList(keysName)
  445. for eventName in eventNames:
  446. binding = self.GetOption(
  447. 'extensions', keysName, eventName, default='').split()
  448. event = '<<' + eventName + '>>'
  449. extKeys[event] = binding
  450. return extKeys
  451. def GetExtensionBindings(self, extensionName):
  452. """Return dict {extensionName event : active or defined keybinding}.
  453. Augment self.GetExtensionKeys(extensionName) with mapping of non-
  454. configurable events (from default config) to GetOption splits,
  455. as in self.__GetRawExtensionKeys.
  456. """
  457. bindsName = extensionName + '_bindings'
  458. extBinds = self.GetExtensionKeys(extensionName)
  459. #add the non-configurable bindings
  460. if self.defaultCfg['extensions'].has_section(bindsName):
  461. eventNames = self.defaultCfg['extensions'].GetOptionList(bindsName)
  462. for eventName in eventNames:
  463. binding = self.GetOption(
  464. 'extensions', bindsName, eventName, default='').split()
  465. event = '<<' + eventName + '>>'
  466. extBinds[event] = binding
  467. return extBinds
  468. def GetKeyBinding(self, keySetName, eventStr):
  469. """Return the keybinding list for keySetName eventStr.
  470. keySetName - name of key binding set (config-keys section).
  471. eventStr - virtual event, including brackets, as in '<<event>>'.
  472. """
  473. eventName = eventStr[2:-2] #trim off the angle brackets
  474. binding = self.GetOption('keys', keySetName, eventName, default='').split()
  475. return binding
  476. def GetCurrentKeySet(self):
  477. "Return CurrentKeys with 'darwin' modifications."
  478. result = self.GetKeySet(self.CurrentKeys())
  479. if sys.platform == "darwin":
  480. # OS X Tk variants do not support the "Alt" keyboard modifier.
  481. # So replace all keybingings that use "Alt" with ones that
  482. # use the "Option" keyboard modifier.
  483. # TODO (Ned?): the "Option" modifier does not work properly for
  484. # Cocoa Tk and XQuartz Tk so we should not use it
  485. # in default OS X KeySets.
  486. for k, v in result.items():
  487. v2 = [ x.replace('<Alt-', '<Option-') for x in v ]
  488. if v != v2:
  489. result[k] = v2
  490. return result
  491. def GetKeySet(self, keySetName):
  492. """Return event-key dict for keySetName core plus active extensions.
  493. If a binding defined in an extension is already in use, the
  494. extension binding is disabled by being set to ''
  495. """
  496. keySet = self.GetCoreKeys(keySetName)
  497. activeExtns = self.GetExtensions(active_only=1)
  498. for extn in activeExtns:
  499. extKeys = self.__GetRawExtensionKeys(extn)
  500. if extKeys: #the extension defines keybindings
  501. for event in extKeys:
  502. if extKeys[event] in keySet.values():
  503. #the binding is already in use
  504. extKeys[event] = '' #disable this binding
  505. keySet[event] = extKeys[event] #add binding
  506. return keySet
  507. def IsCoreBinding(self, virtualEvent):
  508. """Return True if the virtual event is one of the core idle key events.
  509. virtualEvent - string, name of the virtual event to test for,
  510. without the enclosing '<< >>'
  511. """
  512. return ('<<'+virtualEvent+'>>') in self.GetCoreKeys()
  513. # TODO make keyBindins a file or class attribute used for test above
  514. # and copied in function below
  515. def GetCoreKeys(self, keySetName=None):
  516. """Return dict of core virtual-key keybindings for keySetName.
  517. The default keySetName None corresponds to the keyBindings base
  518. dict. If keySetName is not None, bindings from the config
  519. file(s) are loaded _over_ these defaults, so if there is a
  520. problem getting any core binding there will be an 'ultimate last
  521. resort fallback' to the CUA-ish bindings defined here.
  522. """
  523. keyBindings={
  524. '<<copy>>': ['<Control-c>', '<Control-C>'],
  525. '<<cut>>': ['<Control-x>', '<Control-X>'],
  526. '<<paste>>': ['<Control-v>', '<Control-V>'],
  527. '<<beginning-of-line>>': ['<Control-a>', '<Home>'],
  528. '<<center-insert>>': ['<Control-l>'],
  529. '<<close-all-windows>>': ['<Control-q>'],
  530. '<<close-window>>': ['<Alt-F4>'],
  531. '<<do-nothing>>': ['<Control-x>'],
  532. '<<end-of-file>>': ['<Control-d>'],
  533. '<<python-docs>>': ['<F1>'],
  534. '<<python-context-help>>': ['<Shift-F1>'],
  535. '<<history-next>>': ['<Alt-n>'],
  536. '<<history-previous>>': ['<Alt-p>'],
  537. '<<interrupt-execution>>': ['<Control-c>'],
  538. '<<view-restart>>': ['<F6>'],
  539. '<<restart-shell>>': ['<Control-F6>'],
  540. '<<open-class-browser>>': ['<Alt-c>'],
  541. '<<open-module>>': ['<Alt-m>'],
  542. '<<open-new-window>>': ['<Control-n>'],
  543. '<<open-window-from-file>>': ['<Control-o>'],
  544. '<<plain-newline-and-indent>>': ['<Control-j>'],
  545. '<<print-window>>': ['<Control-p>'],
  546. '<<redo>>': ['<Control-y>'],
  547. '<<remove-selection>>': ['<Escape>'],
  548. '<<save-copy-of-window-as-file>>': ['<Alt-Shift-S>'],
  549. '<<save-window-as-file>>': ['<Alt-s>'],
  550. '<<save-window>>': ['<Control-s>'],
  551. '<<select-all>>': ['<Alt-a>'],
  552. '<<toggle-auto-coloring>>': ['<Control-slash>'],
  553. '<<undo>>': ['<Control-z>'],
  554. '<<find-again>>': ['<Control-g>', '<F3>'],
  555. '<<find-in-files>>': ['<Alt-F3>'],
  556. '<<find-selection>>': ['<Control-F3>'],
  557. '<<find>>': ['<Control-f>'],
  558. '<<replace>>': ['<Control-h>'],
  559. '<<goto-line>>': ['<Alt-g>'],
  560. '<<smart-backspace>>': ['<Key-BackSpace>'],
  561. '<<newline-and-indent>>': ['<Key-Return>', '<Key-KP_Enter>'],
  562. '<<smart-indent>>': ['<Key-Tab>'],
  563. '<<indent-region>>': ['<Control-Key-bracketright>'],
  564. '<<dedent-region>>': ['<Control-Key-bracketleft>'],
  565. '<<comment-region>>': ['<Alt-Key-3>'],
  566. '<<uncomment-region>>': ['<Alt-Key-4>'],
  567. '<<tabify-region>>': ['<Alt-Key-5>'],
  568. '<<untabify-region>>': ['<Alt-Key-6>'],
  569. '<<toggle-tabs>>': ['<Alt-Key-t>'],
  570. '<<change-indentwidth>>': ['<Alt-Key-u>'],
  571. '<<del-word-left>>': ['<Control-Key-BackSpace>'],
  572. '<<del-word-right>>': ['<Control-Key-Delete>']
  573. }
  574. if keySetName:
  575. for event in keyBindings:
  576. binding = self.GetKeyBinding(keySetName, event)
  577. if binding:
  578. keyBindings[event] = binding
  579. else: #we are going to return a default, print warning
  580. warning=('\n Warning: configHandler.py - IdleConf.GetCoreKeys'
  581. ' -\n problem retrieving key binding for event %r'
  582. '\n from key set %r.\n'
  583. ' returning default value: %r' %
  584. (event, keySetName, keyBindings[event]))
  585. try:
  586. print(warning, file=sys.stderr)
  587. except IOError:
  588. pass
  589. return keyBindings
  590. def GetExtraHelpSourceList(self, configSet):
  591. """Return list of extra help sources from a given configSet.
  592. Valid configSets are 'user' or 'default'. Return a list of tuples of
  593. the form (menu_item , path_to_help_file , option), or return the empty
  594. list. 'option' is the sequence number of the help resource. 'option'
  595. values determine the position of the menu items on the Help menu,
  596. therefore the returned list must be sorted by 'option'.
  597. """
  598. helpSources = []
  599. if configSet == 'user':
  600. cfgParser = self.userCfg['main']
  601. elif configSet == 'default':
  602. cfgParser = self.defaultCfg['main']
  603. else:
  604. raise InvalidConfigSet('Invalid configSet specified')
  605. options=cfgParser.GetOptionList('HelpFiles')
  606. for option in options:
  607. value=cfgParser.Get('HelpFiles', option, default=';')
  608. if value.find(';') == -1: #malformed config entry with no ';'
  609. menuItem = '' #make these empty
  610. helpPath = '' #so value won't be added to list
  611. else: #config entry contains ';' as expected
  612. value=value.split(';')
  613. menuItem=value[0].strip()
  614. helpPath=value[1].strip()
  615. if menuItem and helpPath: #neither are empty strings
  616. helpSources.append( (menuItem,helpPath,option) )
  617. helpSources.sort(key=lambda x: int(x[2]))
  618. return helpSources
  619. def GetAllExtraHelpSourcesList(self):
  620. """Return a list of the details of all additional help sources.
  621. Tuples in the list are those of GetExtraHelpSourceList.
  622. """
  623. allHelpSources = (self.GetExtraHelpSourceList('default') +
  624. self.GetExtraHelpSourceList('user') )
  625. return allHelpSources
  626. def GetFont(self, root, configType, section):
  627. """Retrieve a font from configuration (font, font-size, font-bold)
  628. Intercept the special value 'TkFixedFont' and substitute
  629. the actual font, factoring in some tweaks if needed for
  630. appearance sakes.
  631. The 'root' parameter can normally be any valid Tkinter widget.
  632. Return a tuple (family, size, weight) suitable for passing
  633. to tkinter.Font
  634. """
  635. family = self.GetOption(configType, section, 'font', default='courier')
  636. size = self.GetOption(configType, section, 'font-size', type='int',
  637. default='10')
  638. bold = self.GetOption(configType, section, 'font-bold', default=0,
  639. type='bool')
  640. if (family == 'TkFixedFont'):
  641. if TkVersion < 8.5:
  642. family = 'Courier'
  643. else:
  644. f = Font(name='TkFixedFont', exists=True, root=root)
  645. actualFont = Font.actual(f)
  646. family = actualFont['family']
  647. size = actualFont['size']
  648. if size <= 0:
  649. size = 10 # if font in pixels, ignore actual size
  650. bold = actualFont['weight']=='bold'
  651. return (family, size, 'bold' if bold else 'normal')
  652. def LoadCfgFiles(self):
  653. "Load all configuration files."
  654. for key in self.defaultCfg:
  655. self.defaultCfg[key].Load()
  656. self.userCfg[key].Load() #same keys
  657. def SaveUserCfgFiles(self):
  658. "Write all loaded user configuration files to disk."
  659. for key in self.userCfg:
  660. self.userCfg[key].Save()
  661. idleConf = IdleConf()
  662. # TODO Revise test output, write expanded unittest
  663. ### module test
  664. if __name__ == '__main__':
  665. def dumpCfg(cfg):
  666. print('\n', cfg, '\n')
  667. for key in cfg:
  668. sections = cfg[key].sections()
  669. print(key)
  670. print(sections)
  671. for section in sections:
  672. options = cfg[key].options(section)
  673. print(section)
  674. print(options)
  675. for option in options:
  676. print(option, '=', cfg[key].Get(section, option))
  677. dumpCfg(idleConf.defaultCfg)
  678. dumpCfg(idleConf.userCfg)
  679. print(idleConf.userCfg['main'].Get('Theme', 'name'))
  680. #print(idleConf.userCfg['highlight'].GetDefHighlight('Foo','normal'))