/Lib/idlelib/configHandler.py

http://unladen-swallow.googlecode.com/ · Python · 712 lines · 550 code · 21 blank · 141 comment · 66 complexity · ff9dfa21b458e03165a41785799a2d5e MD5 · raw file

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