Consistent string chars

This commit is contained in:
Florian Bruhin 2014-04-25 16:53:23 +02:00
parent 35ba97d338
commit 9252ef94ca
23 changed files with 210 additions and 211 deletions

1
TODO
View File

@ -16,7 +16,6 @@ decorators for often-used signals from singletons?
- @on_config_changed('colors')
- @on_enter_mode('hints')
Use py3.4 Enums with a backport to qutebrowser.utils?
" vs ' with strings
Major features
==============

View File

@ -151,7 +151,7 @@ class QuteBrowser(QApplication):
self.setQuitOnLastWindowClosed(False)
self._connect_signals()
modeman.enter("normal")
modeman.enter('normal')
self.mainwindow.show()
self._python_hacks()
@ -166,15 +166,15 @@ class QuteBrowser(QApplication):
"""
parser = ArgumentParser("usage: %(prog)s [options]")
parser.add_argument('-l', '--log', dest='loglevel',
help='Set loglevel', default='info')
parser.add_argument('-c', '--confdir', help='Set config directory '
'(empty for no config storage)')
parser.add_argument('-d', '--debug', help='Turn on debugging options.',
help="Set loglevel", default='info')
parser.add_argument('-c', '--confdir', help="Set config directory "
"(empty for no config storage)")
parser.add_argument('-d', '--debug', help="Turn on debugging options.",
action='store_true')
parser.add_argument('command', nargs='*', help='Commands to execute '
'on startup.', metavar=':command')
parser.add_argument('command', nargs='*', help="Commands to execute "
"on startup.", metavar=':command')
# URLs will actually be in command
parser.add_argument('url', nargs='*', help='URLs to open on startup.')
parser.add_argument('url', nargs='*', help="URLs to open on startup.")
return parser.parse_args()
def _initlog(self):
@ -186,7 +186,7 @@ class QuteBrowser(QApplication):
loglevel = 'debug' if self._args.debug else self._args.loglevel
numeric_level = getattr(logging, loglevel.upper(), None)
if not isinstance(numeric_level, int):
raise ValueError('Invalid log level: {}'.format(loglevel))
raise ValueError("Invalid log level: {}".format(loglevel))
logging.basicConfig(
level=numeric_level,
format='%(asctime)s [%(levelname)s] '
@ -227,15 +227,15 @@ class QuteBrowser(QApplication):
for e in self._args.command:
if e.startswith(':'):
logging.debug('Startup cmd {}'.format(e))
logging.debug("Startup cmd {}".format(e))
self.commandmanager.run(e.lstrip(':'))
else:
logging.debug('Startup url {}'.format(e))
logging.debug("Startup url {}".format(e))
self._opened_urls.append(e)
self.mainwindow.tabs.tabopen(e)
if self.mainwindow.tabs.count() == 0:
logging.debug('Opening startpage')
logging.debug("Opening startpage")
for url in config.get('general', 'startpage'):
self.mainwindow.tabs.tabopen(url)
@ -278,12 +278,12 @@ class QuteBrowser(QApplication):
cmd.got_search_rev.connect(self.searchmanager.search_rev)
cmd.returnPressed.connect(tabs.setFocus)
self.searchmanager.do_search.connect(tabs.cur.search)
kp["normal"].keystring_updated.connect(status.keystring.setText)
kp['normal'].keystring_updated.connect(status.keystring.setText)
# hints
kp["hint"].fire_hint.connect(tabs.cur.fire_hint)
kp["hint"].keystring_updated.connect(tabs.cur.handle_hint_key)
tabs.hint_strings_updated.connect(kp["hint"].on_hint_strings_updated)
kp['hint'].fire_hint.connect(tabs.cur.fire_hint)
kp['hint'].keystring_updated.connect(tabs.cur.handle_hint_key)
tabs.hint_strings_updated.connect(kp['hint'].on_hint_strings_updated)
# messages
message.bridge.error.connect(status.disp_error)
@ -294,7 +294,7 @@ class QuteBrowser(QApplication):
# config
self.config.style_changed.connect(style.invalidate_caches)
for obj in [tabs, completion, self.mainwindow, config.cmd_history,
websettings, kp["normal"], modeman.manager]:
websettings, kp['normal'], modeman.manager]:
self.config.changed.connect(obj.on_config_changed)
# statusbar
@ -397,7 +397,7 @@ class QuteBrowser(QApplication):
except ValueError:
pass
argv = [sys.executable] + argv + pages
logging.debug('Running {} with args {}'.format(sys.executable,
logging.debug("Running {} with args {}".format(sys.executable,
argv))
subprocess.Popen(argv)
self._maybe_quit('crash')

View File

@ -184,7 +184,7 @@ class CurCommandDispatcher(QObject):
break
@cmdutils.register(instance='mainwindow.tabs.cur')
def hint(self, mode="all", target="normal"):
def hint(self, mode='all', target='normal'):
"""Start hinting.
Command handler for :hint.
@ -288,8 +288,8 @@ class CurCommandDispatcher(QObject):
url = urlutils.urlstring(self._tabs.currentWidget().url())
mode = QClipboard.Selection if sel else QClipboard.Clipboard
clip.setText(url, mode)
message.info('URL yanked to {}'.format('primary selection' if sel
else 'clipboard'))
message.info("URL yanked to {}".format("primary selection" if sel
else "clipboard"))
@cmdutils.register(instance='mainwindow.tabs.cur', name='yanktitle')
def yank_title(self, sel=False):
@ -304,8 +304,8 @@ class CurCommandDispatcher(QObject):
title = self._tabs.tabText(self._tabs.currentIndex())
mode = QClipboard.Selection if sel else QClipboard.Clipboard
clip.setText(title, mode)
message.info('Title yanked to {}'.format('primary selection' if sel
else 'clipboard'))
message.info("Title yanked to {}".format("primary selection" if sel
else "clipboard"))
@cmdutils.register(instance='mainwindow.tabs.cur', name='zoomin')
def zoom_in(self, count=1):

View File

@ -47,10 +47,10 @@ class HintManager(QObject):
_elems: A mapping from keystrings to (elem, label) namedtuples.
_baseurl: The URL of the current page.
_target: What to do with the opened links.
"normal"/"tab"/"bgtab": Get passed to BrowserTab.
"yank"/"yank_primary": Yank to clipboard/primary selection
"cmd"/"cmd_tab"/"cmd_bgtab": Enter link to commandline
"rapid": Rapid mode with background tabs
'normal'/'tab'/'bgtab': Get passed to BrowserTab.
'yank'/'yank_primary': Yank to clipboard/primary selection
'cmd'/'cmd_tab'/'cmd_bgtab': Enter link to commandline
'rapid': Rapid mode with background tabs
Signals:
hint_strings_updated: Emitted when the possible hint strings changed.
@ -239,8 +239,8 @@ class HintManager(QObject):
"""
mode = QClipboard.Selection if sel else QClipboard.Clipboard
QApplication.clipboard().setText(urlutils.urlstring(link), mode)
message.info('URL yanked to {}'.format('primary selection' if sel
else 'clipboard'))
message.info("URL yanked to {}".format("primary selection" if sel
else "clipboard"))
def _resolve_link(self, elem):
"""Resolve a link and check if we want to keep it.
@ -259,7 +259,7 @@ class HintManager(QObject):
link = self._baseurl.resolved(link)
return link
def start(self, frame, baseurl, mode="all", target="normal"):
def start(self, frame, baseurl, mode='all', target='normal'):
"""Start hinting.
Args:
@ -284,15 +284,15 @@ class HintManager(QObject):
message.error("No elements found.")
return
texts = {
"normal": "Follow hint...",
"tab": "Follow hint in new tab...",
"bgtab": "Follow hint in background tab...",
"yank": "Yank hint to clipboard...",
"yank_primary": "Yank hint to primary selection...",
"cmd": "Set hint in commandline...",
"cmd_tab": "Set hint in commandline as new tab...",
"cmd_bgtab": "Set hint in commandline as background tab...",
"rapid": "Follow hint (rapid mode)...",
'normal': "Follow hint...",
'tab': "Follow hint in new tab...",
'bgtab': "Follow hint in background tab...",
'yank': "Yank hint to clipboard...",
'yank_primary': "Yank hint to primary selection...",
'cmd': "Set hint in commandline...",
'cmd_tab': "Set hint in commandline as new tab...",
'cmd_bgtab': "Set hint in commandline as background tab...",
'rapid': "Follow hint (rapid mode)...",
}
message.text(texts[target])
strings = self._hint_strings(visible_elems)
@ -301,7 +301,7 @@ class HintManager(QObject):
self._elems[string] = ElemTuple(e, label)
frame.contentsSizeChanged.connect(self.on_contents_size_changed)
self.hint_strings_updated.emit(strings)
modeman.enter("hint")
modeman.enter('hint')
def handle_partial_key(self, keystr):
"""Handle a new partial keypress."""
@ -311,7 +311,7 @@ class HintManager(QObject):
matched = string[:len(keystr)]
rest = string[len(keystr):]
elems.label.setInnerXml('<font color="{}">{}</font>{}'.format(
config.get("colors", "hints.fg.match"), matched, rest))
config.get('colors', 'hints.fg.match'), matched, rest))
else:
elems.label.removeFromDocument()
delete.append(string)
@ -344,7 +344,7 @@ class HintManager(QObject):
message.set_cmd_text(':{} {}'.format(commands[self._target],
urlutils.urlstring(link)))
if self._target != 'rapid':
modeman.leave("hint")
modeman.leave('hint')
@pyqtSlot('QSize')
def on_contents_size_changed(self, _size):
@ -353,12 +353,12 @@ class HintManager(QObject):
rect = elems.elem.geometry()
css = self.HINT_CSS.format(left=rect.x(), top=rect.y(),
config=config.instance)
elems.label.setAttribute("style", css)
elems.label.setAttribute('style', css)
@pyqtSlot(str)
def on_mode_left(self, mode):
"""Stop hinting when hinting mode was left."""
if mode != "hint":
if mode != 'hint':
return
for elem in self._elems.values():
elem.label.removeFromDocument()

View File

@ -74,18 +74,18 @@ class SignalFilter(QObject):
sender = self.sender()
log_signal = not signal.signal.startswith('2cur_progress')
if log_signal:
logging.debug('signal {} (tab {})'.format(
logging.debug("signal {} (tab {})".format(
dbg_signal(signal, args), self._tabs.indexOf(sender)))
if not isinstance(sender, WebView):
# BUG? This should never happen, but it does regularely...
logging.warn('Got signal {} by {} which is no tab!'.format(
logging.warn("Got signal {} by {} which is no tab!".format(
dbg_signal(signal, args), sender))
return
sender.signal_cache.add(signal, args)
if self._tabs.currentWidget() == sender:
if log_signal:
logging.debug(' emitting')
logging.debug(" emitting")
signal.emit(*args)
else:
if log_signal:
logging.debug(' ignoring')
logging.debug(" ignoring")

View File

@ -36,7 +36,7 @@ class ValidationError(ValueError):
option = None
def __init__(self, value, msg):
super().__init__('Invalid value "{}" - {}'.format(value, msg))
super().__init__("Invalid value \"{}\" - {}".format(value, msg))
class ValidValues:
@ -472,10 +472,10 @@ class SearchEngineUrl(BaseType):
"""A search engine URL."""
def validate(self, value):
if "{}" in value:
if '{}' in value:
pass
else:
raise ValidationError(value, 'must contain "{}"')
raise ValidationError(value, "must contain \"{}\"")
class KeyBindingName(BaseType):
@ -490,22 +490,22 @@ class AutoSearch(BaseType):
"""Whether to start a search when something else than an URL is entered."""
valid_values = ValidValues(("naive", "Use simple/naive check."),
("dns", "Use DNS requests (might be slow!)."),
("false", "Never search automatically."))
valid_values = ValidValues(('naive', "Use simple/naive check."),
('dns', "Use DNS requests (might be slow!)."),
('false', "Never search automatically."))
def validate(self, value):
if value.lower() in ["naive", "dns"]:
if value.lower() in ['naive', 'dns']:
pass
else:
Bool.validate(self, value)
def transform(self, value):
if value.lower() in ["naive", "dns"]:
if value.lower() in ['naive', 'dns']:
return value.lower()
elif super().transform(value):
# boolean true is an alias for naive matching
return "naive"
return 'naive'
else:
return False
@ -514,7 +514,7 @@ class Position(String):
"""The position of the tab bar."""
valid_values = ValidValues("north", "south", "east", "west")
valid_values = ValidValues('north', 'south', 'east', 'west')
class SelectOnRemove(String):
@ -522,18 +522,18 @@ class SelectOnRemove(String):
"""Which tab to select when the focused tab is removed."""
valid_values = ValidValues(
("left", "Select the tab on the left."),
("right", "Select the tab on the right."),
("previous", "Select the previously selected tab."))
('left', "Select the tab on the left."),
('right', "Select the tab on the right."),
('previous', "Select the previously selected tab."))
class LastClose(String):
"""Behaviour when the last tab is closed."""
valid_values = ValidValues(("ignore", "Don't do anything."),
("blank", "Load about:blank."),
("quit", "Quit qutebrowser."))
valid_values = ValidValues(('ignore', "Don't do anything."),
('blank', "Load about:blank."),
('quit', "Quit qutebrowser."))
class KeyBinding(Command):

View File

@ -174,7 +174,7 @@ class ConfigManager(QObject):
typestr = ''
else:
typestr = ' ({})'.format(option.typ.typestr)
lines.append('# {}{}:'.format(optname, typestr))
lines.append("# {}{}:".format(optname, typestr))
try:
desc = self.sections[secname].descriptions[optname]
except KeyError:
@ -186,11 +186,11 @@ class ConfigManager(QObject):
if valid_values.descriptions:
for val in valid_values:
desc = valid_values.descriptions[val]
lines += wrapper.wrap(' {}: {}'.format(val, desc))
lines += wrapper.wrap(" {}: {}".format(val, desc))
else:
lines += wrapper.wrap('Valid values: {}'.format(', '.join(
lines += wrapper.wrap("Valid values: {}".format(', '.join(
valid_values)))
lines += wrapper.wrap('Default: {}'.format(
lines += wrapper.wrap("Default: {}".format(
option.values['default']))
return lines

View File

@ -140,212 +140,212 @@ SECTION_DESC = {
DATA = OrderedDict([
('general', sect.KeyValue(
('show_completion',
SettingValue(types.Bool(), "true"),
SettingValue(types.Bool(), 'true'),
"Whether to show the autocompletion window or not."),
('completion_height',
SettingValue(types.PercOrInt(minperc=0, maxperc=100, minint=1),
"50%"),
'50%'),
"The height of the completion, in px or as percentage of the "
"window."),
('ignorecase',
SettingValue(types.Bool(), "true"),
SettingValue(types.Bool(), 'true'),
"Whether to do case-insensitive searching."),
('wrapsearch',
SettingValue(types.Bool(), "true"),
SettingValue(types.Bool(), 'true'),
"Whether to wrap search to the top when arriving at the end."),
('startpage',
SettingValue(types.List(), "http://www.duckduckgo.com"),
SettingValue(types.List(), 'http://www.duckduckgo.com'),
"The default page(s) to open at the start, separated with commas."),
('auto_search',
SettingValue(types.AutoSearch(), "naive"),
SettingValue(types.AutoSearch(), 'naive'),
"Whether to start a search when something else than an URL is "
"entered."),
('zoomlevels',
SettingValue(types.PercList(minval=0),
"25%,33%,50%,67%,75%,90%,100%,110%,125%,150%,175%,200%,"
"250%,300%,400%,500%"),
'25%,33%,50%,67%,75%,90%,100%,110%,125%,150%,175%,200%,'
'250%,300%,400%,500%'),
"The available zoom levels, separated by commas."),
('defaultzoom',
SettingValue(types.ZoomPerc(), "100%"),
SettingValue(types.ZoomPerc(), '100%'),
"The default zoom level."),
('autosave',
SettingValue(types.Bool(), "true"),
SettingValue(types.Bool(), 'true'),
"Whether to save the config automatically on quit."),
('cmd_histlen',
SettingValue(types.Int(minval=-1), "100"),
SettingValue(types.Int(minval=-1), '100'),
"How many commands to save in the history. 0: no history / -1: "
"unlimited"),
('background_tabs',
SettingValue(types.Bool(), "false"),
SettingValue(types.Bool(), 'false'),
"Whether to open new tabs (middleclick/ctrl+click) in background"),
('cmd_timeout',
SettingValue(types.Int(minval=0), "500"),
SettingValue(types.Int(minval=0), '500'),
"Timeout for ambiguous keybindings."),
('insert_mode_on_plugins',
SettingValue(types.Bool(), "true"),
SettingValue(types.Bool(), 'true'),
"Whether to switch to insert mode when clicking flash and other "
"plugins."),
('auto_insert_mode',
SettingValue(types.Bool(), "true"),
SettingValue(types.Bool(), 'true'),
"Whether to automatically enter insert mode if an editable element "
"is focused after page load."),
('forward_unbound_keys',
SettingValue(types.Bool(), "false"),
SettingValue(types.Bool(), 'false'),
"Whether to forward unbound keys to the website in normal mode."),
)),
('tabbar', sect.KeyValue(
('movable',
SettingValue(types.Bool(), "true"),
SettingValue(types.Bool(), 'true'),
"Whether tabs should be movable."),
('closebuttons',
SettingValue(types.Bool(), "false"),
SettingValue(types.Bool(), 'false'),
"Whether tabs should have close-buttons."),
('scrollbuttons',
SettingValue(types.Bool(), "true"),
SettingValue(types.Bool(), 'true'),
"Whether there should be scroll buttons if there are too many tabs."),
('position',
SettingValue(types.Position(), "north"),
SettingValue(types.Position(), 'north'),
"The position of the tab bar."),
('select_on_remove',
SettingValue(types.SelectOnRemove(), "previous"),
SettingValue(types.SelectOnRemove(), 'previous'),
"Which tab to select when the focused tab is removed."),
('last_close',
SettingValue(types.LastClose(), "ignore"),
SettingValue(types.LastClose(), 'ignore'),
"Behaviour when the last tab is closed."),
('wrap',
SettingValue(types.Bool(), "true"),
SettingValue(types.Bool(), 'true'),
"Whether to wrap when changing tabs."),
)),
('webkit', sect.KeyValue(
('auto_load_images',
SettingValue(types.Bool(), "true"),
SettingValue(types.Bool(), 'true'),
"Specifies whether images are automatically loaded in web pages."),
('dns_prefetch_enabled',
SettingValue(types.Bool(), "false"),
SettingValue(types.Bool(), 'false'),
"Specifies whether QtWebkit will try to pre-fetch DNS entries to "
"speed up browsing."),
('javascript_enabled',
SettingValue(types.Bool(), "true"),
SettingValue(types.Bool(), 'true'),
"Enables or disables the running of JavaScript programs."),
#('java_enabled',
# SettingValue(types.Bool(), "true"),
# SettingValue(types.Bool(), 'true'),
# "Enables or disables Java applets. Currently Java applets are "
# "not supported"),
('plugins_enabled',
SettingValue(types.Bool(), "false"),
SettingValue(types.Bool(), 'false'),
"Enables or disables plugins in Web pages"),
('private_browsing_enabled',
SettingValue(types.Bool(), "false"),
SettingValue(types.Bool(), 'false'),
"Private browsing prevents WebKit from recording visited pages in "
"the history and storing web page icons."),
('javascript_can_open_windows',
SettingValue(types.Bool(), "false"),
SettingValue(types.Bool(), 'false'),
"Specifies whether JavaScript programs can open new windows."),
('javascript_can_close_windows',
SettingValue(types.Bool(), "false"),
SettingValue(types.Bool(), 'false'),
"Specifies whether JavaScript programs can close windows."),
('javascript_can_access_clipboard',
SettingValue(types.Bool(), "false"),
SettingValue(types.Bool(), 'false'),
"Specifies whether JavaScript programs can read or write to the "
"clipboard."),
('developer_extras_enabled',
SettingValue(types.Bool(), "false"),
SettingValue(types.Bool(), 'false'),
"Enables extra tools for Web developers (e.g. webinspector)"),
('spatial_navigation_enabled',
SettingValue(types.Bool(), "false"),
SettingValue(types.Bool(), 'false'),
"Enables or disables the Spatial Navigation feature, which consists "
"in the ability to navigate between focusable elements in a Web "
"page, such as hyperlinks and form controls, by using Left, Right, "
"Up and Down arrow keys."),
('links_included_in_focus_chain',
SettingValue(types.Bool(), "true"),
SettingValue(types.Bool(), 'true'),
"Specifies whether hyperlinks should be included in the keyboard "
"focus chain."),
('zoom_text_only',
SettingValue(types.Bool(), "false"),
SettingValue(types.Bool(), 'false'),
"Specifies whether the zoom factor on a frame applies only to the "
"text or to all content."),
('print_element_backgrounds',
SettingValue(types.Bool(), "true"),
SettingValue(types.Bool(), 'true'),
"Specifies whether the background color and images are also drawn "
"when the page is printed. "),
('offline_storage_database_enabled',
SettingValue(types.Bool(), "false"),
SettingValue(types.Bool(), 'false'),
"Specifies whether support for the HTML 5 offline storage feature is "
"enabled or not. "),
('offline_web_application_storage_enabled',
SettingValue(types.Bool(), "false"),
SettingValue(types.Bool(), 'false'),
"Specifies whether support for the HTML 5 web application cache "
"feature is enabled or not. "),
('local_storage_enabled',
SettingValue(types.Bool(), "false"),
SettingValue(types.Bool(), 'false'),
"Specifies whether support for the HTML 5 local storage feature is "
"enabled or not."),
('local_content_can_access_remote_urls',
SettingValue(types.Bool(), "false"),
SettingValue(types.Bool(), 'false'),
"Specifies whether locally loaded documents are allowed to access "
"remote urls."),
('local_content_can_access_file_urls',
SettingValue(types.Bool(), "true"),
SettingValue(types.Bool(), 'true'),
"Specifies whether locally loaded documents are allowed to access "
"other local urls."),
('xss_auditing_enabled',
SettingValue(types.Bool(), "false"),
SettingValue(types.Bool(), 'false'),
"Specifies whether load requests should be monitored for cross-site "
"scripting attempts. Suspicious scripts will be blocked and reported "
"in the inspector's JavaScript console. Enabling this feature might "
"have an impact on performance."),
#('accelerated_compositing_enabled',
# SettingValue(types.Bool(), "true"),
# SettingValue(types.Bool(), 'true'),
# "This feature, when used in conjunction with QGraphicsWebView, "
# "accelerates animations of web content. CSS animations of the "
# "transform and opacity properties will be rendered by composing the "
# "cached content of the animated elements. "),
#('tiled_backing_store_enabled',
# SettingValue(types.Bool(), "false"),
# SettingValue(types.Bool(), 'false'),
# "This setting enables the tiled backing store feature for a "
# "QGraphicsWebView. With the tiled backing store enabled, the web "
# "page contents in and around the current visible area is "
@ -355,27 +355,27 @@ DATA = OrderedDict([
# "Enabling the feature increases memory consuption."),
('frame_flattening_enabled',
SettingValue(types.Bool(), "false"),
SettingValue(types.Bool(), 'false'),
"With this setting each subframe is expanded to its contents. This "
"will flatten all the frames to become one scrollable "
"page."),
('site_specific_quirks_enabled',
SettingValue(types.Bool(), "true"),
SettingValue(types.Bool(), 'true'),
"This setting enables WebKit's workaround for broken sites."),
)),
('hints', sect.KeyValue(
('border',
SettingValue(types.String(), "1px solid #E3BE23"),
SettingValue(types.String(), '1px solid #E3BE23'),
"CSS border value for hints."),
('opacity',
SettingValue(types.Float(minval=0.0, maxval=1.0), "0.7"),
SettingValue(types.Float(minval=0.0, maxval=1.0), '0.7'),
"Opacity for hints."),
('chars',
SettingValue(types.String(minlen=2), "asdfghjkl"),
SettingValue(types.String(minlen=2), 'asdfghjkl'),
"Chars used for hint strings."),
)),
@ -484,121 +484,121 @@ DATA = OrderedDict([
('colors', sect.KeyValue(
('completion.fg',
SettingValue(types.Color(), "#333333"),
SettingValue(types.Color(), '#333333'),
"Text color of the completion widget."),
('completion.item.bg',
SettingValue(types.Color(), "white"),
SettingValue(types.Color(), 'white'),
"Background color of completion widget items."),
('completion.category.bg',
SettingValue(types.Color(), "qlineargradient(x1:0, y1:0, x2:0, y2:1, "
"stop:0 #e4e4e4, stop:1 #dbdbdb)"),
SettingValue(types.Color(), 'qlineargradient(x1:0, y1:0, x2:0, y2:1, '
'stop:0 #e4e4e4, stop:1 #dbdbdb)'),
"Background color of the completion widget category headers."),
('completion.category.border.top',
SettingValue(types.Color(), "#808080"),
SettingValue(types.Color(), '#808080'),
"Top border color of the completion widget category headers."),
('completion.category.border.bottom',
SettingValue(types.Color(), "#bbbbbb"),
SettingValue(types.Color(), '#bbbbbb'),
"Bottom border color of the completion widget category headers."),
('completion.item.selected.fg',
SettingValue(types.Color(), "#333333"),
SettingValue(types.Color(), '#333333'),
"Foreground color of the selected completion item."),
('completion.item.selected.bg',
SettingValue(types.Color(), "#ffec8b"),
SettingValue(types.Color(), '#ffec8b'),
"Background color of the selected completion item."),
('completion.item.selected.border.top',
SettingValue(types.Color(), "#f2f2c0"),
SettingValue(types.Color(), '#f2f2c0'),
"Top border color of the completion widget category headers."),
('completion.item.selected.border.bottom',
SettingValue(types.Color(), "#ffec8b"),
SettingValue(types.Color(), '#ffec8b'),
"Bottom border color of the selected completion item."),
('completion.match.fg',
SettingValue(types.Color(), "red"),
SettingValue(types.Color(), 'red'),
"Foreground color of the matched text in the completion."),
('statusbar.bg',
SettingValue(types.Color(), "black"),
SettingValue(types.Color(), 'black'),
"Foreground color of the statusbar."),
('statusbar.fg',
SettingValue(types.Color(), "white"),
SettingValue(types.Color(), 'white'),
"Foreground color of the statusbar."),
('statusbar.bg.error',
SettingValue(types.Color(), "red"),
SettingValue(types.Color(), 'red'),
"Background color of the statusbar if there was an error."),
('statusbar.fg.error',
SettingValue(types.Color(), "${statusbar.fg}"),
SettingValue(types.Color(), '${statusbar.fg}'),
"Foreground color of the statusbar if there was an error."),
('statusbar.progress.bg',
SettingValue(types.Color(), "white"),
SettingValue(types.Color(), 'white'),
"Background color of the progress bar."),
('statusbar.url.fg',
SettingValue(types.Color(), "${statusbar.fg}"),
SettingValue(types.Color(), '${statusbar.fg}'),
"Default foreground color of the URL in the statusbar."),
('statusbar.url.fg.success',
SettingValue(types.Color(), "lime"),
SettingValue(types.Color(), 'lime'),
"Foreground color of the URL in the statusbar on successful "
"load."),
('statusbar.url.fg.error',
SettingValue(types.Color(), "orange"),
SettingValue(types.Color(), 'orange'),
"Foreground color of the URL in the statusbar on error."),
('statusbar.url.fg.warn',
SettingValue(types.Color(), "yellow"),
SettingValue(types.Color(), 'yellow'),
"Foreground color of the URL in the statusbar when there's a "
"warning."),
('statusbar.url.fg.hover',
SettingValue(types.Color(), "aqua"),
SettingValue(types.Color(), 'aqua'),
"Foreground color of the URL in the statusbar for hovered "
"links."),
('tab.fg',
SettingValue(types.Color(), "white"),
SettingValue(types.Color(), 'white'),
"Foreground color of tabs."),
('tab.bg',
SettingValue(types.Color(), "grey"),
SettingValue(types.Color(), 'grey'),
"Background color of unselected tabs."),
('tab.bg.selected',
SettingValue(types.Color(), "black"),
SettingValue(types.Color(), 'black'),
"Background color of selected tabs."),
('tab.bg.bar',
SettingValue(types.Color(), "#555555"),
SettingValue(types.Color(), '#555555'),
"Background color of the tabbar."),
('tab.seperator',
SettingValue(types.Color(), "#555555"),
SettingValue(types.Color(), '#555555'),
"Color for the tab seperator."),
('hints.fg',
SettingValue(types.CssColor(), "black"),
SettingValue(types.CssColor(), 'black'),
"Font color for hints."),
('hints.fg.match',
SettingValue(types.CssColor(), "green"),
SettingValue(types.CssColor(), 'green'),
"Font color for the matched part of hints."),
('hints.bg',
SettingValue(types.CssColor(), "-webkit-gradient(linear, left top, "
"left bottom, color-stop(0%,#FFF785), "
"color-stop(100%,#FFC542))"),
SettingValue(types.CssColor(), '-webkit-gradient(linear, left top, '
'left bottom, color-stop(0%,#FFF785), '
'color-stop(100%,#FFC542))'),
"Background color for hints."),
)),
@ -611,19 +611,19 @@ DATA = OrderedDict([
"Default monospace fonts."),
('completion',
SettingValue(types.Font(), "8pt ${_monospace}"),
SettingValue(types.Font(), '8pt ${_monospace}'),
"Font used in the completion widget."),
('tabbar',
SettingValue(types.Font(), "8pt ${_monospace}"),
SettingValue(types.Font(), '8pt ${_monospace}'),
"Font used in the tabbar."),
('statusbar',
SettingValue(types.Font(), "8pt ${_monospace}"),
SettingValue(types.Font(), '8pt ${_monospace}'),
"Font used in the statusbar."),
('hints',
SettingValue(types.Font(), "bold 12px Monospace"),
SettingValue(types.Font(), 'bold 12px Monospace'),
"Font used for the hints."),
)),
])

View File

@ -132,7 +132,7 @@ class BaseKeyParser(QObject):
try:
cmdstr = self.special_bindings[modstr + keystr]
except KeyError:
logging.debug('No binding found for {}.'.format(modstr + keystr))
logging.debug("No binding found for {}.".format(modstr + keystr))
return False
self.execute(cmdstr, self.TYPE_SPECIAL)
return True
@ -150,10 +150,10 @@ class BaseKeyParser(QObject):
Return:
True if event has been handled, False otherwise.
"""
logging.debug('Got key: {} / text: "{}"'.format(e.key(), e.text()))
logging.debug("Got key: {} / text: '{}'".format(e.key(), e.text()))
txt = e.text().strip()
if not txt:
logging.debug('Ignoring, no text')
logging.debug("Ignoring, no text")
return False
self._stop_delayed_exec()
@ -179,10 +179,10 @@ class BaseKeyParser(QObject):
elif match == self.MATCH_AMBIGUOUS:
self._handle_ambiguous_match(binding, count)
elif match == self.MATCH_PARTIAL:
logging.debug('No match for "{}" (added {})'.format(
logging.debug("No match for \"{}\" (added {})".format(
self._keystring, txt))
elif match == self.MATCH_NONE:
logging.debug('Giving up with "{}", no matches'.format(
logging.debug("Giving up with \"{}\", no matches".format(
self._keystring))
self._keystring = ''
return False

View File

@ -52,7 +52,7 @@ class CommandKeyParser(BaseKeyParser):
except NoSuchCommandError:
pass
except ArgumentCountError:
logging.debug('Filling statusbar with partial command {}'.format(
logging.debug("Filling statusbar with partial command {}".format(
cmdstr))
message.set_cmd_text(':{} '.format(cmdstr))

View File

@ -213,7 +213,7 @@ class ModeManager(QObject):
not_modes=['normal'], hide=True)
def leave_current_mode(self):
"""Leave the mode we're currently in."""
if self.mode == "normal":
if self.mode == 'normal':
raise ValueError("Can't leave normal mode!")
self.leave(self.mode)

View File

@ -49,7 +49,7 @@ class BaseCompletionModel(QAbstractItemModel):
def __init__(self, parent=None):
super().__init__(parent)
self._id_map = {}
self._root = CompletionItem([""] * 2)
self._root = CompletionItem([''] * 2)
self._id_map[id(self._root)] = self._root
def _node(self, index):
@ -117,7 +117,7 @@ class BaseCompletionModel(QAbstractItemModel):
self._root.children.append(cat)
return cat
def new_item(self, cat, name, desc=""):
def new_item(self, cat, name, desc=''):
"""Add a new item to a category.
Args:

View File

@ -70,7 +70,7 @@ class History:
Args:
text: The preset text.
"""
logging.debug('Preset text: "{}"'.format(text))
logging.debug("Preset text: \"{}\"".format(text))
if text:
items = [e for e in self._history if e.startswith(text)]
else:

View File

@ -73,7 +73,7 @@ class SpecialNetworkReply(QNetworkReply):
self.setHeader(QNetworkRequest.ContentLengthHeader,
QByteArray.number(len(fileData)))
self.setAttribute(QNetworkRequest.HttpStatusCodeAttribute, 200)
self.setAttribute(QNetworkRequest.HttpReasonPhraseAttribute, "OK")
self.setAttribute(QNetworkRequest.HttpReasonPhraseAttribute, 'OK')
# For some reason, a segfault will be triggered if these lambdas aren't
# there. pylint: disable=unnecessary-lambda
QTimer.singleShot(0, lambda: self.metaDataChanged.emit())

View File

@ -87,7 +87,7 @@ class QuteSchemeHandler(SchemeHandler):
Return:
A QNetworkReply.
"""
logging.debug('request: {}'.format(request))
logging.debug("request: {}".format(request))
url = urlstring(request.url())
try:
handler = getattr(QuteHandlers, self._transform_url(url))
@ -95,7 +95,7 @@ class QuteSchemeHandler(SchemeHandler):
data = bytes()
else:
data = handler()
return SpecialNetworkReply(request, data, "text/html", self.parent())
return SpecialNetworkReply(request, data, 'text/html', self.parent())
class QuteHandlers:

View File

@ -105,5 +105,5 @@ class SignalCache(QObject):
def replay(self):
"""Replay all cached signals."""
for (signal, args) in self._signal_dict.values():
logging.debug('emitting {}'.format(dbg_signal(signal, args)))
logging.debug("emitting {}".format(dbg_signal(signal, args)))
signal.emit(*args)

View File

@ -39,7 +39,7 @@ def _get_search_url(txt):
Raise:
SearchEngineError if there is no template or no search term was found.
"""
logging.debug('Finding search engine for "{}"'.format(txt))
logging.debug("Finding search engine for '{}'".format(txt))
r = re.compile(r'(^|\s+)!(\w+)($|\s+)')
m = r.search(txt)
if m:
@ -50,11 +50,11 @@ def _get_search_url(txt):
raise SearchEngineError("Search engine {} not found!".format(
engine))
term = r.sub('', txt)
logging.debug('engine {}, term "{}"'.format(engine, term))
logging.debug("engine {}, term '{}'".format(engine, term))
else:
template = config.get('searchengines', 'DEFAULT')
term = txt
logging.debug('engine: default, term "{}"'.format(txt))
logging.debug("engine: default, term '{}'".format(txt))
if not term:
raise SearchEngineError("No search term given")
return QUrl.fromUserInput(template.format(urllib.parse.quote(term)))
@ -137,7 +137,7 @@ def fuzzy_url(url):
newurl = _get_search_url(urlstr)
except ValueError: # invalid search engine
newurl = QUrl.fromUserInput(urlstr)
logging.debug('Converting fuzzy term {} to url -> {}'.format(
logging.debug("Converting fuzzy term {} to url -> {}".format(
urlstr, urlstring(newurl)))
return newurl
@ -166,7 +166,7 @@ def is_url(url):
autosearch = config.get('general', 'auto_search')
logging.debug('Checking if "{}" is an URL (autosearch={}).'.format(
logging.debug("Checking if '{}' is an URL (autosearch={}).".format(
urlstr, autosearch))
if not autosearch:
@ -175,17 +175,17 @@ def is_url(url):
if ' ' in urlstr:
# An URL will never contain a space
logging.debug('Contains space -> no url')
logging.debug("Contains space -> no url")
return False
elif is_special_url(url):
# Special URLs are always URLs, even with autosearch=False
logging.debug('Is an special URL.')
logging.debug("Is an special URL.")
return True
elif autosearch == 'dns':
logging.debug('Checking via DNS')
logging.debug("Checking via DNS")
return _is_url_dns(QUrl.fromUserInput(urlstr))
elif autosearch == 'naive':
logging.debug('Checking via naive check')
logging.debug("Checking via naive check")
return _is_url_naive(url)
else:
raise ValueError("Invalid autosearch value")

View File

@ -85,11 +85,11 @@ def version():
gitver = _git_str()
lines = [
'qutebrowser v{}'.format(qutebrowser.__version__),
"qutebrowser v{}".format(qutebrowser.__version__),
]
if gitver is not None:
lines.append('Git commit: {}'.format(gitver))
lines.append("Git commit: {}".format(gitver))
lines += [
'',

View File

@ -181,7 +181,7 @@ class CompletionView(QTreeView):
completions = cmdutils.cmd_dict[parts[0]].completion
except KeyError:
return None
logging.debug('completions: {}'.format(completions))
logging.debug("completions: {}".format(completions))
if completions is None:
return None
try:

View File

@ -337,11 +337,11 @@ class TabbedBrowser(TabWidget):
Args:
text: The text to set.
"""
logging.debug('title changed to "{}"'.format(text))
logging.debug("title changed to '{}'".format(text))
if text:
self.setTabText(self.indexOf(self.sender()), text)
else:
logging.debug('ignoring title change')
logging.debug("ignoring title change")
@pyqtSlot(str)
def on_mode_left(self, mode):

View File

@ -51,18 +51,18 @@ class CrashDialog(QDialog):
"""
super().__init__()
self.setFixedSize(500, 350)
self.setWindowTitle('Whoops!')
self.setWindowTitle("Whoops!")
self.setModal(True)
self._vbox = QVBoxLayout(self)
self._lbl = QLabel()
text = ('Argh! qutebrowser crashed unexpectedly.<br/>'
'Please review the info below to remove sensitive data and '
'then submit it to <a href="mailto:crash@qutebrowser.org">'
'crash@qutebrowser.org</a>.<br/><br/>')
text = ("Argh! qutebrowser crashed unexpectedly.<br/>"
"Please review the info below to remove sensitive data and "
"then submit it to <a href='mailto:crash@qutebrowser.org'>"
"crash@qutebrowser.org</a>.<br/><br/>")
if pages:
text += ('You can click "Restore tabs" to attempt to reopen your '
'open tabs.')
text += ("You can click \"Restore tabs\" to attempt to reopen "
"your open tabs.")
self._lbl.setText(text)
self._lbl.setWordWrap(True)
self._vbox.addWidget(self._lbl)
@ -75,12 +75,12 @@ class CrashDialog(QDialog):
self._hbox = QHBoxLayout()
self._hbox.addStretch()
self._btn_quit = QPushButton()
self._btn_quit.setText('Quit')
self._btn_quit.setText("Quit")
self._btn_quit.clicked.connect(self.reject)
self._hbox.addWidget(self._btn_quit)
if pages:
self._btn_restore = QPushButton()
self._btn_restore.setText('Restore tabs')
self._btn_restore.setText("Restore tabs")
self._btn_restore.clicked.connect(self.accept)
self._btn_restore.setDefault(True)
self._hbox.addWidget(self._btn_restore)
@ -99,14 +99,14 @@ class CrashDialog(QDialog):
The string to display.
"""
outputs = [
('Version info', version()),
('Exception', ''.join(traceback.format_exception(*exc))),
('Open Pages', '\n'.join(pages)),
('Command history', '\n'.join(cmdhist)),
('Commandline args', ' '.join(sys.argv[1:])),
("Version info", version()),
("Exception", ''.join(traceback.format_exception(*exc))),
("Open Pages", '\n'.join(pages)),
("Command history", '\n'.join(cmdhist)),
("Commandline args", ' '.join(sys.argv[1:])),
]
try:
outputs.append(('Config', config.instance.dump_userconfig()))
outputs.append(("Config", config.instance.dump_userconfig()))
except AttributeError:
pass
chunks = []

View File

@ -72,7 +72,7 @@ class WebView(QWebView):
super().__init__(parent)
self._scroll_pos = (-1, -1)
self._shutdown_callback = None
self._open_target = "normal"
self._open_target = 'normal'
self._force_open_target = None
self._destroyed = {}
self._zoom = None
@ -86,7 +86,7 @@ class WebView(QWebView):
self.page_.setLinkDelegationPolicy(QWebPage.DelegateAllLinks)
self.page_.linkHovered.connect(self.linkHovered)
self.linkClicked.connect(self.on_link_clicked)
self.loadStarted.connect(lambda: modeman.maybe_leave("insert"))
self.loadStarted.connect(lambda: modeman.maybe_leave('insert'))
self.loadFinished.connect(self.on_load_finished)
# FIXME find some way to hide scrollbars without setScrollBarPolicy
@ -132,12 +132,12 @@ class WebView(QWebView):
return True
if tag == 'object':
# Could be Flash/Java/..., could be image/audio/...
if not elem.hasAttribute("type"):
if not elem.hasAttribute('type'):
logging.debug("<object> without type clicked...")
return False
objtype = elem.attribute("type")
if (objtype.startswith("application/") or
elem.hasAttribute("classid")):
objtype = elem.attribute('type')
if (objtype.startswith('application/') or
elem.hasAttribute('classid')):
# Let's hope flash/java stuff has an application/* mimetype OR
# at least a classid attribute. Oh, and let's home images/...
# DON"T have a classid attribute. HTML sucks.
@ -162,7 +162,7 @@ class WebView(QWebView):
except urlutils.SearchEngineError as e:
message.error(str(e))
return
logging.debug('New title: {}'.format(urlutils.urlstring(u)))
logging.debug("New title: {}".format(urlutils.urlstring(u)))
self.titleChanged.emit(urlutils.urlstring(u))
self.urlChanged.emit(urlutils.qurl(u))
return self.load(u)
@ -226,9 +226,9 @@ class WebView(QWebView):
Emit:
open_tab: Emitted if window should be opened in a new tab.
"""
if self._open_target == "tab":
if self._open_target == 'tab':
self.open_tab.emit(url, False)
elif self._open_target == "bgtab":
elif self._open_target == 'bgtab':
self.open_tab.emit(url, True)
else:
self.openurl(url)

View File

@ -123,17 +123,17 @@ def _check_file(fn):
with open(fn, 'rb') as f:
for line in f:
if b'\r\n' in line:
print('Found CRLF in {}'.format(fn))
print("Found CRLF in {}".format(fn))
return False
elif any(line.decode('UTF-8').startswith(c * 7) for c in "<>=|"):
print('Found conflict marker in {}'.format(fn))
print("Found conflict marker in {}".format(fn))
return False
elif any([line.decode('UTF-8').rstrip('\r\n').endswith(c)
for c in " \t"]):
print('Found whitespace at line ending in {}'.format(fn))
print("Found whitespace at line ending in {}".format(fn))
return False
elif b' \t' in line or b'\t ' in line:
print('Found tab-space mix in {}'.format(fn))
print("Found tab-space mix in {}".format(fn))
return False
return True
@ -195,7 +195,7 @@ for checker in ['pylint', 'flake8']:
run(checker, _get_args(checker))
check_line()
print('Exit status values:')
print("Exit status values:")
for (k, v) in status.items():
print(' {} - {}'.format(k, v))