We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Fix replacing of {url} in set_cmd_text_command
```
        # FIXME we currently replace the URL in any place in the arguments,
        # rather than just replacing it if it is a dedicated argument. We could
        # split the args, but then trailing spaces would be lost, so I'm not
        # sure what's the best thing to do here
        text = text.replace('{url}', url)
```

Fix replacing of {url} in set_cmd_text_command
```
        # FIXME we currently replace the URL in any place in the arguments,
        # rather than just replacing it if it is a dedicated argument. We could
        # split the args, but then trailing spaces would be lost, so I'm not
        # sure what's the best thing to do here
        text = text.replace('{url}', url)
```


--- 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-2016 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, QUrl, 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
28 from qutebrowser.misc import miscwidgets as misc
29 from qutebrowser.utils import usertypes, log, objreg, qtutils
30 
31 
32 class Command(misc.MinimalLineEditMixin, misc.CommandLineEdit):
33 
34     """The commandline part of the statusbar.
35 
36     Attributes:
37         _win_id: The window ID this widget is associated with.
38 
39     Signals:
40         got_cmd: Emitted when a command is triggered by the user.
41                  arg: The command string.
42         clear_completion_selection: Emitted before the completion widget is
43                                     hidden.
44         hide_completion: Emitted when the completion widget should be hidden.
45         update_completion: Emitted when the completion should be shown/updated.
46         show_cmd: Emitted when command input should be shown.
47         hide_cmd: Emitted when command input can be hidden.
48     """
49 
50     got_cmd = pyqtSignal(str)
51     clear_completion_selection = pyqtSignal()
52     hide_completion = pyqtSignal()
53     update_completion = pyqtSignal()
54     show_cmd = pyqtSignal()
55     hide_cmd = pyqtSignal()
56 
57     def __init__(self, win_id, parent=None):
58         misc.CommandLineEdit.__init__(self, parent)
59         misc.MinimalLineEditMixin.__init__(self)
60         self._win_id = win_id
61         command_history = objreg.get('command-history')
62         self.history.handle_private_mode = True
63         self.history.history = command_history.data
64         self.history.changed.connect(command_history.changed)
65         self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Ignored)
66         self.cursorPositionChanged.connect(self.update_completion)
67         self.textChanged.connect(self.update_completion)
68         self.textChanged.connect(self.updateGeometry)
69 
70     def prefix(self):
71         """Get the currently entered command prefix."""
72         text = self.text()
73         if not text:
74             return ''
75         elif text[0] in modeparsers.STARTCHARS:
76             return text[0]
77         else:
78             return ''
79 
80     @pyqtSlot(str)
81     def set_cmd_text(self, text):
82         """Preset the statusbar to some text.
83 
84         Args:
85             text: The text to set as string.
86         """
87         self.setText(text)
88         log.modes.debug("Setting command text, focusing {!r}".format(self))
89         modeman.enter(self._win_id, usertypes.KeyMode.command, 'cmd focus')
90         self.setFocus()
91         self.show_cmd.emit()
92 
93     @cmdutils.register(instance='status-command', name='set-cmd-text',
94                        scope='window', maxsplit=0)
95     def set_cmd_text_command(self, text, space=False, append=False):
96         """Preset the statusbar to some text.
97 
98         //
99 
100         Wrapper for set_cmd_text to check the arguments and allow multiple
101         strings which will get joined.
102 
103         Args:
104             text: The commandline to set.
105             space: If given, a space is added to the end.
106             append: If given, the text is appended to the current text.
107         """
108         tabbed_browser = objreg.get('tabbed-browser', scope='window',
109                                     window=self._win_id)
110         if '{url}' in text:
111             try:
112                 url = tabbed_browser.current_url().toString(
113                     QUrl.FullyEncoded | QUrl.RemovePassword)
114             except qtutils.QtValueError as e:
115                 msg = "Current URL is invalid"
116                 if e.reason:
117                     msg += " ({})".format(e.reason)
118                 msg += "!"
119                 raise cmdexc.CommandError(msg)
120             # FIXME we currently replace the URL in any place in the arguments,
121             # rather than just replacing it if it is a dedicated argument. We
122             # could split the args, but then trailing spaces would be lost, so
123             # I'm not sure what's the best thing to do here
124             # https://github.com/The-Compiler/qutebrowser/issues/123
125             text = text.replace('{url}', url)
126 
127         if space:
128             text += ' '
129         if append:
130             if not self.text():
131                 raise cmdexc.CommandError("No current text!")
132             text = self.text() + text
133 
134         if not text or text[0] not in modeparsers.STARTCHARS:
135             raise cmdexc.CommandError(
136                 "Invalid command text '{}'.".format(text))
137         self.set_cmd_text(text)
138 
139     @cmdutils.register(instance='status-command', hide=True,
140                        modes=[usertypes.KeyMode.command], scope='window')
141     def command_history_prev(self):
142         """Go back in the commandline history."""
143         try:
144             if not self.history.is_browsing():
145                 item = self.history.start(self.text().strip())
146             else:
147                 item = self.history.previtem()
148         except (cmdhistory.HistoryEmptyError,
149                 cmdhistory.HistoryEndReachedError):
150             return
151         if item:
152             self.set_cmd_text(item)
153 
154     @cmdutils.register(instance='status-command', hide=True,
155                        modes=[usertypes.KeyMode.command], scope='window')
156     def command_history_next(self):
157         """Go forward in the commandline history."""
158         if not self.history.is_browsing():
159             return
160         try:
161             item = self.history.nextitem()
162         except cmdhistory.HistoryEndReachedError:
163             return
164         if item:
165             self.set_cmd_text(item)
166 
167     @cmdutils.register(instance='status-command', hide=True,
168                        modes=[usertypes.KeyMode.command], scope='window')
169     def command_accept(self):
170         """Execute the command currently in the commandline."""
171         prefixes = {
172             ':': '',
173             '/': 'search -- ',
174             '?': 'search -r -- ',
175         }
176         text = self.text()
177         self.history.append(text)
178         modeman.leave(self._win_id, usertypes.KeyMode.command, 'cmd accept')
179         self.got_cmd.emit(prefixes[text[0]] + text[1:])
180 
181     @pyqtSlot(usertypes.KeyMode)
182     def on_mode_left(self, mode):
183         """Clear up when command mode was left.
184 
185         - Clear the statusbar text if it's explicitly unfocused.
186         - Clear completion selection
187         - Hide completion
188 
189         Args:
190             mode: The mode which was left.
191         """
192         if mode == usertypes.KeyMode.command:
193             self.setText('')
194             self.history.stop()
195             self.hide_cmd.emit()
196             self.clear_completion_selection.emit()
197             self.hide_completion.emit()
198 
199     def setText(self, text):
200         """Extend setText to set prefix and make sure the prompt is ok."""
201         if not text:
202             pass
203         elif text[0] in modeparsers.STARTCHARS:
204             super().set_prompt(text[0])
205         else:
206             raise AssertionError("setText got called with invalid text "
207                                  "'{}'!".format(text))
208         super().setText(text)
209 
210     def keyPressEvent(self, e):
211         """Override keyPressEvent to ignore Return key presses.
212 
213         If this widget is focused, we are in passthrough key mode, and
214         Enter/Shift+Enter/etc. will cause QLineEdit to think it's finished
215         without command_accept to be called.
216         """
217         if e.key() == Qt.Key_Return:
218             e.ignore()
219             return
220         else:
221             super().keyPressEvent(e)
222 
223     def sizeHint(self):
224         """Dynamically calculate the needed size."""
225         height = super().sizeHint().height()
226         text = self.text()
227         if not text:
228             text = 'x'
229         width = self.fontMetrics().width(text)
230         return QSize(width, height)
231
```
--- 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
@@ -19,14 +19,14 @@
 
 """The commandline in the statusbar."""
 
-from PyQt5.QtCore import pyqtSignal, pyqtSlot, Qt, QUrl, QSize
+from PyQt5.QtCore import pyqtSignal, pyqtSlot, Qt, QSize
 from PyQt5.QtWidgets import QSizePolicy
 
 from qutebrowser.keyinput import modeman, modeparsers
-from qutebrowser.commands import cmdexc, cmdutils
-from qutebrowser.misc import cmdhistory
+from qutebrowser.commands import cmdexc, cmdutils, runners
+from qutebrowser.misc import cmdhistory, split
 from qutebrowser.misc import miscwidgets as misc
-from qutebrowser.utils import usertypes, log, objreg, qtutils
+from qutebrowser.utils import usertypes, log, objreg
 
 
 class Command(misc.MinimalLineEditMixin, misc.CommandLineEdit):
@@ -105,24 +105,9 @@
             space: If given, a space is added to the end.
             append: If given, the text is appended to the current text.
         """
-        tabbed_browser = objreg.get('tabbed-browser', scope='window',
-                                    window=self._win_id)
-        if '{url}' in text:
-            try:
-                url = tabbed_browser.current_url().toString(
-                    QUrl.FullyEncoded | QUrl.RemovePassword)
-            except qtutils.QtValueError as e:
-                msg = "Current URL is invalid"
-                if e.reason:
-                    msg += " ({})".format(e.reason)
-                msg += "!"
-                raise cmdexc.CommandError(msg)
-            # FIXME we currently replace the URL in any place in the arguments,
-            # rather than just replacing it if it is a dedicated argument. We
-            # could split the args, but then trailing spaces would be lost, so
-            # I'm not sure what's the best thing to do here
-            # https://github.com/The-Compiler/qutebrowser/issues/123
-            text = text.replace('{url}', url)
+        args = split.simple_split(text)
+        args = runners.replace_variables(self._win_id, args)
+        text = ' '.join(args)
 
         if space:
             text += ' '

{"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@@ -19,14 +19,14 @@\n \n \"\"\"The commandline in the statusbar.\"\"\"\n \n-from PyQt5.QtCore import pyqtSignal, pyqtSlot, Qt, QUrl, QSize\n+from PyQt5.QtCore import pyqtSignal, pyqtSlot, Qt, QSize\n from PyQt5.QtWidgets import QSizePolicy\n \n from qutebrowser.keyinput import modeman, modeparsers\n-from qutebrowser.commands import cmdexc, cmdutils\n-from qutebrowser.misc import cmdhistory\n+from qutebrowser.commands import cmdexc, cmdutils, runners\n+from qutebrowser.misc import cmdhistory, split\n from qutebrowser.misc import miscwidgets as misc\n-from qutebrowser.utils import usertypes, log, objreg, qtutils\n+from qutebrowser.utils import usertypes, log, objreg\n \n \n class Command(misc.MinimalLineEditMixin, misc.CommandLineEdit):\n@@ -105,24 +105,9 @@\n             space: If given, a space is added to the end.\n             append: If given, the text is appended to the current text.\n         \"\"\"\n-        tabbed_browser = objreg.get('tabbed-browser', scope='window',\n-                                    window=self._win_id)\n-        if '{url}' in text:\n-            try:\n-                url = tabbed_browser.current_url().toString(\n-                    QUrl.FullyEncoded | QUrl.RemovePassword)\n-            except qtutils.QtValueError as e:\n-                msg = \"Current URL is invalid\"\n-                if e.reason:\n-                    msg += \" ({})\".format(e.reason)\n-                msg += \"!\"\n-                raise cmdexc.CommandError(msg)\n-            # FIXME we currently replace the URL in any place in the arguments,\n-            # rather than just replacing it if it is a dedicated argument. We\n-            # could split the args, but then trailing spaces would be lost, so\n-            # I'm not sure what's the best thing to do here\n-            # https://github.com/The-Compiler/qutebrowser/issues/123\n-            text = text.replace('{url}', url)\n+        args = split.simple_split(text)\n+        args = runners.replace_variables(self._win_id, args)\n+        text = ' '.join(args)\n \n         if space:\n             text += ' '\n", "issue": "Fix replacing of {url} in set_cmd_text_command\n```\n        # FIXME we currently replace the URL in any place in the arguments,\n        # rather than just replacing it if it is a dedicated argument. We could\n        # split the args, but then trailing spaces would be lost, so I'm not\n        # sure what's the best thing to do here\n        text = text.replace('{url}', url)\n```\n\nFix replacing of {url} in set_cmd_text_command\n```\n        # FIXME we currently replace the URL in any place in the arguments,\n        # rather than just replacing it if it is a dedicated argument. We could\n        # split the args, but then trailing spaces would be lost, so I'm not\n        # sure what's the best thing to do here\n        text = text.replace('{url}', url)\n```\n\n", "before_files": [{"content": "# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:\n\n# Copyright 2014-2016 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, QUrl, QSize\nfrom PyQt5.QtWidgets import QSizePolicy\n\nfrom qutebrowser.keyinput import modeman, modeparsers\nfrom qutebrowser.commands import cmdexc, cmdutils\nfrom qutebrowser.misc import cmdhistory\nfrom qutebrowser.misc import miscwidgets as misc\nfrom qutebrowser.utils import usertypes, log, objreg, qtutils\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.\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)\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, parent=None):\n        misc.CommandLineEdit.__init__(self, parent)\n        misc.MinimalLineEditMixin.__init__(self)\n        self._win_id = win_id\n        command_history = objreg.get('command-history')\n        self.history.handle_private_mode = True\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\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    @pyqtSlot(str)\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    def set_cmd_text_command(self, text, space=False, append=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            space: If given, a space is added to the end.\n            append: If given, the text is appended to the current text.\n        \"\"\"\n        tabbed_browser = objreg.get('tabbed-browser', scope='window',\n                                    window=self._win_id)\n        if '{url}' in text:\n            try:\n                url = tabbed_browser.current_url().toString(\n                    QUrl.FullyEncoded | QUrl.RemovePassword)\n            except qtutils.QtValueError as e:\n                msg = \"Current URL is invalid\"\n                if e.reason:\n                    msg += \" ({})\".format(e.reason)\n                msg += \"!\"\n                raise cmdexc.CommandError(msg)\n            # FIXME we currently replace the URL in any place in the arguments,\n            # rather than just replacing it if it is a dedicated argument. We\n            # could split the args, but then trailing spaces would be lost, so\n            # I'm not sure what's the best thing to do here\n            # https://github.com/The-Compiler/qutebrowser/issues/123\n            text = text.replace('{url}', url)\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        self.set_cmd_text(text)\n\n    @cmdutils.register(instance='status-command', hide=True,\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', hide=True,\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', hide=True,\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.emit(prefixes[text[0]] + text[1:])\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", "path": "qutebrowser/mainwindow/statusbar/command.py"}], "after_files": [{"content": "# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:\n\n# Copyright 2014-2016 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, runners\nfrom qutebrowser.misc import cmdhistory, split\nfrom qutebrowser.misc import miscwidgets as misc\nfrom qutebrowser.utils import usertypes, log, objreg\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.\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)\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, parent=None):\n        misc.CommandLineEdit.__init__(self, parent)\n        misc.MinimalLineEditMixin.__init__(self)\n        self._win_id = win_id\n        command_history = objreg.get('command-history')\n        self.history.handle_private_mode = True\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\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    @pyqtSlot(str)\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    def set_cmd_text_command(self, text, space=False, append=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            space: If given, a space is added to the end.\n            append: If given, the text is appended to the current text.\n        \"\"\"\n        args = split.simple_split(text)\n        args = runners.replace_variables(self._win_id, args)\n        text = ' '.join(args)\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        self.set_cmd_text(text)\n\n    @cmdutils.register(instance='status-command', hide=True,\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', hide=True,\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', hide=True,\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.emit(prefixes[text[0]] + text[1:])\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", "path": "qutebrowser/mainwindow/statusbar/command.py"}]}