"""Provides access to stored IDLE configuration information.
Refer to the comments at the beginning of config-main.def for a description of
the available configuration files and the design implemented to update user
configuration information. In particular, user configuration choices which
duplicate the defaults will be removed from the user's configuration files,
and if a file becomes empty, it will be deleted.
The contents of the user files may be altered using the Options/Configure IDLE
menu to access the configuration GUI (configDialog.py), or manually.
Throughout this module there is an emphasis on returning useable defaults
when a problem occurs in returning a requested configuration value back to
idle. This is to allow IDLE to continue to function in spite of errors in
the retrieval of config information. When a default is returned instead of
a requested config value, a message is printed to stderr to aid in
configuration problem notification and resolution.
# TODOs added Oct 2014, tjr
from __future__ import print_function
from ConfigParser import ConfigParser
from Tkinter import TkVersion
from tkFont import Font, nametofont
class InvalidConfigType(Exception): pass
class InvalidConfigSet(Exception): pass
class InvalidFgBg(Exception): pass
class InvalidTheme(Exception): pass
class IdleConfParser(ConfigParser):
A ConfigParser specialised for idle configuration file handling
def __init__(self, cfgFile, cfgDefaults=None):
cfgFile - string, fully specified configuration file name
ConfigParser.__init__(self, defaults=cfgDefaults)
def Get(self, section, option, type=None, default=None, raw=False):
Get an option value for given section/option or return default.
If type is specified, return as type.
# TODO Use default as fallback, at least if not None
# Should also print Warning(file, section, option).
# Currently may raise ValueError
if not self.has_option(section, option):
return self.getboolean(section, option)
return self.getint(section, option)
return self.get(section, option, raw=raw)
def GetOptionList(self, section):
"Return a list of options for given section, else []."
if self.has_section(section):
return self.options(section)
else: #return a default value
"Load the configuration file from disk."
class IdleUserConfParser(IdleConfParser):
IdleConfigParser specialised for user configuration handling.
def AddSection(self, section):
"If section doesn't exist, add it."
if not self.has_section(section):
self.add_section(section)
def RemoveEmptySections(self):
"Remove any sections that have no options."
for section in self.sections():
if not self.GetOptionList(section):
self.remove_section(section)
"Return True if no sections after removing empty sections."
self.RemoveEmptySections()
return not self.sections()
def RemoveOption(self, section, option):
"""Return True if option is removed from section, else False.
False if either section does not exist or did not have option.
if self.has_section(section):
return self.remove_option(section, option)
def SetOption(self, section, option, value):
"""Return True if option is added or changed to value, else False.
Add section if required. False means option already had value.
if self.has_option(section, option):
if self.get(section, option) == value:
self.set(section, option, value)
if not self.has_section(section):
self.add_section(section)
self.set(section, option, value)
"Remove user config file self.file from disk if it exists."
if os.path.exists(self.file):
"""Update user configuration file.
Remove empty sections. If resulting config isn't empty, write the file
to disk. If config is empty, remove the file from disk if it exists.
cfgFile = open(fname, 'w')
cfgFile = open(fname, 'w')
"""Hold config parsers for all idle config files in singleton instance.
Default config files, self.defaultCfg --
for config_type in self.config_types:
(idle install dir)/config-{config-type}.def
User config files, self.userCfg --
for config_type in self.config_types:
(user home dir)/.idlerc/config-{config-type}.cfg
self.config_types = ('main', 'extensions', 'highlight', 'keys')
self.cfg = {} # TODO use to select userCfg vs defaultCfg
self.CreateConfigHandlers()
def CreateConfigHandlers(self):
"Populate default and user config parser dictionaries."
if __name__ != '__main__': # we were imported
idleDir=os.path.dirname(__file__)
else: # we were exec'ed (for testing only)
idleDir=os.path.abspath(sys.path[0])
userDir=self.GetUserCfgDir()
# TODO eliminate these temporaries by combining loops
for cfgType in self.config_types: #build config file names
defCfgFiles[cfgType] = os.path.join(
idleDir, 'config-' + cfgType + '.def')
usrCfgFiles[cfgType] = os.path.join(
userDir, 'config-' + cfgType + '.cfg')
for cfgType in self.config_types: #create config parsers
self.defaultCfg[cfgType] = IdleConfParser(defCfgFiles[cfgType])
self.userCfg[cfgType] = IdleUserConfParser(usrCfgFiles[cfgType])
"""Return a filesystem directory for storing user config files.
userDir = os.path.expanduser('~')
if userDir != '~': # expanduser() found user home dir
if not os.path.exists(userDir):
warn = ('\n Warning: os.path.expanduser("~") points to\n ' +
userDir + ',\n but the path does not exist.')
print(warn, file=sys.stderr)
if userDir == "~": # still no path to home!
# traditionally IDLE has defaulted to os.getcwd(), is this adequate?
userDir = os.path.join(userDir, cfgDir)
if not os.path.exists(userDir):
except (OSError, IOError):
warn = ('\n Warning: unable to create user config directory\n' +
userDir + '\n Check path and permissions.\n Exiting!\n')
print(warn, file=sys.stderr)
# TODO continue without userDIr instead of exit
def GetOption(self, configType, section, option, default=None, type=None,
warn_on_default=True, raw=False):
"""Return a value for configType section option, or default.
If type is not None, return a value of that type. Also pass raw
to the config parser. First try to return a valid value
(including type) from a user configuration. If that fails, try
the default configuration. If that fails, return default, with a
Warn if either user or default configurations have an invalid value.
Warn if default is returned and warn_on_default is True.
if self.userCfg[configType].has_option(section, option):
return self.userCfg[configType].Get(section, option,
warning = ('\n Warning: configHandler.py - IdleConf.GetOption -\n'
' invalid %r value for configuration option %r\n'
self.userCfg[configType].Get(section, option, raw=raw)))
print(warning, file=sys.stderr)
if self.defaultCfg[configType].has_option(section,option):
return self.defaultCfg[configType].Get(
section, option, type=type, raw=raw)
#returning default, print warning
warning = ('\n Warning: configHandler.py - IdleConf.GetOption -\n'
' problem retrieving configuration option %r\n'
' returning default value: %r' %
(option, section, default))
print(warning, file=sys.stderr)
def SetOption(self, configType, section, option, value):
"""Set section option to value in user config file."""
self.userCfg[configType].SetOption(section, option, value)
def GetSectionList(self, configSet, configType):
"""Return sections for configSet configType configuration.
configSet must be either 'user' or 'default'
configType must be in self.config_types.
if not (configType in self.config_types):
raise InvalidConfigType('Invalid configType specified')
cfgParser = self.userCfg[configType]
elif configSet == 'default':
cfgParser=self.defaultCfg[configType]
raise InvalidConfigSet('Invalid configSet specified')
return cfgParser.sections()
def GetHighlight(self, theme, element, fgBg=None):
"""Return individual theme element highlight color(s).
fgBg - string ('fg' or 'bg') or None.
If None, return a dictionary containing fg and bg colors with
keys 'foreground' and 'background'. Otherwise, only return
fg or bg color, as specified. Colors are intended to be
appropriate for passing to Tkinter in, e.g., a tag_config call).
if self.defaultCfg['highlight'].has_section(theme):
themeDict = self.GetThemeDict('default', theme)
themeDict = self.GetThemeDict('user', theme)
fore = themeDict[element + '-foreground']
if element == 'cursor': # There is no config value for cursor bg
back = themeDict['normal-background']
back = themeDict[element + '-background']
highlight = {"foreground": fore, "background": back}
if not fgBg: # Return dict of both colors
else: # Return specified color only
return highlight["foreground"]
return highlight["background"]
raise InvalidFgBg('Invalid fgBg specified')
def GetThemeDict(self, type, themeName):
"""Return {option:value} dict for elements in themeName.
type - string, 'default' or 'user' theme type
themeName - string, theme name
Values are loaded over ultimate fallback defaults to guarantee
that all theme elements are present in a newly created theme.
cfgParser = self.userCfg['highlight']
cfgParser = self.defaultCfg['highlight']
raise InvalidTheme('Invalid theme type specified')
# Provide foreground and background colors for each theme
# element (other than cursor) even though some values are not
# yet used by idle, to allow for their use in the future.
# Default values are generally black and white.
# TODO copy theme from a class attribute.
theme ={'normal-foreground':'#000000',
'normal-background':'#ffffff',
'keyword-foreground':'#000000',
'keyword-background':'#ffffff',
'builtin-foreground':'#000000',
'builtin-background':'#ffffff',
'comment-foreground':'#000000',
'comment-background':'#ffffff',
'string-foreground':'#000000',
'string-background':'#ffffff',
'definition-foreground':'#000000',
'definition-background':'#ffffff',
'hilite-foreground':'#000000',
'hilite-background':'gray',
'break-foreground':'#ffffff',
'break-background':'#000000',
'hit-foreground':'#ffffff',
'hit-background':'#000000',
'error-foreground':'#ffffff',
'error-background':'#000000',
#cursor (only foreground can be set)
'cursor-foreground':'#000000',
'stdout-foreground':'#000000',
'stdout-background':'#ffffff',
'stderr-foreground':'#000000',
'stderr-background':'#ffffff',
'console-foreground':'#000000',
'console-background':'#ffffff' }
if not cfgParser.has_option(themeName, element):
# Print warning that will return a default color
warning = ('\n Warning: configHandler.IdleConf.GetThemeDict'
' -\n problem retrieving theme element %r'
' returning default color: %r' %
(element, themeName, theme[element]))
print(warning, file=sys.stderr)
theme[element] = cfgParser.Get(
themeName, element, default=theme[element])
"""Return the name of the currently active text color theme.
idlelib.config-main.def includes this section
# name2 set in user config-main.cfg for themes added after 2015 Oct 1
Item name2 is needed because setting name to a new builtin
causes older IDLEs to display multiple error messages or quit.
See https://bugs.python.org/issue25313.
When default = True, name2 takes precedence over name,
while older IDLEs will just use name.
default = self.GetOption('main', 'Theme', 'default',
type='bool', default=True)
theme = self.GetOption('main', 'Theme', 'name2', default='')
if default and not theme or not default:
theme = self.GetOption('main', 'Theme', 'name', default='')
source = self.defaultCfg if default else self.userCfg
if source['highlight'].has_section(theme):
"Return the name of the currently active key set."
return self.GetOption('main', 'Keys', 'name', default='')
def GetExtensions(self, active_only=True, editor_only=False, shell_only=False):
"""Return extensions in default and user config-extensions files.
If active_only True, only return active (enabled) extensions
and optionally only editor or shell extensions.
If active_only False, return all extensions.
extns = self.RemoveKeyBindNames(
self.GetSectionList('default', 'extensions'))
userExtns = self.RemoveKeyBindNames(
self.GetSectionList('user', 'extensions'))
if extn not in extns: #user has added own extension
if self.GetOption('extensions', extn, 'enable', default=True,
#the extension is enabled
if editor_only or shell_only: # TODO if both, contradictory
if self.GetOption('extensions', extn,option,
default=True, type='bool',
def RemoveKeyBindNames(self, extnNameList):
"Return extnNameList with keybinding section names removed."
# TODO Easier to return filtered copy with list comp
if name.endswith(('_bindings', '_cfgBindings')):
kbNameIndicies.append(names.index(name))
kbNameIndicies.sort(reverse=True)
for index in kbNameIndicies: #delete each keybinding section name
def GetExtnNameForEvent(self, virtualEvent):
"""Return the name of the extension binding virtualEvent, or None.
virtualEvent - string, name of the virtual event to test for,
without the enclosing '<< >>'
vEvent = '<<' + virtualEvent + '>>'
for extn in self.GetExtensions(active_only=0):
for event in self.GetExtensionKeys(extn):
extName = extn # TODO return here?
def GetExtensionKeys(self, extensionName):
"""Return dict: {configurable extensionName event : active keybinding}.
Events come from default config extension_cfgBindings section.
Keybindings come from GetCurrentKeySet() active key dict,
where previously used bindings are disabled.
keysName = extensionName + '_cfgBindings'
activeKeys = self.GetCurrentKeySet()
if self.defaultCfg['extensions'].has_section(keysName):
eventNames = self.defaultCfg['extensions'].GetOptionList(keysName)
for eventName in eventNames:
event = '<<' + eventName + '>>'
binding = activeKeys[event]
def __GetRawExtensionKeys(self,extensionName):
"""Return dict {configurable extensionName event : keybinding list}.
Events come from default config extension_cfgBindings section.
Keybindings list come from the splitting of GetOption, which
tries user config before default config.
keysName = extensionName+'_cfgBindings'
if self.defaultCfg['extensions'].has_section(keysName):
eventNames = self.defaultCfg['extensions'].GetOptionList(keysName)
for eventName in eventNames:
binding = self.GetOption(
'extensions', keysName, eventName, default='').split()