| 1 |
============================== |
| 2 |
Specific configuration details |
| 3 |
============================== |
| 4 |
|
| 5 |
.. _llm_suggestions: |
| 6 |
|
| 7 |
LLM Suggestions |
| 8 |
=============== |
| 9 |
|
| 10 |
Starting with 9.0, IPython will be able to use LLM providers to suggest code in |
| 11 |
the terminal. This requires a recent version of prompt_toolkit in order to allow |
| 12 |
multiline suggestions. There are currently a number of limitations, and feedback |
| 13 |
on the API is welcome. |
| 14 |
|
| 15 |
Unlike many of IPython features, this is not enabled by default and requires |
| 16 |
multiple configuration options to be set to properly work: |
| 17 |
|
| 18 |
- Set a keybinding to trigger LLM suggestions. Due to terminal limitations |
| 19 |
across platforms and emulators, it is difficult to provide a default |
| 20 |
keybinding. Note that not all keybindings are availables, in particular all |
| 21 |
the `Ctrl-Enter`, `Alt-backslash` and `Ctrl-Shift-Enter` are not available |
| 22 |
without integration with your terminal emulator. |
| 23 |
|
| 24 |
- Chose a LLM `provider`, usually from Jupyter-AI. This will be the interface |
| 25 |
between IPython itself, and the LLM – that may be local or in on a server. |
| 26 |
|
| 27 |
- Configure said provider with models, API keys, etc – this will depend on the |
| 28 |
provider, and you will have to refer to Jupyter-AI documentation, and/or your |
| 29 |
LLM documenatation. |
| 30 |
|
| 31 |
|
| 32 |
While setting up IPython to use a real LLM, you can refer to |
| 33 |
``examples/auto_suggest_llm.py`` that both provide an example of how to set up |
| 34 |
IPython to use a Fake LLM provider, this can help ensure that the full setup is |
| 35 |
working before switching to a real LLM provider. |
| 36 |
|
| 37 |
|
| 38 |
Setup a keybinding |
| 39 |
------------------ |
| 40 |
|
| 41 |
You may want to refer on how to setup a keybinding in IPython, but in short you |
| 42 |
want to bind the ``IPython:auto_suggest.llm_autosuggestion`` command to a |
| 43 |
keybinding, and have it active only when the default buffer isi focused, and |
| 44 |
when using the NavigableSuggestions suggestter (this is the default suggestter, |
| 45 |
the one that is history and LLM aware). Thus the ``navigable_suggestions & |
| 46 |
default_buffer_focused`` filter should be used. |
| 47 |
|
| 48 |
Usually ``Ctrl-Q`` on macos is an available shortcut, note that is does use |
| 49 |
``Ctrl``, and not ``Command``. |
| 50 |
|
| 51 |
The following example will bind ``Ctrl-Q`` to the ``llm_autosuggestion`` |
| 52 |
command, with the suggested filter:: |
| 53 |
|
| 54 |
c.TerminalInteractiveShell.shortcuts = [ |
| 55 |
{ |
| 56 |
"new_keys": ["c-q"], |
| 57 |
"command": "IPython:auto_suggest.llm_autosuggestion", |
| 58 |
"new_filter": "navigable_suggestions & default_buffer_focused", |
| 59 |
"create": True, |
| 60 |
}, |
| 61 |
] |
| 62 |
|
| 63 |
|
| 64 |
Choose a LLM provider |
| 65 |
--------------------- |
| 66 |
|
| 67 |
Set the ``TerminalInteractiveShell.llm_provider_class`` trait to the fully |
| 68 |
qualified name of the Provider you like, when testing from inside the IPython |
| 69 |
source tree, you can use |
| 70 |
``"examples.auto_suggest_llm.ExampleCompletionProvider"`` This will always |
| 71 |
stream an extract of the Little Prince by Antoine de Saint-Exupéry, and will not |
| 72 |
require any API key or real LLM. |
| 73 |
|
| 74 |
|
| 75 |
In your configuration file adapt the following line to your needs: |
| 76 |
|
| 77 |
.. code-block:: python |
| 78 |
|
| 79 |
c.TerminalInteractiveShell.llm_provider_class = "examples.auto_suggest_llm.ExampleCompletionProvider" |
| 80 |
|
| 81 |
Configure the provider |
| 82 |
---------------------- |
| 83 |
|
| 84 |
It the provider needs to be passed parameters at initialization, you can do so |
| 85 |
by setting the ``llm_construction_kwargs`` traitlet. |
| 86 |
|
| 87 |
.. code-block:: python |
| 88 |
|
| 89 |
c.TerminalInteractiveShell.llm_constructor_kwargs = {"model": "skynet"} |
| 90 |
|
| 91 |
This will depdend on the provider you chose, and you will have to refer to |
| 92 |
the provider documentation. |
| 93 |
|
| 94 |
Extra configuration may be needed by setting environment variables, this will |
| 95 |
again depend on the provider you chose, and you will have to refer to the |
| 96 |
provider documentation. |
| 97 |
|
| 98 |
LLM Context |
| 99 |
----------- |
| 100 |
|
| 101 |
The option ``c.TerminalInteractiveShell.llm_prefix_from_history`` controls the |
| 102 |
context the ``Provider`` gets when trying to complete. See the help of this |
| 103 |
options (``ipython --help-all``):: |
| 104 |
|
| 105 |
Fully Qualifed name of a function that takes an IPython history manager and |
| 106 |
return a prefix to pass the llm provider in addition to the current buffer |
| 107 |
text. |
| 108 |
|
| 109 |
You can use: |
| 110 |
|
| 111 |
- no_prefix |
| 112 |
- input_history |
| 113 |
|
| 114 |
As default value. `input_history` (default), will use all the input history |
| 115 |
of current IPython session |
| 116 |
|
| 117 |
|
| 118 |
|
| 119 |
|
| 120 |
|
| 121 |
|
| 122 |
.. _custom_prompts: |
| 123 |
|
| 124 |
Custom Prompts |
| 125 |
============== |
| 126 |
|
| 127 |
.. versionchanged:: 5.0 |
| 128 |
|
| 129 |
From IPython 5, prompts are produced as a list of Pygments tokens, which are |
| 130 |
tuples of (token_type, text). You can customise prompts by writing a method |
| 131 |
which generates a list of tokens. |
| 132 |
|
| 133 |
There are four kinds of prompt: |
| 134 |
|
| 135 |
* The **in** prompt is shown before the first line of input |
| 136 |
(default like ``In [1]:``). |
| 137 |
* The **continuation** prompt is shown before further lines of input |
| 138 |
(default like ``...:``). |
| 139 |
* The **rewrite** prompt is shown to highlight how special syntax has been |
| 140 |
interpreted (default like ``----->``). |
| 141 |
* The **out** prompt is shown before the result from evaluating the input |
| 142 |
(default like ``Out[1]:``). |
| 143 |
|
| 144 |
Custom prompts are supplied together as a class. If you want to customise only |
| 145 |
some of the prompts, inherit from :class:`IPython.terminal.prompts.Prompts`, |
| 146 |
which defines the defaults. The required interface is like this: |
| 147 |
|
| 148 |
.. class:: MyPrompts(shell) |
| 149 |
|
| 150 |
Prompt style definition. *shell* is a reference to the |
| 151 |
:class:`~.TerminalInteractiveShell` instance. |
| 152 |
|
| 153 |
.. method:: in_prompt_tokens() |
| 154 |
continuation_prompt_tokens(self, width=None) |
| 155 |
rewrite_prompt_tokens() |
| 156 |
out_prompt_tokens() |
| 157 |
|
| 158 |
Return the respective prompts as lists of ``(token_type, text)`` tuples. |
| 159 |
|
| 160 |
For continuation prompts, *width* is an integer representing the width of |
| 161 |
the prompt area in terminal columns. |
| 162 |
|
| 163 |
|
| 164 |
Here is an example Prompt class that will show the current working directory |
| 165 |
in the input prompt: |
| 166 |
|
| 167 |
.. code-block:: python |
| 168 |
|
| 169 |
from IPython.terminal.prompts import Prompts, Token |
| 170 |
import os |
| 171 |
|
| 172 |
class MyPrompt(Prompts): |
| 173 |
def in_prompt_tokens(self): |
| 174 |
return [(Token, os.getcwd()), |
| 175 |
(Token.Prompt, ' >>>')] |
| 176 |
|
| 177 |
To set the new prompt, assign it to the ``prompts`` attribute of the IPython |
| 178 |
shell: |
| 179 |
|
| 180 |
.. code-block:: python |
| 181 |
|
| 182 |
In [2]: ip = get_ipython() |
| 183 |
...: ip.prompts = MyPrompt(ip) |
| 184 |
|
| 185 |
/home/bob >>> # it works |
| 186 |
|
| 187 |
See ``IPython/example/utils/cwd_prompt.py`` for an example of how to write |
| 188 |
extensions to customise prompts. |
| 189 |
|
| 190 |
Inside IPython or in a startup script, you can use a custom prompts class |
| 191 |
by setting ``get_ipython().prompts`` to an *instance* of the class. |
| 192 |
In configuration, ``TerminalInteractiveShell.prompts_class`` may be set to |
| 193 |
either the class object, or a string of its full importable name. |
| 194 |
|
| 195 |
To include invisible terminal control sequences in a prompt, use |
| 196 |
``Token.ZeroWidthEscape`` as the token type. Tokens with this type are ignored |
| 197 |
when calculating the width. |
| 198 |
|
| 199 |
Colours in the prompt are determined by the token types and the highlighting |
| 200 |
style; see below for more details. The tokens used in the default prompts are |
| 201 |
``Prompt``, ``PromptNum``, ``OutPrompt`` and ``OutPromptNum``. |
| 202 |
|
| 203 |
.. _termcolour: |
| 204 |
|
| 205 |
Terminal Colors |
| 206 |
=============== |
| 207 |
|
| 208 |
.. versionchanged:: 9.0 |
| 209 |
|
| 210 |
IPython 9.0 changed almost all of the color handling, which is now referred to |
| 211 |
as **themes**. A Theme can do a bit more than purely colors, as it can handle |
| 212 |
bold, italic and basically any style that ``pygments`` support. Themes also |
| 213 |
support a number of ``Symbols``, which allows you to – for example – change the |
| 214 |
shape of the arrow that mark the current frame and line numbers in the debugger |
| 215 |
and the tracebacks. |
| 216 |
|
| 217 |
Most of the various IPython options that were used pre 9.0 have been renamed, |
| 218 |
with a exceptions a few, and most classes that deal with themes can, now take a |
| 219 |
``theme_name`` parameter. |
| 220 |
|
| 221 |
To reflect this, the ``--colors`` flag now is also aliased to ``--theme``. |
| 222 |
|
| 223 |
The default themes included are the same, except lowercase, for ease of typing. |
| 224 |
|
| 225 |
``'nocolor', 'neutral', 'linux', 'lightbg', 'gruvbox-dark'``, with the addition of ``'pride'`` |
| 226 |
to celebrate the inclusively of this project (I welcome update to the pride |
| 227 |
theme as I'm not a designer myself). |
| 228 |
|
| 229 |
In addition, the ``--theme=pride`` theme, is the first to make use of unicode |
| 230 |
symbols for the traceback separation line, and the debugger and traceback arrow, |
| 231 |
as well as making some use of ``bold``, and ``italic`` formatting, and not limit |
| 232 |
itself to the 16 base ANSI colors. |
| 233 |
|
| 234 |
Theme details |
| 235 |
------------- |
| 236 |
|
| 237 |
We encourage you to contribute themes, and to distribute them, |
| 238 |
while currently you need to modify source code to add a theme, it should be |
| 239 |
possible to load theme from Json, Yaml, or any other declarative file type. |
| 240 |
|
| 241 |
Since IPython 9.0, most of IPython internal code emit a sequence of `(Token |
| 242 |
Type, string)`, which is fed through pygments, and a theme is mapping from those |
| 243 |
token types to a style. For example: ``Token.Prompt : '#ansired underline'``, or |
| 244 |
``Token.Filename : 'bg:#A30262``. |
| 245 |
|
| 246 |
For simplicity, a theme can be derived from from a pygments style (which will |
| 247 |
give the basic code highlighting). |
| 248 |
|
| 249 |
A theme can also define a few symbols (see the source for how), for example |
| 250 |
``arrow_body``, and ``arrow_head``, can help customising line indicators. |
| 251 |
|
| 252 |
|
| 253 |
|
| 254 |
Colors in the pager |
| 255 |
------------------- |
| 256 |
|
| 257 |
On some systems, the default pager has problems with ANSI colour codes. |
| 258 |
To configure your default pager to allow these: |
| 259 |
|
| 260 |
1. Set the environment PAGER variable to ``less``. |
| 261 |
2. Set the environment LESS variable to ``-r`` (plus any other options |
| 262 |
you always want to pass to less by default). This tells less to |
| 263 |
properly interpret control sequences, which is how color |
| 264 |
information is given to your terminal. |
| 265 |
|
| 266 |
.. _editors: |
| 267 |
|
| 268 |
Editor configuration |
| 269 |
==================== |
| 270 |
|
| 271 |
IPython can integrate with text editors in a number of different ways: |
| 272 |
|
| 273 |
* Editors (such as `(X)Emacs`_, vim_ and TextMate_) can |
| 274 |
send code to IPython for execution. |
| 275 |
|
| 276 |
* IPython's ``%edit`` magic command can open an editor of choice to edit |
| 277 |
a code block. |
| 278 |
|
| 279 |
The %edit command (and its alias %ed) will invoke the editor set in your |
| 280 |
environment as :envvar:`EDITOR`. If this variable is not set, it will default |
| 281 |
to vi under Linux/Unix and to notepad under Windows. You may want to set this |
| 282 |
variable properly and to a lightweight editor which doesn't take too long to |
| 283 |
start (that is, something other than a new instance of Emacs). This way you |
| 284 |
can edit multi-line code quickly and with the power of a real editor right |
| 285 |
inside IPython. |
| 286 |
|
| 287 |
You can also control the editor by setting :attr:`TerminalInteractiveShell.editor` |
| 288 |
in :file:`ipython_config.py`. |
| 289 |
|
| 290 |
Vim |
| 291 |
--- |
| 292 |
|
| 293 |
Paul Ivanov's `vim-ipython <https://github.com/ivanov/vim-ipython>`_ provides |
| 294 |
powerful IPython integration for vim. |
| 295 |
|
| 296 |
.. _emacs: |
| 297 |
|
| 298 |
(X)Emacs |
| 299 |
-------- |
| 300 |
|
| 301 |
If you are a dedicated Emacs user, and want to use Emacs when IPython's |
| 302 |
``%edit`` magic command is called you should set up the Emacs server so that |
| 303 |
new requests are handled by the original process. This means that almost no |
| 304 |
time is spent in handling the request (assuming an Emacs process is already |
| 305 |
running). For this to work, you need to set your EDITOR environment variable |
| 306 |
to 'emacsclient'. The code below, supplied by Francois Pinard, can then be |
| 307 |
used in your :file:`.emacs` file to enable the server: |
| 308 |
|
| 309 |
.. code-block:: common-lisp |
| 310 |
|
| 311 |
(defvar server-buffer-clients) |
| 312 |
(when (and (fboundp 'server-start) (string-equal (getenv "TERM") 'xterm)) |
| 313 |
(server-start) |
| 314 |
(defun fp-kill-server-with-buffer-routine () |
| 315 |
(and server-buffer-clients (server-done))) |
| 316 |
(add-hook 'kill-buffer-hook 'fp-kill-server-with-buffer-routine)) |
| 317 |
|
| 318 |
Thanks to the work of Alexander Schmolck and Prabhu Ramachandran, |
| 319 |
currently (X)Emacs and IPython get along very well in other ways. |
| 320 |
|
| 321 |
With (X)EMacs >= 24, You can enable IPython in python-mode with: |
| 322 |
|
| 323 |
.. code-block:: common-lisp |
| 324 |
|
| 325 |
(require 'python) |
| 326 |
(setq python-shell-interpreter "ipython") |
| 327 |
|
| 328 |
.. _`(X)Emacs`: http://www.gnu.org/software/emacs/ |
| 329 |
.. _TextMate: http://macromates.com/ |
| 330 |
.. _vim: http://www.vim.org/ |
| 331 |
|
| 332 |
.. _custom_keyboard_shortcuts: |
| 333 |
|
| 334 |
Keyboard Shortcuts |
| 335 |
================== |
| 336 |
|
| 337 |
.. versionadded:: 8.11 |
| 338 |
|
| 339 |
You can modify, disable or modify keyboard shortcuts for IPython Terminal using |
| 340 |
:std:configtrait:`TerminalInteractiveShell.shortcuts` traitlet. |
| 341 |
|
| 342 |
The list of shortcuts is available in the Configuring IPython :ref:`terminal-shortcuts-list` section. |
| 343 |
|
| 344 |
Advanced configuration |
| 345 |
---------------------- |
| 346 |
|
| 347 |
.. versionchanged:: 5.0 |
| 348 |
|
| 349 |
Creating custom commands requires adding custom code to a |
| 350 |
:ref:`startup file <startup_files>`:: |
| 351 |
|
| 352 |
from IPython import get_ipython |
| 353 |
from prompt_toolkit.enums import DEFAULT_BUFFER |
| 354 |
from prompt_toolkit.keys import Keys |
| 355 |
from prompt_toolkit.filters import HasFocus, HasSelection, ViInsertMode, EmacsInsertMode |
| 356 |
|
| 357 |
ip = get_ipython() |
| 358 |
insert_mode = ViInsertMode() | EmacsInsertMode() |
| 359 |
|
| 360 |
def insert_unexpected(event): |
| 361 |
buf = event.current_buffer |
| 362 |
buf.insert_text('The Spanish Inquisition') |
| 363 |
# Register the shortcut if IPython is using prompt_toolkit |
| 364 |
if getattr(ip, 'pt_app', None): |
| 365 |
registry = ip.pt_app.key_bindings |
| 366 |
registry.add_binding(Keys.ControlN, |
| 367 |
filter=(HasFocus(DEFAULT_BUFFER) |
| 368 |
& ~HasSelection() |
| 369 |
& insert_mode))(insert_unexpected) |
| 370 |
|
| 371 |
|
| 372 |
Here is a second example that bind the key sequence ``j``, ``k`` to switch to |
| 373 |
VI input mode to ``Normal`` when in insert mode:: |
| 374 |
|
| 375 |
from IPython import get_ipython |
| 376 |
from prompt_toolkit.enums import DEFAULT_BUFFER |
| 377 |
from prompt_toolkit.filters import HasFocus, ViInsertMode |
| 378 |
from prompt_toolkit.key_binding.vi_state import InputMode |
| 379 |
|
| 380 |
ip = get_ipython() |
| 381 |
|
| 382 |
def switch_to_navigation_mode(event): |
| 383 |
vi_state = event.cli.vi_state |
| 384 |
vi_state.input_mode = InputMode.NAVIGATION |
| 385 |
|
| 386 |
if getattr(ip, 'pt_app', None): |
| 387 |
registry = ip.pt_app.key_bindings |
| 388 |
registry.add_binding(u'j',u'k', |
| 389 |
filter=(HasFocus(DEFAULT_BUFFER) |
| 390 |
& ViInsertMode()))(switch_to_navigation_mode) |
| 391 |
|
| 392 |
For more information on filters and what you can do with the ``event`` object, |
| 393 |
`see the prompt_toolkit docs |
| 394 |
<https://python-prompt-toolkit.readthedocs.io/en/latest/pages/asking_for_input.html#adding-custom-key-bindings>`__. |
| 395 |
|
| 396 |
|
| 397 |
Enter to execute |
| 398 |
---------------- |
| 399 |
|
| 400 |
In the Terminal IPython shell – which by default uses the ``prompt_toolkit`` |
| 401 |
interface, the semantic meaning of pressing the :kbd:`Enter` key can be |
| 402 |
ambiguous. In some case :kbd:`Enter` should execute code, and in others it |
| 403 |
should add a new line. IPython uses heuristics to decide whether to execute or |
| 404 |
insert a new line at cursor position. For example, if we detect that the current |
| 405 |
code is not valid Python, then the user is likely editing code and the right |
| 406 |
behavior is to likely to insert a new line. If the current code is a simple |
| 407 |
statement like `ord('*')`, then the right behavior is likely to execute. Though |
| 408 |
the exact desired semantics often varies from users to users. |
| 409 |
|
| 410 |
As the exact behavior of :kbd:`Enter` is ambiguous, it has been special cased |
| 411 |
to allow users to completely configure the behavior they like. Hence you can |
| 412 |
have enter always execute code. If you prefer fancier behavior, you need to get |
| 413 |
your hands dirty and read the ``prompt_toolkit`` and IPython documentation |
| 414 |
though. See :ghpull:`10500`, set the |
| 415 |
``c.TerminalInteractiveShell.handle_return`` option and get inspiration from the |
| 416 |
following example that only auto-executes the input if it begins with a bang or |
| 417 |
a modulo character (``!`` or ``%``). To use the following code, add it to your |
| 418 |
IPython configuration:: |
| 419 |
|
| 420 |
def custom_return(shell): |
| 421 |
|
| 422 |
"""This function is required by the API. It takes a reference to |
| 423 |
the shell, which is the same thing `get_ipython()` evaluates to. |
| 424 |
This function must return a function that handles each keypress |
| 425 |
event. That function, named `handle` here, references `shell` |
| 426 |
by closure.""" |
| 427 |
|
| 428 |
def handle(event): |
| 429 |
|
| 430 |
"""This function is called each time `Enter` is pressed, |
| 431 |
and takes a reference to a Prompt Toolkit event object. |
| 432 |
If the current input starts with a bang or modulo, then |
| 433 |
the input is executed, otherwise a newline is entered, |
| 434 |
followed by any spaces needed to auto-indent.""" |
| 435 |
|
| 436 |
# set up a few handy references to nested items... |
| 437 |
|
| 438 |
buffer = event.current_buffer |
| 439 |
document = buffer.document |
| 440 |
text = document.text |
| 441 |
|
| 442 |
if text.startswith('!') or text.startswith('%'): # execute the input... |
| 443 |
|
| 444 |
buffer.accept_action.validate_and_handle(event.cli, buffer) |
| 445 |
|
| 446 |
else: # insert a newline with auto-indentation... |
| 447 |
|
| 448 |
if document.line_count > 1: text = text[:document.cursor_position] |
| 449 |
indent = shell.check_complete(text)[1] |
| 450 |
buffer.insert_text('\n' + indent) |
| 451 |
|
| 452 |
# if you just wanted a plain newline without any indentation, you |
| 453 |
# could use `buffer.insert_text('\n')` instead of the lines above |
| 454 |
|
| 455 |
return handle |
| 456 |
|
| 457 |
c.TerminalInteractiveShell.handle_return = custom_return |