We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Up arrow key history search gets stuck in QTConsole
With the ipython installed with with commit 50a583890fd0640492fcd76d6ecc97b5c3f23ae0, going through history with up arrow key in qtconsole works without any problem. But in current commit 48b63c19a53f9e26dc4f64150641c730cb6a2305, in qtconsole, it gets "stuck" after several items - pressing up arrow key does not do anything. It seems to be happening when the currently showing history is longer than the qtconsole width. 

Since there are more than 120 commits in between, I haven't tried to identify what was the commit which caused this.

Also, in terminal this does not happen.


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `IPython/frontend/qt/console/history_console_widget.py`
Content:
```
1 # System library imports
2 from IPython.external.qt import QtGui
3 
4 # Local imports
5 from IPython.utils.traitlets import Bool
6 from console_widget import ConsoleWidget
7 
8 
9 class HistoryConsoleWidget(ConsoleWidget):
10     """ A ConsoleWidget that keeps a history of the commands that have been
11         executed and provides a readline-esque interface to this history.
12     """
13 
14     #------ Configuration ------------------------------------------------------
15 
16     # If enabled, the input buffer will become "locked" to history movement when
17     # an edit is made to a multi-line input buffer. To override the lock, use
18     # Shift in conjunction with the standard history cycling keys.
19     history_lock = Bool(False, config=True)
20 
21     #---------------------------------------------------------------------------
22     # 'object' interface
23     #---------------------------------------------------------------------------
24 
25     def __init__(self, *args, **kw):
26         super(HistoryConsoleWidget, self).__init__(*args, **kw)
27 
28         # HistoryConsoleWidget protected variables.
29         self._history = []
30         self._history_edits = {}
31         self._history_index = 0
32         self._history_prefix = ''
33 
34     #---------------------------------------------------------------------------
35     # 'ConsoleWidget' public interface
36     #---------------------------------------------------------------------------
37 
38     def execute(self, source=None, hidden=False, interactive=False):
39         """ Reimplemented to the store history.
40         """
41         if not hidden:
42             history = self.input_buffer if source is None else source
43 
44         executed = super(HistoryConsoleWidget, self).execute(
45             source, hidden, interactive)
46 
47         if executed and not hidden:
48             # Save the command unless it was an empty string or was identical
49             # to the previous command.
50             history = history.rstrip()
51             if history and (not self._history or self._history[-1] != history):
52                 self._history.append(history)
53 
54             # Emulate readline: reset all history edits.
55             self._history_edits = {}
56 
57             # Move the history index to the most recent item.
58             self._history_index = len(self._history)
59 
60         return executed
61 
62     #---------------------------------------------------------------------------
63     # 'ConsoleWidget' abstract interface
64     #---------------------------------------------------------------------------
65 
66     def _up_pressed(self, shift_modifier):
67         """ Called when the up key is pressed. Returns whether to continue
68             processing the event.
69         """
70         prompt_cursor = self._get_prompt_cursor()
71         if self._get_cursor().blockNumber() == prompt_cursor.blockNumber():
72             # Bail out if we're locked.
73             if self._history_locked() and not shift_modifier:
74                 return False
75 
76             # Set a search prefix based on the cursor position.
77             col = self._get_input_buffer_cursor_column()
78             input_buffer = self.input_buffer
79             # use the *shortest* of the cursor column and the history prefix
80             # to determine if the prefix has changed
81             n = min(col, len(self._history_prefix))
82             
83             # prefix changed, restart search from the beginning
84             if (self._history_prefix[:n] != input_buffer[:n]):
85                 self._history_index = len(self._history)
86             
87             # the only time we shouldn't set the history prefix
88             # to the line up to the cursor is if we are already
89             # in a simple scroll (no prefix),
90             # and the cursor is at the end of the first line
91             first_line = input_buffer.split('\n', 1)[0]
92             if self._history_index == len(self._history) or \
93                 not (self._history_prefix == '' and col == len(first_line)) or \
94                 not (self._get_edited_history(self._history_index)[:col] == input_buffer[:col]):
95                 self._history_prefix = input_buffer[:col]
96 
97             # Perform the search.
98             self.history_previous(self._history_prefix,
99                                     as_prefix=not shift_modifier)
100 
101             # Go to the first line of the prompt for seemless history scrolling.
102             # Emulate readline: keep the cursor position fixed for a prefix
103             # search.
104             cursor = self._get_prompt_cursor()
105             if self._history_prefix:
106                 cursor.movePosition(QtGui.QTextCursor.Right,
107                                     n=len(self._history_prefix))
108             else:
109                 cursor.movePosition(QtGui.QTextCursor.EndOfLine)
110             self._set_cursor(cursor)
111 
112             return False
113 
114         return True
115 
116     def _down_pressed(self, shift_modifier):
117         """ Called when the down key is pressed. Returns whether to continue
118             processing the event.
119         """
120         end_cursor = self._get_end_cursor()
121         if self._get_cursor().blockNumber() == end_cursor.blockNumber():
122             # Bail out if we're locked.
123             if self._history_locked() and not shift_modifier:
124                 return False
125 
126             # Perform the search.
127             replaced = self.history_next(self._history_prefix,
128                                             as_prefix=not shift_modifier)
129 
130             # Emulate readline: keep the cursor position fixed for a prefix
131             # search. (We don't need to move the cursor to the end of the buffer
132             # in the other case because this happens automatically when the
133             # input buffer is set.)
134             if self._history_prefix and replaced:
135                 cursor = self._get_prompt_cursor()
136                 cursor.movePosition(QtGui.QTextCursor.Right,
137                                     n=len(self._history_prefix))
138                 self._set_cursor(cursor)
139 
140             return False
141 
142         return True
143 
144     #---------------------------------------------------------------------------
145     # 'HistoryConsoleWidget' public interface
146     #---------------------------------------------------------------------------
147 
148     def history_previous(self, substring='', as_prefix=True):
149         """ If possible, set the input buffer to a previous history item.
150 
151         Parameters:
152         -----------
153         substring : str, optional
154             If specified, search for an item with this substring.
155         as_prefix : bool, optional
156             If True, the substring must match at the beginning (default).
157 
158         Returns:
159         --------
160         Whether the input buffer was changed.
161         """
162         index = self._history_index
163         replace = False
164         while index > 0:
165             index -= 1
166             history = self._get_edited_history(index)
167             if (as_prefix and history.startswith(substring)) \
168                 or (not as_prefix and substring in history):
169                 replace = True
170                 break
171 
172         if replace:
173             self._store_edits()
174             self._history_index = index
175             self.input_buffer = history
176 
177         return replace
178 
179     def history_next(self, substring='', as_prefix=True):
180         """ If possible, set the input buffer to a subsequent history item.
181 
182         Parameters:
183         -----------
184         substring : str, optional
185             If specified, search for an item with this substring.
186         as_prefix : bool, optional
187             If True, the substring must match at the beginning (default).
188 
189         Returns:
190         --------
191         Whether the input buffer was changed.
192         """
193         index = self._history_index
194         replace = False
195         while index < len(self._history):
196             index += 1
197             history = self._get_edited_history(index)
198             if (as_prefix and history.startswith(substring)) \
199                 or (not as_prefix and substring in history):
200                 replace = True
201                 break
202 
203         if replace:
204             self._store_edits()
205             self._history_index = index
206             self.input_buffer = history
207 
208         return replace
209 
210     def history_tail(self, n=10):
211         """ Get the local history list.
212 
213         Parameters:
214         -----------
215         n : int
216             The (maximum) number of history items to get.
217         """
218         return self._history[-n:]
219 
220     def _request_update_session_history_length(self):
221         msg_id = self.kernel_manager.shell_channel.execute('',
222             silent=True,
223             user_expressions={
224                 'hlen':'len(get_ipython().history_manager.input_hist_raw)',
225                 }
226             )
227         self._request_info['execute'][msg_id] = self._ExecutionRequest(msg_id, 'save_magic')
228 
229     def _handle_execute_reply(self, msg):
230         """ Handles replies for code execution, here only session history length
231         """
232         msg_id = msg['parent_header']['msg_id']
233         info = self._request_info['execute'].pop(msg_id,None)
234         if info and info.kind == 'save_magic' and not self._hidden:
235             content = msg['content']
236             status = content['status']
237             if status == 'ok':
238                 self._max_session_history=(int(content['user_expressions']['hlen']))
239 
240     def save_magic(self):
241         # update the session history length
242         self._request_update_session_history_length()
243 
244         file_name,extFilter = QtGui.QFileDialog.getSaveFileName(self,
245             "Enter A filename",
246             filter='Python File (*.py);; All files (*.*)'
247             )
248 
249         # let's the user search/type for a file name, while the history length
250         # is fetched
251 
252         if file_name:
253             hist_range, ok = QtGui.QInputDialog.getText(self,
254                 'Please enter an interval of command to save',
255                 'Saving commands:',
256                 text=str('1-'+str(self._max_session_history))
257                 )
258             if ok:
259                 self.execute("%save"+" "+file_name+" "+str(hist_range))
260 
261     #---------------------------------------------------------------------------
262     # 'HistoryConsoleWidget' protected interface
263     #---------------------------------------------------------------------------
264 
265     def _history_locked(self):
266         """ Returns whether history movement is locked.
267         """
268         return (self.history_lock and
269                 (self._get_edited_history(self._history_index) !=
270                  self.input_buffer) and
271                 (self._get_prompt_cursor().blockNumber() !=
272                  self._get_end_cursor().blockNumber()))
273 
274     def _get_edited_history(self, index):
275         """ Retrieves a history item, possibly with temporary edits.
276         """
277         if index in self._history_edits:
278             return self._history_edits[index]
279         elif index == len(self._history):
280             return unicode()
281         return self._history[index]
282 
283     def _set_history(self, history):
284         """ Replace the current history with a sequence of history items.
285         """
286         self._history = list(history)
287         self._history_edits = {}
288         self._history_index = len(self._history)
289 
290     def _store_edits(self):
291         """ If there are edits to the current input buffer, store them.
292         """
293         current = self.input_buffer
294         if self._history_index == len(self._history) or \
295                 self._history[self._history_index] != current:
296             self._history_edits[self._history_index] = current
297
```
--- 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/IPython/frontend/qt/console/history_console_widget.py b/IPython/frontend/qt/console/history_console_widget.py
--- a/IPython/frontend/qt/console/history_console_widget.py
+++ b/IPython/frontend/qt/console/history_console_widget.py
@@ -88,9 +88,15 @@
             # to the line up to the cursor is if we are already
             # in a simple scroll (no prefix),
             # and the cursor is at the end of the first line
-            first_line = input_buffer.split('\n', 1)[0]
+            
+            # check if we are at the end of the first line
+            c = self._get_cursor()
+            current_pos = c.position()
+            c.movePosition(QtGui.QTextCursor.EndOfLine)
+            at_eol = (c.position() == current_pos)
+            
             if self._history_index == len(self._history) or \
-                not (self._history_prefix == '' and col == len(first_line)) or \
+                not (self._history_prefix == '' and at_eol) or \
                 not (self._get_edited_history(self._history_index)[:col] == input_buffer[:col]):
                 self._history_prefix = input_buffer[:col]

{"golden_diff": "diff --git a/IPython/frontend/qt/console/history_console_widget.py b/IPython/frontend/qt/console/history_console_widget.py\n--- a/IPython/frontend/qt/console/history_console_widget.py\n+++ b/IPython/frontend/qt/console/history_console_widget.py\n@@ -88,9 +88,15 @@\n             # to the line up to the cursor is if we are already\n             # in a simple scroll (no prefix),\n             # and the cursor is at the end of the first line\n-            first_line = input_buffer.split('\\n', 1)[0]\n+            \n+            # check if we are at the end of the first line\n+            c = self._get_cursor()\n+            current_pos = c.position()\n+            c.movePosition(QtGui.QTextCursor.EndOfLine)\n+            at_eol = (c.position() == current_pos)\n+            \n             if self._history_index == len(self._history) or \\\n-                not (self._history_prefix == '' and col == len(first_line)) or \\\n+                not (self._history_prefix == '' and at_eol) or \\\n                 not (self._get_edited_history(self._history_index)[:col] == input_buffer[:col]):\n                 self._history_prefix = input_buffer[:col]\n", "issue": "Up arrow key history search gets stuck in QTConsole\nWith the ipython installed with with commit 50a583890fd0640492fcd76d6ecc97b5c3f23ae0, going through history with up arrow key in qtconsole works without any problem. But in current commit 48b63c19a53f9e26dc4f64150641c730cb6a2305, in qtconsole, it gets \"stuck\" after several items - pressing up arrow key does not do anything. It seems to be happening when the currently showing history is longer than the qtconsole width. \n\nSince there are more than 120 commits in between, I haven't tried to identify what was the commit which caused this.\n\nAlso, in terminal this does not happen.\n\n", "before_files": [{"content": "# System library imports\nfrom IPython.external.qt import QtGui\n\n# Local imports\nfrom IPython.utils.traitlets import Bool\nfrom console_widget import ConsoleWidget\n\n\nclass HistoryConsoleWidget(ConsoleWidget):\n    \"\"\" A ConsoleWidget that keeps a history of the commands that have been\n        executed and provides a readline-esque interface to this history.\n    \"\"\"\n\n    #------ Configuration ------------------------------------------------------\n\n    # If enabled, the input buffer will become \"locked\" to history movement when\n    # an edit is made to a multi-line input buffer. To override the lock, use\n    # Shift in conjunction with the standard history cycling keys.\n    history_lock = Bool(False, config=True)\n\n    #---------------------------------------------------------------------------\n    # 'object' interface\n    #---------------------------------------------------------------------------\n\n    def __init__(self, *args, **kw):\n        super(HistoryConsoleWidget, self).__init__(*args, **kw)\n\n        # HistoryConsoleWidget protected variables.\n        self._history = []\n        self._history_edits = {}\n        self._history_index = 0\n        self._history_prefix = ''\n\n    #---------------------------------------------------------------------------\n    # 'ConsoleWidget' public interface\n    #---------------------------------------------------------------------------\n\n    def execute(self, source=None, hidden=False, interactive=False):\n        \"\"\" Reimplemented to the store history.\n        \"\"\"\n        if not hidden:\n            history = self.input_buffer if source is None else source\n\n        executed = super(HistoryConsoleWidget, self).execute(\n            source, hidden, interactive)\n\n        if executed and not hidden:\n            # Save the command unless it was an empty string or was identical\n            # to the previous command.\n            history = history.rstrip()\n            if history and (not self._history or self._history[-1] != history):\n                self._history.append(history)\n\n            # Emulate readline: reset all history edits.\n            self._history_edits = {}\n\n            # Move the history index to the most recent item.\n            self._history_index = len(self._history)\n\n        return executed\n\n    #---------------------------------------------------------------------------\n    # 'ConsoleWidget' abstract interface\n    #---------------------------------------------------------------------------\n\n    def _up_pressed(self, shift_modifier):\n        \"\"\" Called when the up key is pressed. Returns whether to continue\n            processing the event.\n        \"\"\"\n        prompt_cursor = self._get_prompt_cursor()\n        if self._get_cursor().blockNumber() == prompt_cursor.blockNumber():\n            # Bail out if we're locked.\n            if self._history_locked() and not shift_modifier:\n                return False\n\n            # Set a search prefix based on the cursor position.\n            col = self._get_input_buffer_cursor_column()\n            input_buffer = self.input_buffer\n            # use the *shortest* of the cursor column and the history prefix\n            # to determine if the prefix has changed\n            n = min(col, len(self._history_prefix))\n            \n            # prefix changed, restart search from the beginning\n            if (self._history_prefix[:n] != input_buffer[:n]):\n                self._history_index = len(self._history)\n            \n            # the only time we shouldn't set the history prefix\n            # to the line up to the cursor is if we are already\n            # in a simple scroll (no prefix),\n            # and the cursor is at the end of the first line\n            first_line = input_buffer.split('\\n', 1)[0]\n            if self._history_index == len(self._history) or \\\n                not (self._history_prefix == '' and col == len(first_line)) or \\\n                not (self._get_edited_history(self._history_index)[:col] == input_buffer[:col]):\n                self._history_prefix = input_buffer[:col]\n\n            # Perform the search.\n            self.history_previous(self._history_prefix,\n                                    as_prefix=not shift_modifier)\n\n            # Go to the first line of the prompt for seemless history scrolling.\n            # Emulate readline: keep the cursor position fixed for a prefix\n            # search.\n            cursor = self._get_prompt_cursor()\n            if self._history_prefix:\n                cursor.movePosition(QtGui.QTextCursor.Right,\n                                    n=len(self._history_prefix))\n            else:\n                cursor.movePosition(QtGui.QTextCursor.EndOfLine)\n            self._set_cursor(cursor)\n\n            return False\n\n        return True\n\n    def _down_pressed(self, shift_modifier):\n        \"\"\" Called when the down key is pressed. Returns whether to continue\n            processing the event.\n        \"\"\"\n        end_cursor = self._get_end_cursor()\n        if self._get_cursor().blockNumber() == end_cursor.blockNumber():\n            # Bail out if we're locked.\n            if self._history_locked() and not shift_modifier:\n                return False\n\n            # Perform the search.\n            replaced = self.history_next(self._history_prefix,\n                                            as_prefix=not shift_modifier)\n\n            # Emulate readline: keep the cursor position fixed for a prefix\n            # search. (We don't need to move the cursor to the end of the buffer\n            # in the other case because this happens automatically when the\n            # input buffer is set.)\n            if self._history_prefix and replaced:\n                cursor = self._get_prompt_cursor()\n                cursor.movePosition(QtGui.QTextCursor.Right,\n                                    n=len(self._history_prefix))\n                self._set_cursor(cursor)\n\n            return False\n\n        return True\n\n    #---------------------------------------------------------------------------\n    # 'HistoryConsoleWidget' public interface\n    #---------------------------------------------------------------------------\n\n    def history_previous(self, substring='', as_prefix=True):\n        \"\"\" If possible, set the input buffer to a previous history item.\n\n        Parameters:\n        -----------\n        substring : str, optional\n            If specified, search for an item with this substring.\n        as_prefix : bool, optional\n            If True, the substring must match at the beginning (default).\n\n        Returns:\n        --------\n        Whether the input buffer was changed.\n        \"\"\"\n        index = self._history_index\n        replace = False\n        while index > 0:\n            index -= 1\n            history = self._get_edited_history(index)\n            if (as_prefix and history.startswith(substring)) \\\n                or (not as_prefix and substring in history):\n                replace = True\n                break\n\n        if replace:\n            self._store_edits()\n            self._history_index = index\n            self.input_buffer = history\n\n        return replace\n\n    def history_next(self, substring='', as_prefix=True):\n        \"\"\" If possible, set the input buffer to a subsequent history item.\n\n        Parameters:\n        -----------\n        substring : str, optional\n            If specified, search for an item with this substring.\n        as_prefix : bool, optional\n            If True, the substring must match at the beginning (default).\n\n        Returns:\n        --------\n        Whether the input buffer was changed.\n        \"\"\"\n        index = self._history_index\n        replace = False\n        while index < len(self._history):\n            index += 1\n            history = self._get_edited_history(index)\n            if (as_prefix and history.startswith(substring)) \\\n                or (not as_prefix and substring in history):\n                replace = True\n                break\n\n        if replace:\n            self._store_edits()\n            self._history_index = index\n            self.input_buffer = history\n\n        return replace\n\n    def history_tail(self, n=10):\n        \"\"\" Get the local history list.\n\n        Parameters:\n        -----------\n        n : int\n            The (maximum) number of history items to get.\n        \"\"\"\n        return self._history[-n:]\n\n    def _request_update_session_history_length(self):\n        msg_id = self.kernel_manager.shell_channel.execute('',\n            silent=True,\n            user_expressions={\n                'hlen':'len(get_ipython().history_manager.input_hist_raw)',\n                }\n            )\n        self._request_info['execute'][msg_id] = self._ExecutionRequest(msg_id, 'save_magic')\n\n    def _handle_execute_reply(self, msg):\n        \"\"\" Handles replies for code execution, here only session history length\n        \"\"\"\n        msg_id = msg['parent_header']['msg_id']\n        info = self._request_info['execute'].pop(msg_id,None)\n        if info and info.kind == 'save_magic' and not self._hidden:\n            content = msg['content']\n            status = content['status']\n            if status == 'ok':\n                self._max_session_history=(int(content['user_expressions']['hlen']))\n\n    def save_magic(self):\n        # update the session history length\n        self._request_update_session_history_length()\n\n        file_name,extFilter = QtGui.QFileDialog.getSaveFileName(self,\n            \"Enter A filename\",\n            filter='Python File (*.py);; All files (*.*)'\n            )\n\n        # let's the user search/type for a file name, while the history length\n        # is fetched\n\n        if file_name:\n            hist_range, ok = QtGui.QInputDialog.getText(self,\n                'Please enter an interval of command to save',\n                'Saving commands:',\n                text=str('1-'+str(self._max_session_history))\n                )\n            if ok:\n                self.execute(\"%save\"+\" \"+file_name+\" \"+str(hist_range))\n\n    #---------------------------------------------------------------------------\n    # 'HistoryConsoleWidget' protected interface\n    #---------------------------------------------------------------------------\n\n    def _history_locked(self):\n        \"\"\" Returns whether history movement is locked.\n        \"\"\"\n        return (self.history_lock and\n                (self._get_edited_history(self._history_index) !=\n                 self.input_buffer) and\n                (self._get_prompt_cursor().blockNumber() !=\n                 self._get_end_cursor().blockNumber()))\n\n    def _get_edited_history(self, index):\n        \"\"\" Retrieves a history item, possibly with temporary edits.\n        \"\"\"\n        if index in self._history_edits:\n            return self._history_edits[index]\n        elif index == len(self._history):\n            return unicode()\n        return self._history[index]\n\n    def _set_history(self, history):\n        \"\"\" Replace the current history with a sequence of history items.\n        \"\"\"\n        self._history = list(history)\n        self._history_edits = {}\n        self._history_index = len(self._history)\n\n    def _store_edits(self):\n        \"\"\" If there are edits to the current input buffer, store them.\n        \"\"\"\n        current = self.input_buffer\n        if self._history_index == len(self._history) or \\\n                self._history[self._history_index] != current:\n            self._history_edits[self._history_index] = current\n", "path": "IPython/frontend/qt/console/history_console_widget.py"}], "after_files": [{"content": "# System library imports\nfrom IPython.external.qt import QtGui\n\n# Local imports\nfrom IPython.utils.traitlets import Bool\nfrom console_widget import ConsoleWidget\n\n\nclass HistoryConsoleWidget(ConsoleWidget):\n    \"\"\" A ConsoleWidget that keeps a history of the commands that have been\n        executed and provides a readline-esque interface to this history.\n    \"\"\"\n\n    #------ Configuration ------------------------------------------------------\n\n    # If enabled, the input buffer will become \"locked\" to history movement when\n    # an edit is made to a multi-line input buffer. To override the lock, use\n    # Shift in conjunction with the standard history cycling keys.\n    history_lock = Bool(False, config=True)\n\n    #---------------------------------------------------------------------------\n    # 'object' interface\n    #---------------------------------------------------------------------------\n\n    def __init__(self, *args, **kw):\n        super(HistoryConsoleWidget, self).__init__(*args, **kw)\n\n        # HistoryConsoleWidget protected variables.\n        self._history = []\n        self._history_edits = {}\n        self._history_index = 0\n        self._history_prefix = ''\n\n    #---------------------------------------------------------------------------\n    # 'ConsoleWidget' public interface\n    #---------------------------------------------------------------------------\n\n    def execute(self, source=None, hidden=False, interactive=False):\n        \"\"\" Reimplemented to the store history.\n        \"\"\"\n        if not hidden:\n            history = self.input_buffer if source is None else source\n\n        executed = super(HistoryConsoleWidget, self).execute(\n            source, hidden, interactive)\n\n        if executed and not hidden:\n            # Save the command unless it was an empty string or was identical\n            # to the previous command.\n            history = history.rstrip()\n            if history and (not self._history or self._history[-1] != history):\n                self._history.append(history)\n\n            # Emulate readline: reset all history edits.\n            self._history_edits = {}\n\n            # Move the history index to the most recent item.\n            self._history_index = len(self._history)\n\n        return executed\n\n    #---------------------------------------------------------------------------\n    # 'ConsoleWidget' abstract interface\n    #---------------------------------------------------------------------------\n\n    def _up_pressed(self, shift_modifier):\n        \"\"\" Called when the up key is pressed. Returns whether to continue\n            processing the event.\n        \"\"\"\n        prompt_cursor = self._get_prompt_cursor()\n        if self._get_cursor().blockNumber() == prompt_cursor.blockNumber():\n            # Bail out if we're locked.\n            if self._history_locked() and not shift_modifier:\n                return False\n\n            # Set a search prefix based on the cursor position.\n            col = self._get_input_buffer_cursor_column()\n            input_buffer = self.input_buffer\n            # use the *shortest* of the cursor column and the history prefix\n            # to determine if the prefix has changed\n            n = min(col, len(self._history_prefix))\n            \n            # prefix changed, restart search from the beginning\n            if (self._history_prefix[:n] != input_buffer[:n]):\n                self._history_index = len(self._history)\n            \n            # the only time we shouldn't set the history prefix\n            # to the line up to the cursor is if we are already\n            # in a simple scroll (no prefix),\n            # and the cursor is at the end of the first line\n            \n            # check if we are at the end of the first line\n            c = self._get_cursor()\n            current_pos = c.position()\n            c.movePosition(QtGui.QTextCursor.EndOfLine)\n            at_eol = (c.position() == current_pos)\n            \n            if self._history_index == len(self._history) or \\\n                not (self._history_prefix == '' and at_eol) or \\\n                not (self._get_edited_history(self._history_index)[:col] == input_buffer[:col]):\n                self._history_prefix = input_buffer[:col]\n\n            # Perform the search.\n            self.history_previous(self._history_prefix,\n                                    as_prefix=not shift_modifier)\n\n            # Go to the first line of the prompt for seemless history scrolling.\n            # Emulate readline: keep the cursor position fixed for a prefix\n            # search.\n            cursor = self._get_prompt_cursor()\n            if self._history_prefix:\n                cursor.movePosition(QtGui.QTextCursor.Right,\n                                    n=len(self._history_prefix))\n            else:\n                cursor.movePosition(QtGui.QTextCursor.EndOfLine)\n            self._set_cursor(cursor)\n\n            return False\n\n        return True\n\n    def _down_pressed(self, shift_modifier):\n        \"\"\" Called when the down key is pressed. Returns whether to continue\n            processing the event.\n        \"\"\"\n        end_cursor = self._get_end_cursor()\n        if self._get_cursor().blockNumber() == end_cursor.blockNumber():\n            # Bail out if we're locked.\n            if self._history_locked() and not shift_modifier:\n                return False\n\n            # Perform the search.\n            replaced = self.history_next(self._history_prefix,\n                                            as_prefix=not shift_modifier)\n\n            # Emulate readline: keep the cursor position fixed for a prefix\n            # search. (We don't need to move the cursor to the end of the buffer\n            # in the other case because this happens automatically when the\n            # input buffer is set.)\n            if self._history_prefix and replaced:\n                cursor = self._get_prompt_cursor()\n                cursor.movePosition(QtGui.QTextCursor.Right,\n                                    n=len(self._history_prefix))\n                self._set_cursor(cursor)\n\n            return False\n\n        return True\n\n    #---------------------------------------------------------------------------\n    # 'HistoryConsoleWidget' public interface\n    #---------------------------------------------------------------------------\n\n    def history_previous(self, substring='', as_prefix=True):\n        \"\"\" If possible, set the input buffer to a previous history item.\n\n        Parameters:\n        -----------\n        substring : str, optional\n            If specified, search for an item with this substring.\n        as_prefix : bool, optional\n            If True, the substring must match at the beginning (default).\n\n        Returns:\n        --------\n        Whether the input buffer was changed.\n        \"\"\"\n        index = self._history_index\n        replace = False\n        while index > 0:\n            index -= 1\n            history = self._get_edited_history(index)\n            if (as_prefix and history.startswith(substring)) \\\n                or (not as_prefix and substring in history):\n                replace = True\n                break\n\n        if replace:\n            self._store_edits()\n            self._history_index = index\n            self.input_buffer = history\n\n        return replace\n\n    def history_next(self, substring='', as_prefix=True):\n        \"\"\" If possible, set the input buffer to a subsequent history item.\n\n        Parameters:\n        -----------\n        substring : str, optional\n            If specified, search for an item with this substring.\n        as_prefix : bool, optional\n            If True, the substring must match at the beginning (default).\n\n        Returns:\n        --------\n        Whether the input buffer was changed.\n        \"\"\"\n        index = self._history_index\n        replace = False\n        while index < len(self._history):\n            index += 1\n            history = self._get_edited_history(index)\n            if (as_prefix and history.startswith(substring)) \\\n                or (not as_prefix and substring in history):\n                replace = True\n                break\n\n        if replace:\n            self._store_edits()\n            self._history_index = index\n            self.input_buffer = history\n\n        return replace\n\n    def history_tail(self, n=10):\n        \"\"\" Get the local history list.\n\n        Parameters:\n        -----------\n        n : int\n            The (maximum) number of history items to get.\n        \"\"\"\n        return self._history[-n:]\n\n    def _request_update_session_history_length(self):\n        msg_id = self.kernel_manager.shell_channel.execute('',\n            silent=True,\n            user_expressions={\n                'hlen':'len(get_ipython().history_manager.input_hist_raw)',\n                }\n            )\n        self._request_info['execute'][msg_id] = self._ExecutionRequest(msg_id, 'save_magic')\n\n    def _handle_execute_reply(self, msg):\n        \"\"\" Handles replies for code execution, here only session history length\n        \"\"\"\n        msg_id = msg['parent_header']['msg_id']\n        info = self._request_info['execute'].pop(msg_id,None)\n        if info and info.kind == 'save_magic' and not self._hidden:\n            content = msg['content']\n            status = content['status']\n            if status == 'ok':\n                self._max_session_history=(int(content['user_expressions']['hlen']))\n\n    def save_magic(self):\n        # update the session history length\n        self._request_update_session_history_length()\n\n        file_name,extFilter = QtGui.QFileDialog.getSaveFileName(self,\n            \"Enter A filename\",\n            filter='Python File (*.py);; All files (*.*)'\n            )\n\n        # let's the user search/type for a file name, while the history length\n        # is fetched\n\n        if file_name:\n            hist_range, ok = QtGui.QInputDialog.getText(self,\n                'Please enter an interval of command to save',\n                'Saving commands:',\n                text=str('1-'+str(self._max_session_history))\n                )\n            if ok:\n                self.execute(\"%save\"+\" \"+file_name+\" \"+str(hist_range))\n\n    #---------------------------------------------------------------------------\n    # 'HistoryConsoleWidget' protected interface\n    #---------------------------------------------------------------------------\n\n    def _history_locked(self):\n        \"\"\" Returns whether history movement is locked.\n        \"\"\"\n        return (self.history_lock and\n                (self._get_edited_history(self._history_index) !=\n                 self.input_buffer) and\n                (self._get_prompt_cursor().blockNumber() !=\n                 self._get_end_cursor().blockNumber()))\n\n    def _get_edited_history(self, index):\n        \"\"\" Retrieves a history item, possibly with temporary edits.\n        \"\"\"\n        if index in self._history_edits:\n            return self._history_edits[index]\n        elif index == len(self._history):\n            return unicode()\n        return self._history[index]\n\n    def _set_history(self, history):\n        \"\"\" Replace the current history with a sequence of history items.\n        \"\"\"\n        self._history = list(history)\n        self._history_edits = {}\n        self._history_index = len(self._history)\n\n    def _store_edits(self):\n        \"\"\" If there are edits to the current input buffer, store them.\n        \"\"\"\n        current = self.input_buffer\n        if self._history_index == len(self._history) or \\\n                self._history[self._history_index] != current:\n            self._history_edits[self._history_index] = current\n", "path": "IPython/frontend/qt/console/history_console_widget.py"}]}