We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Rapid firing for completion
The completion should have some way to spawn a completed command without closing the completion - for example, using <kbd>Shift-Enter</kbd> or middle-click.


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `qutebrowser/mainwindow/statusbar/command.py`
Content:
```
1 # vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
2 
3 # Copyright 2014-2017 Florian Bruhin (The Compiler) <mail@qutebrowser.org>
4 #
5 # This file is part of qutebrowser.
6 #
7 # qutebrowser is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # qutebrowser is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with qutebrowser.  If not, see <http://www.gnu.org/licenses/>.
19 
20 """The commandline in the statusbar."""
21 
22 from PyQt5.QtCore import pyqtSignal, pyqtSlot, Qt, QSize
23 from PyQt5.QtWidgets import QSizePolicy
24 
25 from qutebrowser.keyinput import modeman, modeparsers
26 from qutebrowser.commands import cmdexc, cmdutils
27 from qutebrowser.misc import cmdhistory, editor
28 from qutebrowser.misc import miscwidgets as misc
29 from qutebrowser.utils import usertypes, log, objreg, message
30 from qutebrowser.config import config
31 
32 
33 class Command(misc.MinimalLineEditMixin, misc.CommandLineEdit):
34 
35     """The commandline part of the statusbar.
36 
37     Attributes:
38         _win_id: The window ID this widget is associated with.
39 
40     Signals:
41         got_cmd: Emitted when a command is triggered by the user.
42                  arg: The command string and also potentially the count.
43         clear_completion_selection: Emitted before the completion widget is
44                                     hidden.
45         hide_completion: Emitted when the completion widget should be hidden.
46         update_completion: Emitted when the completion should be shown/updated.
47         show_cmd: Emitted when command input should be shown.
48         hide_cmd: Emitted when command input can be hidden.
49     """
50 
51     got_cmd = pyqtSignal([str], [str, int])
52     clear_completion_selection = pyqtSignal()
53     hide_completion = pyqtSignal()
54     update_completion = pyqtSignal()
55     show_cmd = pyqtSignal()
56     hide_cmd = pyqtSignal()
57 
58     def __init__(self, *, win_id, private, parent=None):
59         misc.CommandLineEdit.__init__(self, parent=parent)
60         misc.MinimalLineEditMixin.__init__(self)
61         self._win_id = win_id
62         if not private:
63             command_history = objreg.get('command-history')
64             self.history.history = command_history.data
65             self.history.changed.connect(command_history.changed)
66         self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Ignored)
67         self.cursorPositionChanged.connect(self.update_completion)
68         self.textChanged.connect(self.update_completion)
69         self.textChanged.connect(self.updateGeometry)
70         self.textChanged.connect(self._incremental_search)
71 
72     def prefix(self):
73         """Get the currently entered command prefix."""
74         text = self.text()
75         if not text:
76             return ''
77         elif text[0] in modeparsers.STARTCHARS:
78             return text[0]
79         else:
80             return ''
81 
82     def set_cmd_text(self, text):
83         """Preset the statusbar to some text.
84 
85         Args:
86             text: The text to set as string.
87         """
88         self.setText(text)
89         log.modes.debug("Setting command text, focusing {!r}".format(self))
90         modeman.enter(self._win_id, usertypes.KeyMode.command, 'cmd focus')
91         self.setFocus()
92         self.show_cmd.emit()
93 
94     @cmdutils.register(instance='status-command', name='set-cmd-text',
95                        scope='window', maxsplit=0)
96     @cmdutils.argument('count', count=True)
97     def set_cmd_text_command(self, text, count=None, space=False, append=False,
98                              run_on_count=False):
99         """Preset the statusbar to some text.
100 
101         //
102 
103         Wrapper for set_cmd_text to check the arguments and allow multiple
104         strings which will get joined.
105 
106         Args:
107             text: The commandline to set.
108             count: The count if given.
109             space: If given, a space is added to the end.
110             append: If given, the text is appended to the current text.
111             run_on_count: If given with a count, the command is run with the
112                           given count rather than setting the command text.
113         """
114         if space:
115             text += ' '
116         if append:
117             if not self.text():
118                 raise cmdexc.CommandError("No current text!")
119             text = self.text() + text
120 
121         if not text or text[0] not in modeparsers.STARTCHARS:
122             raise cmdexc.CommandError(
123                 "Invalid command text '{}'.".format(text))
124         if run_on_count and count is not None:
125             self.got_cmd[str, int].emit(text, count)
126         else:
127             self.set_cmd_text(text)
128 
129     @cmdutils.register(instance='status-command',
130                        modes=[usertypes.KeyMode.command], scope='window')
131     def command_history_prev(self):
132         """Go back in the commandline history."""
133         try:
134             if not self.history.is_browsing():
135                 item = self.history.start(self.text().strip())
136             else:
137                 item = self.history.previtem()
138         except (cmdhistory.HistoryEmptyError,
139                 cmdhistory.HistoryEndReachedError):
140             return
141         if item:
142             self.set_cmd_text(item)
143 
144     @cmdutils.register(instance='status-command',
145                        modes=[usertypes.KeyMode.command], scope='window')
146     def command_history_next(self):
147         """Go forward in the commandline history."""
148         if not self.history.is_browsing():
149             return
150         try:
151             item = self.history.nextitem()
152         except cmdhistory.HistoryEndReachedError:
153             return
154         if item:
155             self.set_cmd_text(item)
156 
157     @cmdutils.register(instance='status-command',
158                        modes=[usertypes.KeyMode.command], scope='window')
159     def command_accept(self):
160         """Execute the command currently in the commandline."""
161         prefixes = {
162             ':': '',
163             '/': 'search -- ',
164             '?': 'search -r -- ',
165         }
166         text = self.text()
167         self.history.append(text)
168         modeman.leave(self._win_id, usertypes.KeyMode.command, 'cmd accept')
169         self.got_cmd[str].emit(prefixes[text[0]] + text[1:])
170 
171     @cmdutils.register(instance='status-command', scope='window')
172     def edit_command(self, run=False):
173         """Open an editor to modify the current command.
174 
175         Args:
176             run: Run the command if the editor exits successfully.
177         """
178         ed = editor.ExternalEditor(parent=self)
179 
180         def callback(text):
181             """Set the commandline to the edited text."""
182             if not text or text[0] not in modeparsers.STARTCHARS:
183                 message.error('command must start with one of {}'
184                               .format(modeparsers.STARTCHARS))
185                 return
186             self.set_cmd_text(text)
187             if run:
188                 self.command_accept()
189 
190         ed.editing_finished.connect(callback)
191         ed.edit(self.text())
192 
193     @pyqtSlot(usertypes.KeyMode)
194     def on_mode_left(self, mode):
195         """Clear up when command mode was left.
196 
197         - Clear the statusbar text if it's explicitly unfocused.
198         - Clear completion selection
199         - Hide completion
200 
201         Args:
202             mode: The mode which was left.
203         """
204         if mode == usertypes.KeyMode.command:
205             self.setText('')
206             self.history.stop()
207             self.hide_cmd.emit()
208             self.clear_completion_selection.emit()
209             self.hide_completion.emit()
210 
211     def setText(self, text):
212         """Extend setText to set prefix and make sure the prompt is ok."""
213         if not text:
214             pass
215         elif text[0] in modeparsers.STARTCHARS:
216             super().set_prompt(text[0])
217         else:
218             raise AssertionError("setText got called with invalid text "
219                                  "'{}'!".format(text))
220         super().setText(text)
221 
222     def keyPressEvent(self, e):
223         """Override keyPressEvent to ignore Return key presses.
224 
225         If this widget is focused, we are in passthrough key mode, and
226         Enter/Shift+Enter/etc. will cause QLineEdit to think it's finished
227         without command_accept to be called.
228         """
229         if e.key() == Qt.Key_Return:
230             e.ignore()
231             return
232         else:
233             super().keyPressEvent(e)
234 
235     def sizeHint(self):
236         """Dynamically calculate the needed size."""
237         height = super().sizeHint().height()
238         text = self.text()
239         if not text:
240             text = 'x'
241         width = self.fontMetrics().width(text)
242         return QSize(width, height)
243 
244     @pyqtSlot(str)
245     def _incremental_search(self, text):
246         if not config.val.search.incremental:
247             return
248 
249         search_prefixes = {
250             '/': 'search -- ',
251             '?': 'search -r -- ',
252         }
253 
254         if self.prefix() in ['/', '?']:
255             self.got_cmd[str].emit(search_prefixes[text[0]] + text[1:])
256
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/qutebrowser/mainwindow/statusbar/command.py b/qutebrowser/mainwindow/statusbar/command.py
--- a/qutebrowser/mainwindow/statusbar/command.py
+++ b/qutebrowser/mainwindow/statusbar/command.py
@@ -156,8 +156,12 @@
 
     @cmdutils.register(instance='status-command',
                        modes=[usertypes.KeyMode.command], scope='window')
-    def command_accept(self):
-        """Execute the command currently in the commandline."""
+    def command_accept(self, rapid=False):
+        """Execute the command currently in the commandline.
+
+        Args:
+            rapid: Run the command without closing or clearing the command bar.
+        """
         prefixes = {
             ':': '',
             '/': 'search -- ',
@@ -165,7 +169,9 @@
         }
         text = self.text()
         self.history.append(text)
-        modeman.leave(self._win_id, usertypes.KeyMode.command, 'cmd accept')
+        if not rapid:
+            modeman.leave(self._win_id, usertypes.KeyMode.command,
+                          'cmd accept')
         self.got_cmd[str].emit(prefixes[text[0]] + text[1:])
 
     @cmdutils.register(instance='status-command', scope='window')

{"golden_diff": "diff --git a/qutebrowser/mainwindow/statusbar/command.py b/qutebrowser/mainwindow/statusbar/command.py\n--- a/qutebrowser/mainwindow/statusbar/command.py\n+++ b/qutebrowser/mainwindow/statusbar/command.py\n@@ -156,8 +156,12 @@\n \n     @cmdutils.register(instance='status-command',\n                        modes=[usertypes.KeyMode.command], scope='window')\n-    def command_accept(self):\n-        \"\"\"Execute the command currently in the commandline.\"\"\"\n+    def command_accept(self, rapid=False):\n+        \"\"\"Execute the command currently in the commandline.\n+\n+        Args:\n+            rapid: Run the command without closing or clearing the command bar.\n+        \"\"\"\n         prefixes = {\n             ':': '',\n             '/': 'search -- ',\n@@ -165,7 +169,9 @@\n         }\n         text = self.text()\n         self.history.append(text)\n-        modeman.leave(self._win_id, usertypes.KeyMode.command, 'cmd accept')\n+        if not rapid:\n+            modeman.leave(self._win_id, usertypes.KeyMode.command,\n+                          'cmd accept')\n         self.got_cmd[str].emit(prefixes[text[0]] + text[1:])\n \n     @cmdutils.register(instance='status-command', scope='window')\n", "issue": "Rapid firing for completion\nThe completion should have some way to spawn a completed command without closing the completion - for example, using <kbd>Shift-Enter</kbd> or middle-click.\n\n", "before_files": [{"content": "# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:\n\n# Copyright 2014-2017 Florian Bruhin (The Compiler) <mail@qutebrowser.org>\n#\n# This file is part of qutebrowser.\n#\n# qutebrowser is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# qutebrowser is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with qutebrowser.  If not, see <http://www.gnu.org/licenses/>.\n\n\"\"\"The commandline in the statusbar.\"\"\"\n\nfrom PyQt5.QtCore import pyqtSignal, pyqtSlot, Qt, QSize\nfrom PyQt5.QtWidgets import QSizePolicy\n\nfrom qutebrowser.keyinput import modeman, modeparsers\nfrom qutebrowser.commands import cmdexc, cmdutils\nfrom qutebrowser.misc import cmdhistory, editor\nfrom qutebrowser.misc import miscwidgets as misc\nfrom qutebrowser.utils import usertypes, log, objreg, message\nfrom qutebrowser.config import config\n\n\nclass Command(misc.MinimalLineEditMixin, misc.CommandLineEdit):\n\n    \"\"\"The commandline part of the statusbar.\n\n    Attributes:\n        _win_id: The window ID this widget is associated with.\n\n    Signals:\n        got_cmd: Emitted when a command is triggered by the user.\n                 arg: The command string and also potentially the count.\n        clear_completion_selection: Emitted before the completion widget is\n                                    hidden.\n        hide_completion: Emitted when the completion widget should be hidden.\n        update_completion: Emitted when the completion should be shown/updated.\n        show_cmd: Emitted when command input should be shown.\n        hide_cmd: Emitted when command input can be hidden.\n    \"\"\"\n\n    got_cmd = pyqtSignal([str], [str, int])\n    clear_completion_selection = pyqtSignal()\n    hide_completion = pyqtSignal()\n    update_completion = pyqtSignal()\n    show_cmd = pyqtSignal()\n    hide_cmd = pyqtSignal()\n\n    def __init__(self, *, win_id, private, parent=None):\n        misc.CommandLineEdit.__init__(self, parent=parent)\n        misc.MinimalLineEditMixin.__init__(self)\n        self._win_id = win_id\n        if not private:\n            command_history = objreg.get('command-history')\n            self.history.history = command_history.data\n            self.history.changed.connect(command_history.changed)\n        self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Ignored)\n        self.cursorPositionChanged.connect(self.update_completion)\n        self.textChanged.connect(self.update_completion)\n        self.textChanged.connect(self.updateGeometry)\n        self.textChanged.connect(self._incremental_search)\n\n    def prefix(self):\n        \"\"\"Get the currently entered command prefix.\"\"\"\n        text = self.text()\n        if not text:\n            return ''\n        elif text[0] in modeparsers.STARTCHARS:\n            return text[0]\n        else:\n            return ''\n\n    def set_cmd_text(self, text):\n        \"\"\"Preset the statusbar to some text.\n\n        Args:\n            text: The text to set as string.\n        \"\"\"\n        self.setText(text)\n        log.modes.debug(\"Setting command text, focusing {!r}\".format(self))\n        modeman.enter(self._win_id, usertypes.KeyMode.command, 'cmd focus')\n        self.setFocus()\n        self.show_cmd.emit()\n\n    @cmdutils.register(instance='status-command', name='set-cmd-text',\n                       scope='window', maxsplit=0)\n    @cmdutils.argument('count', count=True)\n    def set_cmd_text_command(self, text, count=None, space=False, append=False,\n                             run_on_count=False):\n        \"\"\"Preset the statusbar to some text.\n\n        //\n\n        Wrapper for set_cmd_text to check the arguments and allow multiple\n        strings which will get joined.\n\n        Args:\n            text: The commandline to set.\n            count: The count if given.\n            space: If given, a space is added to the end.\n            append: If given, the text is appended to the current text.\n            run_on_count: If given with a count, the command is run with the\n                          given count rather than setting the command text.\n        \"\"\"\n        if space:\n            text += ' '\n        if append:\n            if not self.text():\n                raise cmdexc.CommandError(\"No current text!\")\n            text = self.text() + text\n\n        if not text or text[0] not in modeparsers.STARTCHARS:\n            raise cmdexc.CommandError(\n                \"Invalid command text '{}'.\".format(text))\n        if run_on_count and count is not None:\n            self.got_cmd[str, int].emit(text, count)\n        else:\n            self.set_cmd_text(text)\n\n    @cmdutils.register(instance='status-command',\n                       modes=[usertypes.KeyMode.command], scope='window')\n    def command_history_prev(self):\n        \"\"\"Go back in the commandline history.\"\"\"\n        try:\n            if not self.history.is_browsing():\n                item = self.history.start(self.text().strip())\n            else:\n                item = self.history.previtem()\n        except (cmdhistory.HistoryEmptyError,\n                cmdhistory.HistoryEndReachedError):\n            return\n        if item:\n            self.set_cmd_text(item)\n\n    @cmdutils.register(instance='status-command',\n                       modes=[usertypes.KeyMode.command], scope='window')\n    def command_history_next(self):\n        \"\"\"Go forward in the commandline history.\"\"\"\n        if not self.history.is_browsing():\n            return\n        try:\n            item = self.history.nextitem()\n        except cmdhistory.HistoryEndReachedError:\n            return\n        if item:\n            self.set_cmd_text(item)\n\n    @cmdutils.register(instance='status-command',\n                       modes=[usertypes.KeyMode.command], scope='window')\n    def command_accept(self):\n        \"\"\"Execute the command currently in the commandline.\"\"\"\n        prefixes = {\n            ':': '',\n            '/': 'search -- ',\n            '?': 'search -r -- ',\n        }\n        text = self.text()\n        self.history.append(text)\n        modeman.leave(self._win_id, usertypes.KeyMode.command, 'cmd accept')\n        self.got_cmd[str].emit(prefixes[text[0]] + text[1:])\n\n    @cmdutils.register(instance='status-command', scope='window')\n    def edit_command(self, run=False):\n        \"\"\"Open an editor to modify the current command.\n\n        Args:\n            run: Run the command if the editor exits successfully.\n        \"\"\"\n        ed = editor.ExternalEditor(parent=self)\n\n        def callback(text):\n            \"\"\"Set the commandline to the edited text.\"\"\"\n            if not text or text[0] not in modeparsers.STARTCHARS:\n                message.error('command must start with one of {}'\n                              .format(modeparsers.STARTCHARS))\n                return\n            self.set_cmd_text(text)\n            if run:\n                self.command_accept()\n\n        ed.editing_finished.connect(callback)\n        ed.edit(self.text())\n\n    @pyqtSlot(usertypes.KeyMode)\n    def on_mode_left(self, mode):\n        \"\"\"Clear up when command mode was left.\n\n        - Clear the statusbar text if it's explicitly unfocused.\n        - Clear completion selection\n        - Hide completion\n\n        Args:\n            mode: The mode which was left.\n        \"\"\"\n        if mode == usertypes.KeyMode.command:\n            self.setText('')\n            self.history.stop()\n            self.hide_cmd.emit()\n            self.clear_completion_selection.emit()\n            self.hide_completion.emit()\n\n    def setText(self, text):\n        \"\"\"Extend setText to set prefix and make sure the prompt is ok.\"\"\"\n        if not text:\n            pass\n        elif text[0] in modeparsers.STARTCHARS:\n            super().set_prompt(text[0])\n        else:\n            raise AssertionError(\"setText got called with invalid text \"\n                                 \"'{}'!\".format(text))\n        super().setText(text)\n\n    def keyPressEvent(self, e):\n        \"\"\"Override keyPressEvent to ignore Return key presses.\n\n        If this widget is focused, we are in passthrough key mode, and\n        Enter/Shift+Enter/etc. will cause QLineEdit to think it's finished\n        without command_accept to be called.\n        \"\"\"\n        if e.key() == Qt.Key_Return:\n            e.ignore()\n            return\n        else:\n            super().keyPressEvent(e)\n\n    def sizeHint(self):\n        \"\"\"Dynamically calculate the needed size.\"\"\"\n        height = super().sizeHint().height()\n        text = self.text()\n        if not text:\n            text = 'x'\n        width = self.fontMetrics().width(text)\n        return QSize(width, height)\n\n    @pyqtSlot(str)\n    def _incremental_search(self, text):\n        if not config.val.search.incremental:\n            return\n\n        search_prefixes = {\n            '/': 'search -- ',\n            '?': 'search -r -- ',\n        }\n\n        if self.prefix() in ['/', '?']:\n            self.got_cmd[str].emit(search_prefixes[text[0]] + text[1:])\n", "path": "qutebrowser/mainwindow/statusbar/command.py"}], "after_files": [{"content": "# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:\n\n# Copyright 2014-2017 Florian Bruhin (The Compiler) <mail@qutebrowser.org>\n#\n# This file is part of qutebrowser.\n#\n# qutebrowser is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# qutebrowser is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with qutebrowser.  If not, see <http://www.gnu.org/licenses/>.\n\n\"\"\"The commandline in the statusbar.\"\"\"\n\nfrom PyQt5.QtCore import pyqtSignal, pyqtSlot, Qt, QSize\nfrom PyQt5.QtWidgets import QSizePolicy\n\nfrom qutebrowser.keyinput import modeman, modeparsers\nfrom qutebrowser.commands import cmdexc, cmdutils\nfrom qutebrowser.misc import cmdhistory, editor\nfrom qutebrowser.misc import miscwidgets as misc\nfrom qutebrowser.utils import usertypes, log, objreg, message\nfrom qutebrowser.config import config\n\n\nclass Command(misc.MinimalLineEditMixin, misc.CommandLineEdit):\n\n    \"\"\"The commandline part of the statusbar.\n\n    Attributes:\n        _win_id: The window ID this widget is associated with.\n\n    Signals:\n        got_cmd: Emitted when a command is triggered by the user.\n                 arg: The command string and also potentially the count.\n        clear_completion_selection: Emitted before the completion widget is\n                                    hidden.\n        hide_completion: Emitted when the completion widget should be hidden.\n        update_completion: Emitted when the completion should be shown/updated.\n        show_cmd: Emitted when command input should be shown.\n        hide_cmd: Emitted when command input can be hidden.\n    \"\"\"\n\n    got_cmd = pyqtSignal([str], [str, int])\n    clear_completion_selection = pyqtSignal()\n    hide_completion = pyqtSignal()\n    update_completion = pyqtSignal()\n    show_cmd = pyqtSignal()\n    hide_cmd = pyqtSignal()\n\n    def __init__(self, *, win_id, private, parent=None):\n        misc.CommandLineEdit.__init__(self, parent=parent)\n        misc.MinimalLineEditMixin.__init__(self)\n        self._win_id = win_id\n        if not private:\n            command_history = objreg.get('command-history')\n            self.history.history = command_history.data\n            self.history.changed.connect(command_history.changed)\n        self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Ignored)\n        self.cursorPositionChanged.connect(self.update_completion)\n        self.textChanged.connect(self.update_completion)\n        self.textChanged.connect(self.updateGeometry)\n        self.textChanged.connect(self._incremental_search)\n\n    def prefix(self):\n        \"\"\"Get the currently entered command prefix.\"\"\"\n        text = self.text()\n        if not text:\n            return ''\n        elif text[0] in modeparsers.STARTCHARS:\n            return text[0]\n        else:\n            return ''\n\n    def set_cmd_text(self, text):\n        \"\"\"Preset the statusbar to some text.\n\n        Args:\n            text: The text to set as string.\n        \"\"\"\n        self.setText(text)\n        log.modes.debug(\"Setting command text, focusing {!r}\".format(self))\n        modeman.enter(self._win_id, usertypes.KeyMode.command, 'cmd focus')\n        self.setFocus()\n        self.show_cmd.emit()\n\n    @cmdutils.register(instance='status-command', name='set-cmd-text',\n                       scope='window', maxsplit=0)\n    @cmdutils.argument('count', count=True)\n    def set_cmd_text_command(self, text, count=None, space=False, append=False,\n                             run_on_count=False):\n        \"\"\"Preset the statusbar to some text.\n\n        //\n\n        Wrapper for set_cmd_text to check the arguments and allow multiple\n        strings which will get joined.\n\n        Args:\n            text: The commandline to set.\n            count: The count if given.\n            space: If given, a space is added to the end.\n            append: If given, the text is appended to the current text.\n            run_on_count: If given with a count, the command is run with the\n                          given count rather than setting the command text.\n        \"\"\"\n        if space:\n            text += ' '\n        if append:\n            if not self.text():\n                raise cmdexc.CommandError(\"No current text!\")\n            text = self.text() + text\n\n        if not text or text[0] not in modeparsers.STARTCHARS:\n            raise cmdexc.CommandError(\n                \"Invalid command text '{}'.\".format(text))\n        if run_on_count and count is not None:\n            self.got_cmd[str, int].emit(text, count)\n        else:\n            self.set_cmd_text(text)\n\n    @cmdutils.register(instance='status-command',\n                       modes=[usertypes.KeyMode.command], scope='window')\n    def command_history_prev(self):\n        \"\"\"Go back in the commandline history.\"\"\"\n        try:\n            if not self.history.is_browsing():\n                item = self.history.start(self.text().strip())\n            else:\n                item = self.history.previtem()\n        except (cmdhistory.HistoryEmptyError,\n                cmdhistory.HistoryEndReachedError):\n            return\n        if item:\n            self.set_cmd_text(item)\n\n    @cmdutils.register(instance='status-command',\n                       modes=[usertypes.KeyMode.command], scope='window')\n    def command_history_next(self):\n        \"\"\"Go forward in the commandline history.\"\"\"\n        if not self.history.is_browsing():\n            return\n        try:\n            item = self.history.nextitem()\n        except cmdhistory.HistoryEndReachedError:\n            return\n        if item:\n            self.set_cmd_text(item)\n\n    @cmdutils.register(instance='status-command',\n                       modes=[usertypes.KeyMode.command], scope='window')\n    def command_accept(self, rapid=False):\n        \"\"\"Execute the command currently in the commandline.\n\n        Args:\n            rapid: Run the command without closing or clearing the command bar.\n        \"\"\"\n        prefixes = {\n            ':': '',\n            '/': 'search -- ',\n            '?': 'search -r -- ',\n        }\n        text = self.text()\n        self.history.append(text)\n        if not rapid:\n            modeman.leave(self._win_id, usertypes.KeyMode.command,\n                          'cmd accept')\n        self.got_cmd[str].emit(prefixes[text[0]] + text[1:])\n\n    @cmdutils.register(instance='status-command', scope='window')\n    def edit_command(self, run=False):\n        \"\"\"Open an editor to modify the current command.\n\n        Args:\n            run: Run the command if the editor exits successfully.\n        \"\"\"\n        ed = editor.ExternalEditor(parent=self)\n\n        def callback(text):\n            \"\"\"Set the commandline to the edited text.\"\"\"\n            if not text or text[0] not in modeparsers.STARTCHARS:\n                message.error('command must start with one of {}'\n                              .format(modeparsers.STARTCHARS))\n                return\n            self.set_cmd_text(text)\n            if run:\n                self.command_accept()\n\n        ed.editing_finished.connect(callback)\n        ed.edit(self.text())\n\n    @pyqtSlot(usertypes.KeyMode)\n    def on_mode_left(self, mode):\n        \"\"\"Clear up when command mode was left.\n\n        - Clear the statusbar text if it's explicitly unfocused.\n        - Clear completion selection\n        - Hide completion\n\n        Args:\n            mode: The mode which was left.\n        \"\"\"\n        if mode == usertypes.KeyMode.command:\n            self.setText('')\n            self.history.stop()\n            self.hide_cmd.emit()\n            self.clear_completion_selection.emit()\n            self.hide_completion.emit()\n\n    def setText(self, text):\n        \"\"\"Extend setText to set prefix and make sure the prompt is ok.\"\"\"\n        if not text:\n            pass\n        elif text[0] in modeparsers.STARTCHARS:\n            super().set_prompt(text[0])\n        else:\n            raise AssertionError(\"setText got called with invalid text \"\n                                 \"'{}'!\".format(text))\n        super().setText(text)\n\n    def keyPressEvent(self, e):\n        \"\"\"Override keyPressEvent to ignore Return key presses.\n\n        If this widget is focused, we are in passthrough key mode, and\n        Enter/Shift+Enter/etc. will cause QLineEdit to think it's finished\n        without command_accept to be called.\n        \"\"\"\n        if e.key() == Qt.Key_Return:\n            e.ignore()\n            return\n        else:\n            super().keyPressEvent(e)\n\n    def sizeHint(self):\n        \"\"\"Dynamically calculate the needed size.\"\"\"\n        height = super().sizeHint().height()\n        text = self.text()\n        if not text:\n            text = 'x'\n        width = self.fontMetrics().width(text)\n        return QSize(width, height)\n\n    @pyqtSlot(str)\n    def _incremental_search(self, text):\n        if not config.val.search.incremental:\n            return\n\n        search_prefixes = {\n            '/': 'search -- ',\n            '?': 'search -r -- ',\n        }\n\n        if self.prefix() in ['/', '?']:\n            self.got_cmd[str].emit(search_prefixes[text[0]] + text[1:])\n", "path": "qutebrowser/mainwindow/statusbar/command.py"}]}