Skip to content


Prompt manager #507

merged 12 commits into from

4 participants

IPython member

I'm not expecting this to land before 0.11, but I thought I'd get it on the radar.

Every time I've wondered how prompts were produced, I've ended up rather confused. So this is an attempt at cleaning it up, with a new PromptManager class responsible for handling everything to do with the prompts. The critical part is its render method, which assembles the necessary information, then uses the string formatting introduced in Python 2.6 to fill in the prompt template.

I've expanded the definition of 'prompts' to include the auto_rewrite prompt ("------> " by default). So there are now four prompts: input, continuation, output, and rewrite.

This definition of prompts does not include input/output separators. For now, I've left those as attributes of the main InteractiveShell object.

IPython member

Thanks, this looks good.

This should be part of the general move removing all prompt/separator/ui-specific code from the InteractiveShell object to frontends, which definitely won't make it into 0.11.

IPython member

Rebased to bring it up to date.

IPython member

Can you hook up the qtconsole prompts to your new PromptManager as part of this?

I think making that change will help us make the right decisions on the PromptManager, since it will require support for things like HTML prompts without ANSI colors, divorcing the prompt from the InteractiveShell object, and executing things like os.getcwdu() either locally or in the kernel.

IPython member

Does it make sense to simply generate an HTML prompt in the kernel, and send it over? Or, more generally, have the frontend make a prompt_request with a template (which could be in any format), and the kernel replies with the filled in version?

IPython member

The kernel should probably know exactly nothing about prompts.

IPython member

Pragmatically, though, I suspect it will, at least to the extent of filling in slots in a template.

IPython member

Possibly, but hopefully not. Any such information should be accessible via the user_expressions/user_variables fields of execute requests.

IPython member

OK, that makes more sense, I didn't know about those fields. So the frontend needs to parse the format string, work out which variables it needs, and retrieve them from the backend. I think we still need to think a bit more about how this works, though, because a lot of the details that could go in the prompt aren't accessible from the user namespace without importing extra modules (like os or time).

IPython member

Yes, the idea was to have frontends request whatever information/expressions they want along with each new prompt (possibly including calls to things like os.getcwd() or time.time(), etc). Then they can build whichever display they want with this. In principle, the same kernel could be monitored by two clients that offer different levels of customizability for the prompts.

So the only thing the kernel supplies always is the execution counter, plus whatever variables or expressions may be requested in this form.

IPython member

Thomas, this overall looks pretty good, and even if it doesn't get us all the way in terms of restructuring the prompt system as we'd like to, it's probably worth merging now. The prompt rework will likely take a few passes until we have a full separation of duties between kernels (who just handle the namespace) and frontends (who present data from that namespace to the users in various ways, including possibly in a prompt).

But there's one thing we should think about: prompts were the one thing for which we kept using Itpl, because it allows the interpolation of arbitrary python expressions, while the new-style string formatting only allows simple variable name access, nothing else. And I know there are projects out there embedding ipython and making weird prompts that update dynamically with function calls, something like: "${some_function()[somearg]}> ".

So it seems your change removes that ability, right?

Now, I'm not totally against that, as long as we plan to complete the transition into a system that allows users to achieve their goal again, even if by different means (i.e. by asking the kernel for these things and using them to build the prompt).

IPython member

@fperez the EvalFormatter I used in the parallel templating code is a step towards exactly that. It doesn't support more than super-simple evals, but that shouldn't be hard. It's in utils.text.

For more arbitrary execution, you can do:

class EvalFormatter2(Formatter):
    def get_field(self, name, args, kwargs):
        v = eval(name, kwargs)
        return v, name

fmt = EvalFormatter2()
import os
ns = dict(os=os)
fmt.format(' we are in {os.getcwdu()}...', **ns)
# returns 'we are in /home/you/...'
IPython member

Plain string formatting can handle attribute.access and item[access], but specifically doesn't handle function calls. It should be trivial to use Min's EvalFormatter here instead.

IPython member

Note that neither my EvalFormatter in utils.text nor the one I typed up in 5 minutes above are finished implementations (at least something breaks in both), but it shouldn't be hard to get something that works.

IPython member

I guess one question is: do we really need to write a new one? I mean, Itpl may be old code, but it works and hasn't needed major updating. So what is the argument for effectively reimplementing itpl?

IPython member

Well, just that we can do essentially the same thing with a fraction of the code. Also, Itpl parses the string character-by-character in Python code, so we should get better performance from string formatting. I had the idea of dropping some of our external dependencies, and there are only a couple of places that we actually use Itpl. But I'm not going to push the issue.

IPython member

I don't think Itpl handles unicode at all. So either we need to reimplement Itpl with real string formatting (I doubt such a formatter would be more than ~20 lines), or we need to fix Itpl for unicode support.

IPython member

Fair enough, I'm ok with both of these arguments. I just wanted to see them :)

So Thomas, do you want to finish up a full EvalFormatter and we can merge this puppy?

IPython member

ps - we're on IRC now if you want to have a look at any of this right away.

IPython member

I could do with hitting the sack now. @minrk, what breaks in the current implementation of EvalFormatter? And is it a condition that we should care about? The only one I'm currently aware of is that you can't readily put a dict literal ({}) inside an expression in a string (it might work if you double both braces, although I've not checked).

IPython member

A few quick tests of EvalFormatter2 show that it probably supports everything we need for this PR:

In [2]: from string import Formatter 

class EvalFormatter2(Formatter): 
    def get_field(self, name, args, kwargs): 
        v = eval(name, kwargs) 
        return v, name 

fmt = EvalFormatter2() 
import os 
ns = dict(os=os) 
print fmt.format(' we are in {os.getcwdu()}...', **ns)

we are in /home/fperez/ipython/notebooks...

In [3]: print fmt.format(' we are in {os.getcwdu()+"hi"}...', **ns)

we are in /home/fperez/ipython/notebookshi...

In [5]: print fmt.format(' we are in {os.getcwdu()}, a is {a} and a0 is {a[0]}...', 

we are in /home/fperez/ipython/notebooks, a is [1, 2] and a0 is 1...

So @takluyver, it seems to me that if you update the code to use this (perhaps providing EvalFormatter2 as utils.text.FulEvalFormatter), we'd be good to go.

IPython member

Lots of stuff (function calls) don't work in the EvalFormatter in master. EvalFormatter2 seems to work for just about everything, but slicing definitely doesn't work: fmt.format("we are in ...{os.getcwdu()[-10:]}", os=os). It raises a SyntaxError, because the token is split at the colon for some reason, so os.getcwdu()[-10 is what gets eval'd.

Like I said above, I didn't spend more than 5-10 minutes on either of these, and I had never looked at any Formatter code before. So perhaps a more careful eye (and a test suite for various known Itpl use cases) would be prudent.

IPython member

OK, the issue is that ':' is part of the format specification, see Specifically:

Format Specifiers
    Each field can also specify an optional set of 'format
    specifiers' which can be used to adjust the format of that field.
    Format specifiers follow the field name, with a colon (':')
    character separating the two:

        "My name is {0:8}".format('Fred')

so the parser splits on ':' and returns the stuff after the colon as the format specifier.

Which means that this syntax simply is incompatible with arbitrary Python expressions.

That doesn't mean we can't use it, just that we'd be setting some restrictions on what kinds of things can go in there.

So Thomas, if you can do a little audit of our uses of Itpl and see if a more restrictive version based on EvalFormatter2 (hopefully with a nicer name) isn't a problem, then I have no issues with ditching itpl.

And I hope we'll find the time to complete the prompt machinery for frontends before 0.12.

IPython member

@fperez, I see, so possibly slicing is out, but it's still possible that even the colon-splitting is implemented in a method that we can easily override. If we can take over right at where the Formatter decides what to do with something inside '{...}', then we should be able to just eval that block, and be done.

I don't see any reason for the new one to not just replace EvalFormatter. I just called the example I tossed up EvalFormatter2 because it was my second 10-minute attempt at writing a formatter that evals code. There should be no need for more than one of these.

IPython member

Turns out it's actually pretty easy. I looked at the string.Formatter source, and the string docs, and all I have to do is override the _vformat method instead of get_field/get_value like I was doing. Now I can execute arbitrary code, and with a switch interpret ':' for slicing (disabling the format_spec part of fancy-formatting), or leave it as-is, preventing slicing (obviously you can't have both).

I'll do a PR soon, but I'm writing some tests first. For now a preview:

class EvalFormatter(Formatter):
    """A String Formatter that allows evaluation of simple expressions.

    Any time a format key is not found in the kwargs,
    it will be tried as an expression in the kwargs namespace.

    This is to be used in templating cases, such as the parallel batch
    script templates, where simple arithmetic on arguments is useful.


    In [1]: f = EvalFormatter()
    In [2]: f.format('{n/4}', n=8)
    Out[2]: '2'

    In [3]: f.format('{range(3)}')
    Out[3]: '[0, 1, 2]'

    In [4]: f.format('{3*2}')
    Out[4]: '6'


    # should we allow slicing by disabling the format_spec feature?
    allow_slicing = True

    # copied from Formatter._vformat with minor changes to allow eval
    # and replace the format_spec code with 
    def _vformat(self, format_string, args, kwargs, used_args, recursion_depth):
        if recursion_depth < 0:
            raise ValueError('Max string recursion exceeded')
        result = []
        for literal_text, field_name, format_spec, conversion in \

            # output the literal text
            if literal_text:

            # if there's a field, output it
            if field_name is not None:
                # this is some markup, find the object and do
                #  the formatting

                if self.allow_slicing:
                    # override format spec, to allow slicing:
                    field_name = ':'.join([field_name, format_spec])
                    format_spec = ''

                # eval the contents of the field for the object
                # to be formatted
                obj = eval(field_name, kwargs)

                # do any conversion on the resulting object
                obj = self.convert_field(obj, conversion)

                # expand the format spec, if needed
                format_spec = self._vformat(format_spec, args, kwargs,
                                            used_args, recursion_depth-1)

                # format the object and append to the result
                result.append(self.format_field(obj, format_spec))

        return ''.join(result)

And the difference between this and the base Formatter is tiny. If we disallow slicing, then the EvalFormatter2 above is cleaner and identical to this when allow_slicing=False.

[edit: obviously without the print statement I had initially]

IPython member

EvalFormatter updated: #716

Just pass the namespace in which you want the code to execute as the kwargs to format.

IPython member

OK, I've merged #716, so that @takluyver can update this one cleanly, to use the new EvalFormatter that has full slicing support for these situations.

We do need to make one design decision: for these kinds of expressions, do we value more the ability to do slicing or the ability to specify formatting (i.e. using the ':N' syntax for format specification)? I'm leaning towards the latter, both to keep this syntax in sync with normal Python formatting syntax and because fine-tuning formatting seems to be more likely to be useful in producing things like prompts than slicing. And if slicing is needed, people can always hide it behind a little utility function they can write, so it's not like slicing is impossible.

But I'd like to get some consensus before we pull the trigger on the final design for this part.

IPython member

I'd lean towards having format string enabled as well. If people do want slicing, they don't even need a utility function: x[slice(1,10)] is equivalent to x[1:10]. To give a particular use case, we could expose the timestamp as a datetime object, which can be formatted using the format string.

IPython member

It is a hard choice. The reason I discovered that slicing didn't work in the EvalFormatter2 above, is the first example I tried was a truncated version of cwd:

f.format("...{os.getcwd()[-10:]}", os=os)


you can actually get slicing by using slice objects, and never need a colon:

f.format("...{os.getcwd()[slice(-10,None,None)]}", os=os)

So you can get slice behavior without colon notation, if slightly inconvenient to type, but you can't get formatting-notation back in any reasonably way if you allow slicing. Further, if we don't want to support the slicing, the three-line EvalFormatter2 implementation above is much simpler, and probably preferable (and functionally identical when allow_slicing=False).

IPython member

OK, it seems we're in agreement that give how slice(a,b,c) is an option (if slightly less convenient), that's the way to go. In that case, we should perhaps go with the really simple EvalFormatter2 (renamed) and be done with it.

It's still useful to have the full one @minrk wrote, as it gives us a replacement for itpl with the modern python syntax and unicode support, but for this we should probably stick to the easy, comprehensible 3-liner.

IPython member

The only other place we're using Itpl is for expanding variables in %magic and !system calls. My gut feeling is that slicing is more useful than format strings there, but on the other hand we may want to keep closer to the standard Python format as people get more used to that.

@minrk: Should EvalFormatter2 replace the existing EvalFormatter that we shipped with 0.11? I think the main difference is that the existing EvalFormatter will treat {0} as referring to a positional argument, but EvalFormatter2 will treat it as a literal 0.

IPython member

I think the EvalFormatter has no need to support positional arguments. I would just replace the 0.11 EvalFormatter with EvalFormatter2 under the EvalFormatter name, and keep the big one that supports splitting around as a separate class (FullEvalFormatter, RichEvalFormatter, or something), just in case there is a desire to split args somewhere down the line.

I think of the EvalFormatter as evaluating code in a namespace. Positional args don't really make sense in that context.

The Itpl syntax is really much nicer for expanding variables (especially in the shell profile when it is restored), but it's not very Python, and as we have discovered doesn't play nice with unicode.

IPython member

@takluyver, did you see my message on-list about the idea of a frontend_ns to handle this issue? The more I think about it, the more it seems it's the way to go, as it gives us a clean solution to the prompt namespace question as well as a place for other things frontends may legitimately want to do in isolation from the user's namespace.

Now, we could go ahead and finish merging this before tackling that to ensure this doesn't bitrot away... What's your take?

IPython member

Hi Fernando, I did see your message - sorry, I've been a bit busy for the last week or so.

I think a frontend_ns makes sense, but a few questions about it:
1. Do we add frontend_variables & frontend_expressions fields to the execute request message? Or add another message type for accessing those?
2. What goes in the frontend_ns initially? I guess os and sys are obvious choices, along with the cwd-truncating functions currently defined for prompts. And something for timestamps. Anything else?
3. How can the frontend manipulate what's in the frontend_ns, e.g. for importing extra stuff? Can it send arbitrary Python code to be executed? Or a specific way to request an import? Or a way to "push" variables, perhaps from the user_ns (or even from the frontend, if it's in Python)?

As for merging this now - do you think this is the general structure of what we want to go forward with? It has the advantage that it makes the prompts code much more tractable for other people to work on. But if large parts are going to be redone, it might lead people down the wrong track. First, though, I need to sort out the various EvalFormatters. I'll get onto that now.

IPython member

I've reintroduced the very simple EvalFormatter, and made the slicing-enabled one FullEvalFormatter.

IPython member

No worries :)

  1. I'm thinking right now that the cleanest approach would be to use the standard execute request message, but simply add an optional field to it indicating the target namespace. Normal messages would go (as they do now) to the user_ns, but if frontend_ns is specified as the target, then they would get executed there.

  2. I'd say we don't put anything in there other than perhaps our prompt-manipulation machinery (since that's an obvious use case). With 1 above, frontends can simply execute import statements.

  3. Via 1, it's taken care of.

Currently our spec has the notion of user_variables and user_expressions. Those would be interpreted as variables and expressions in the execution namespace (perhaps we should change these names accordingly).

So basically, all we'd need is to add a new optional field, namespace, to the execute_request message. And the behavior would be such that if namespace != user_ns, then silent=True automatically, so that the user counter isn't auto-incremented behind the user's back.

How does this sound?

IPython member

So each namespace would have a standard string name, e.g. "user_local"? That seems a reasonable way to do it. Although I should note that technically you evaluate or execute code in two namespaces - local and global - just to complicate matters a little.

On the other hand, @ellisonbg has a point (from his email) that this should probably be kept as simple as possible, because we don't want the burden of complex code for a fairly minor feature. Is there a simpler way to handle prompts for the frontends? The idea I had previously was that the frontend would send a prompt template, and the kernel would return a formatted prompt (although the frontend still needs some flexibility so it can update prompt numbers).

IPython member
IPython member
IPython member
IPython member
IPython member

I think there are some good points here. If multiple frontends want to watch the value of a variable, then this data needs to be published on the iopub channel. There would need to be a way of registering variables that get published in this way after each execution. Also, there would need to be a way for those variables to become modified. For that the simplest thing is to use the user_ns, but you might want to compute some expression each time a variable is published (like os.getcwd()).

IPython member


What you are describing does indeed sound quite useful, and would suggest something along the lines of a 'state change' message. frontends could register names or expressions to check, and a check_state() call is made at the end of each execute request, publishing its results. Of course, this could add arbitrarily expensive computations to every execute request.

IPython member

I am also thinking about how we can design things to enable "Manipulate" style rich widgets to exist in the browser and receive updates as a computation progresses. This type of design might help in that context as well.

IPython member

Do we want to merge this PromptManager work into 0.12, since it seems like the user_expressions / zmq frontend prompts still has some discussion to resolve?

IPython member

@takluyver, just noticed this one needs a rebase... I can work on it later if you want, we might be able to flush this and your other two before 0.12...

IPython member

Rebased, run the tests on 2.7 and 3.2.

IPython member

@takluyver, I was going to start testing this puppy but a conflict seems to have appeared between yesterday and today, sorry... The conflict is tiny and I can fix it here while testing, but you may want to rebase this guy.

IPython member

Also note that the test suite doesn't pass anymore. Make sure to clear your .pyc files first to see the problem. It's the same reason as the conflict, simply that lib.pylabtools got moved to core.pylabtools.

IPython member

Sorry about those, it was my emergency merge last night that caused these. Fortunately it's a very easy fix.

IPython member

Other than the above small problems, here's a proposal for moving forward with this one. The code looks solid, and it's indeed already an improvement and cleanup of the prompt machinery, so I don't see a reason for holding it back further, risking more (and possibly non-trivial) merge conflicts popping up.

The only thing I see missing is a good description of the changes in the docs, since the format of the special expressions for prompts has now changed as we move away from itpl.

As far as the larger discussion on the whole frontend_ns ideas, we should probably not rush into it. @ellisonbg's caution is often wisely guided, and I find @minrk's argument about non-atomicity of a separate request and the possibility of it being 'backed up' in a busy kernel very compelling.

The whole question of how to let multiple clients interact with a kernel regarding 'sideband' information (i.e. stuff beyond the raw execution of pure code blocks for the user) is a very tricky design problem, and we're just feeling our way through it. So it's probably best to go in small steps and see what works. We can keep thinking about how to serve those needs slowly, and for now the user_var,exp system will probably be sufficient in most cases. We might add some functionality to register variables protected of deletion in %reset so that people with special prompts can safely use %reset.

How does that sound? We could move forward with this (pending rebase and docs) and then we'll see how things work out in practice with the prompt system, and whether we can continue to work just with user_vars/exp or not. Given we have no actual use of even those components yet, it may be premature to extend the system even further.

IPython member

I've just rebased. I've done my best to clear .pyc files, and import IPython.lib.pylabtools fails, but I'm not seeing any test failure. I'll look into docs later.

IPython member

Yes, pylabtools was moved to core. But that change was made in master already, so a rebase should pick it up for you; did it not?

IPython member
IPython member

Just to mention: I haven't got time to go through the docs tonight, but hopefully I can get to it tomorrow.

IPython member

OK, yes: working correctly is what you should expect. No problem with the docs, thanks for taking care of them.!

IPython member

I've updated the docs; let me know if you spot any other bits that need to be updated.

Still to do:

  • Update pysh profile to use new prompt config system.
  • Work out why %config doesn't seem to see PromptManager. Probably a trivial fix.
IPython member

I've tidied those bits up - I think this is all OK now.

IPython member

Is the test suite passing for you? I'm having some very bizarre problems with the test suite right now on my box at work, but they are odd enough that I think it's my problem and nothing with the codebase. What do you get?

IPython member
IPython member

OK, great. Let's merge this then as-is, and we'll continue mulling the deeper frontend namespace questions later. No point in holding this any further, lots of work has gone into it. Thanks!

@fperez fperez merged commit 272152c into ipython:master
IPython member

Thanks, Fernando. It's an odd feeling, not having an open pull request against IPython ;-).

IPython member
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
8 IPython/config/profile/pysh/
@@ -5,11 +5,11 @@
# and merge it into the current one.
load_subconfig('', profile='default')
-c.InteractiveShell.prompt_in1 = r'\C_LightGreen\u@\h\C_LightBlue[\C_LightCyan\Y1\C_LightBlue]\C_Green|\#> '
-c.InteractiveShell.prompt_in2 = r'\C_Green|\C_LightGreen\D\C_Green> '
-c.InteractiveShell.prompt_out = r'<\#> '
+c.PromptManager.in_template = r'{color.LightGreen}\u@\h{color.LightBlue}[{color.LightCyan}\Y1{color.LightBlue}]{color.Green}|\#> '
+c.PromptManager.in2_template = r'{color.Green}|{color.LightGreen}\D{color.Green}> '
+c.PromptManager.out_template = r'<\#> '
-c.InteractiveShell.prompts_pad_left = True
+c.PromptManager.justify = True
c.InteractiveShell.separate_in = ''
c.InteractiveShell.separate_out = ''
86 IPython/core/
@@ -25,7 +25,6 @@
import __builtin__
from IPython.config.configurable import Configurable
-from IPython.core import prompts
from IPython.utils import io
from IPython.utils.traitlets import Instance, List
from IPython.utils.warn import warn
@@ -34,32 +33,20 @@
# Main displayhook class
-# TODO: The DisplayHook class should be split into two classes, one that
-# manages the prompts and their synchronization and another that just does the
-# displayhook logic and calls into the prompt manager.
-# TODO: Move the various attributes (cache_size, colors, input_sep,
-# output_sep, output_sep2, ps1, ps2, ps_out, pad_left). Some of these are also
-# attributes of InteractiveShell. They should be on ONE object only and the
-# other objects should ask that one object for their values.
+# TODO: Move the various attributes (cache_size, [others now moved]). Some
+# of these are also attributes of InteractiveShell. They should be on ONE object
+# only and the other objects should ask that one object for their values.
class DisplayHook(Configurable):
"""The custom IPython displayhook to replace sys.displayhook.
This class does many things, but the basic idea is that it is a callable
that gets called anytime user code returns a value.
- Currently this class does more than just the displayhook logic and that
- extra logic should eventually be moved out of here.
shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
- def __init__(self, shell=None, cache_size=1000,
- colors='NoColor', input_sep='\n',
- output_sep='\n', output_sep2='',
- ps1 = None, ps2 = None, ps_out = None, pad_left=True,
- config=None):
+ def __init__(self, shell=None, cache_size=1000, config=None):
super(DisplayHook, self).__init__(shell=shell, config=config)
cache_size_min = 3
@@ -75,36 +62,10 @@ def __init__(self, shell=None, cache_size=1000,
self.do_full_cache = 1
self.cache_size = cache_size
- self.input_sep = input_sep
# we need a reference to the user-level namespace = shell
- # Set input prompt strings and colors
- if cache_size == 0:
- if ps1.find('%n') > -1 or ps1.find(r'\#') > -1 \
- or ps1.find(r'\N') > -1:
- ps1 = '>>> '
- if ps2.find('%n') > -1 or ps2.find(r'\#') > -1 \
- or ps2.find(r'\N') > -1:
- ps2 = '... '
- self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ')
- self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ')
- self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','')
- self.color_table = prompts.PromptColors
- self.prompt1 = prompts.Prompt1(self,sep=input_sep,prompt=self.ps1_str,
- pad_left=pad_left)
- self.prompt2 = prompts.Prompt2(self,prompt=self.ps2_str,pad_left=pad_left)
- self.prompt_out = prompts.PromptOut(self,sep='',prompt=self.ps_out_str,
- pad_left=pad_left)
- self.set_colors(colors)
- # Store the last prompt string each time, we need it for aligning
- # continuation and auto-rewrite prompts
- self.last_prompt = ''
- self.output_sep = output_sep
- self.output_sep2 = output_sep2
self._,self.__,self.___ = '','',''
# these are deliberately global:
@@ -115,32 +76,6 @@ def __init__(self, shell=None, cache_size=1000,
def prompt_count(self):
- def _set_prompt_str(self,p_str,cache_def,no_cache_def):
- if p_str is None:
- if self.do_full_cache:
- return cache_def
- else:
- return no_cache_def
- else:
- return p_str
- def set_colors(self, colors):
- """Set the active color scheme and configure colors for the three
- prompt subsystems."""
- # FIXME: This modifying of the global prompts.prompt_specials needs
- # to be fixed. We need to refactor all of the prompts stuff to use
- # proper configuration and traits notifications.
- if colors.lower()=='nocolor':
- prompts.prompt_specials = prompts.prompt_specials_nocolor
- else:
- prompts.prompt_specials = prompts.prompt_specials_color
- self.color_table.set_active_scheme(colors)
- self.prompt1.set_colors()
- self.prompt2.set_colors()
- self.prompt_out.set_colors()
# Methods used in __call__. Override these methods to modify the behavior
# of the displayhook.
@@ -180,8 +115,8 @@ def write_output_prompt(self):
# Use write, not print which adds an extra space.
- io.stdout.write(self.output_sep)
- outprompt = str(self.prompt_out)
+ io.stdout.write(
+ outprompt ='out')
if self.do_full_cache:
@@ -235,11 +170,12 @@ def write_format_data(self, format_dict):
# So that multi-line strings line up with the left column of
# the screen, instead of having the output prompt mess up
# their first line.
- # We use the ps_out_str template instead of the expanded prompt
+ # We use the prompt template instead of the expanded prompt
# because the expansion may add ANSI escapes that will interfere
# with our ability to determine whether or not we should add
# a newline.
- if self.ps_out_str and not self.ps_out_str.endswith('\n'):
+ prompt_template =
+ if prompt_template and not prompt_template.endswith('\n'):
# But avoid extraneous empty lines.
result_repr = '\n' + result_repr
@@ -286,7 +222,7 @@ def log_output(self, format_dict):
def finish_displayhook(self):
"""Finish up all displayhook activities."""
- io.stdout.write(self.output_sep2)
+ io.stdout.write(
def __call__(self, result=None):
9 IPython/core/
@@ -51,7 +51,7 @@ def calljed(self,filename, linenum):
__all__ = ['editor', 'fix_error_editor', 'synchronize_with_editor',
'input_prefilter', 'shutdown_hook', 'late_startup_hook',
- 'generate_prompt', 'show_in_pager','pre_prompt_hook',
+ 'show_in_pager','pre_prompt_hook',
'pre_run_code_hook', 'clipboard_get']
def editor(self,filename, linenum=None):
@@ -187,13 +187,6 @@ def late_startup_hook(self):
#print "default startup hook ok" # dbg
-def generate_prompt(self, is_continuation):
- """ calculate and return a string with the prompt to display """
- if is_continuation:
- return str(self.displayhook.prompt2)
- return str(self.displayhook.prompt1)
def show_in_pager(self,s):
""" Run a string through pager """
# raising TryNext here will use the default paging functionality
16 IPython/core/
@@ -63,6 +63,7 @@
from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
from IPython.core.profiledir import ProfileDir
from IPython.core.pylabtools import pylab_activate
+from IPython.core.prompts import PromptManager
from IPython.external.Itpl import ItplNS
from IPython.utils import PyColorize
from IPython.utils import io
@@ -594,10 +595,8 @@ def init_io(self):
io.stderr = io.IOStream(sys.stderr)
def init_prompts(self):
- # TODO: This is a pass for now because the prompts are managed inside
- # the DisplayHook. Once there is a separate prompt manager, this
- # will initialize that object and all prompt related information.
- pass
+ self.prompt_manager = PromptManager(shell=self, config=self.config)
+ self.configurables.append(self.prompt_manager)
def init_display_formatter(self):
self.display_formatter = DisplayFormatter(config=self.config)
@@ -613,13 +612,6 @@ def init_displayhook(self):
- input_sep = self.separate_in,
- output_sep = self.separate_out,
- output_sep2 = self.separate_out2,
- ps1 = self.prompt_in1,
- ps2 = self.prompt_in2,
- ps_out = self.prompt_out,
- pad_left = self.prompts_pad_left
# This is a context manager that installs/revmoes the displayhook at
@@ -2149,7 +2141,7 @@ def auto_rewrite_input(self, cmd):
after the user's input prompt. This helps the user understand that the
input line was transformed automatically by IPython.
- rw = self.displayhook.prompt1.auto_rewrite() + cmd
+ rw = self.prompt_manager.render('rewrite') + cmd
# plain ascii works better w/ pyreadline, on some machines, so
38 IPython/core/
@@ -2554,12 +2554,12 @@ def color_switch_err(name):
# Set prompt colors
- shell.displayhook.set_colors(new_scheme)
+ shell.prompt_manager.color_scheme = new_scheme
shell.colors = \
- shell.displayhook.color_table.active_scheme_name
+ shell.prompt_manager.color_scheme_table.active_scheme_name
# Set exception colors
shell.InteractiveTB.set_colors(scheme = new_scheme)
@@ -3237,7 +3237,7 @@ def magic_doctest_mode(self,parameter_s=''):
# Shorthands
shell =
- oc = shell.displayhook
+ pm = shell.prompt_manager
meta = shell.meta
disp_formatter =
ptformatter = disp_formatter.formatters['text/plain']
@@ -3252,23 +3252,23 @@ def magic_doctest_mode(self,parameter_s=''):
- save_dstore('rc_prompts_pad_left',shell.prompts_pad_left)
+ save_dstore('rc_prompts_pad_left',pm.justify)
+ save_dstore('prompt_templates',(pm.in_template, pm.in2_template, pm.out_template))
if mode == False:
# turn on
- oc.prompt1.p_template = '>>> '
- oc.prompt2.p_template = '... '
- oc.prompt_out.p_template = ''
+ pm.in_template = '>>> '
+ pm.in2_template = '... '
+ pm.out_template = ''
# Prompt separators like plain python
- oc.input_sep = oc.prompt1.sep = ''
- oc.output_sep = ''
- oc.output_sep2 = ''
+ shell.separate_in = ''
+ shell.separate_out = ''
+ shell.separate_out2 = ''
- oc.prompt1.pad_left = oc.prompt2.pad_left = \
- oc.prompt_out.pad_left = False
+ pm.justify = False
ptformatter.pprint = False
disp_formatter.plain_text_only = True
@@ -3276,17 +3276,14 @@ def magic_doctest_mode(self,parameter_s=''):
# turn off
- oc.prompt1.p_template = shell.prompt_in1
- oc.prompt2.p_template = shell.prompt_in2
- oc.prompt_out.p_template = shell.prompt_out
+ pm.in_template, pm.in2_template, pm.out_template = dstore.prompt_templates
- oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in
+ shell.separate_in = dstore.rc_separate_in
- oc.output_sep = dstore.rc_separate_out
- oc.output_sep2 = dstore.rc_separate_out2
+ shell.separate_out = dstore.rc_separate_out
+ shell.separate_out2 = dstore.rc_separate_out2
- oc.prompt1.pad_left = oc.prompt2.pad_left = \
- oc.prompt_out.pad_left = dstore.rc_prompts_pad_left
+ pm.justify = dstore.rc_prompts_pad_left
ptformatter.pprint = dstore.rc_pprint
disp_formatter.plain_text_only = dstore.rc_plain_text_only
@@ -3603,6 +3600,7 @@ def magic_config(self, s):
+ PromptManager
To view what is configurable on a given class, just pass the class name::
498 IPython/core/
@@ -5,6 +5,7 @@
* Fernando Perez
* Brian Granger
+* Thomas Kluyver
@@ -23,20 +24,23 @@
import re
import socket
import sys
+import time
+from IPython.config.configurable import Configurable
from IPython.core import release
-from IPython.external.Itpl import ItplNS
from IPython.utils import coloransi
+from IPython.utils.traitlets import (Unicode, Instance, Dict, Bool, Int)
# Color schemes for prompts
-PromptColors = coloransi.ColorSchemeTable()
InputColors = coloransi.InputTermColors # just a shorthand
Colors = coloransi.TermColors # just a shorthand
+color_lists = dict(normal=Colors(), inp=InputColors(), nocolor=coloransi.NoColors())
+PColNoColors = coloransi.ColorScheme(
in_prompt = InputColors.NoColor, # Input prompt
in_number = InputColors.NoColor, # Input prompt number
@@ -47,10 +51,10 @@
out_number = Colors.NoColor, # Output prompt number
normal = Colors.NoColor # color off (usu. Colors.Normal)
- ))
+ )
# make some schemes as instances so we can copy them for modification easily:
-__PColLinux = coloransi.ColorScheme(
+PColLinux = coloransi.ColorScheme(
in_prompt = InputColors.Green,
in_number = InputColors.LightGreen,
@@ -62,25 +66,35 @@
normal = Colors.Normal
-# Don't forget to enter it into the table!
# Slightly modified Linux for light backgrounds
-__PColLightBG = __PColLinux.copy('LightBG')
+PColLightBG = PColLinux.copy('LightBG')
in_prompt = InputColors.Blue,
in_number = InputColors.LightBlue,
in_prompt2 = InputColors.Blue
-del Colors,InputColors
# Utilities
+class LazyEvaluate(object):
+ """This is used for formatting strings with values that need to be updated
+ at that time, such as the current time or working directory."""
+ def __init__(self, func, *args, **kwargs):
+ self.func = func
+ self.args = args
+ self.kwargs = kwargs
+ def __call__(self, **kwargs):
+ self.kwargs.update(kwargs)
+ return self.func(*self.args, **self.kwargs)
+ def __str__(self):
+ return str(self())
def multiple_replace(dict, text):
""" Replace in 'text' all occurences of any key in the given
dictionary by its corresponding value. Returns the new string."""
@@ -121,51 +135,43 @@ def multiple_replace(dict, text):
USER = os.environ.get("USER")
HOSTNAME = socket.gethostname()
-ROOT_SYMBOL = "$#"['nt' or os.getuid()==0]
+ROOT_SYMBOL = "#" if ('nt' or os.getuid()==0) else "$"
-prompt_specials_color = {
+prompt_abbreviations = {
# Prompt/history count
- '%n' : '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
- r'\#': '${self.col_num}' '${self.cache.prompt_count}' '${self.col_p}',
+ '%n' : '{color.number}' '{count}' '{color.prompt}',
+ r'\#': '{color.number}' '{count}' '{color.prompt}',
# Just the prompt counter number, WITHOUT any coloring wrappers, so users
# can get numbers displayed in whatever color they want.
- r'\N': '${self.cache.prompt_count}',
+ r'\N': '{count}',
# Prompt/history count, with the actual digits replaced by dots. Used
# mainly in continuation prompts (prompt_in2)
- #r'\D': '${"."*len(str(self.cache.prompt_count))}',
- # More robust form of the above expression, that uses the __builtin__
- # module. Note that we can NOT use __builtins__ (note the 's'), because
- # that can either be a dict or a module, and can even mutate at runtime,
- # depending on the context (Python makes no guarantees on it). In
- # contrast, __builtin__ is always a module object, though it must be
- # explicitly imported.
- r'\D': '${"."*__builtin__.len(__builtin__.str(self.cache.prompt_count))}',
+ r'\D': '{dots}',
- # Current working directory
- r'\w': '${os.getcwd()}',
# Current time
- r'\t' : '${time.strftime("%H:%M:%S")}',
+ r'\T' : '{time}',
+ # Current working directory
+ r'\w': '{cwd}',
# Basename of current working directory.
# (use os.sep to make this portable across OSes)
- r'\W' : '${os.getcwd().split("%s")[-1]}' % os.sep,
+ r'\W' : '{cwd_last}',
# These X<N> are an extension to the normal bash prompts. They return
# N terms of the path, after replacing $HOME with '~'
- r'\X0': '${os.getcwd().replace("%s","~")}' % HOME,
- r'\X1': '${self.cwd_filt(1)}',
- r'\X2': '${self.cwd_filt(2)}',
- r'\X3': '${self.cwd_filt(3)}',
- r'\X4': '${self.cwd_filt(4)}',
- r'\X5': '${self.cwd_filt(5)}',
+ r'\X0': '{cwd_x[0]}',
+ r'\X1': '{cwd_x[1]}',
+ r'\X2': '{cwd_x[2]}',
+ r'\X3': '{cwd_x[3]}',
+ r'\X4': '{cwd_x[4]}',
+ r'\X5': '{cwd_x[5]}',
# Y<N> are similar to X<N>, but they show '~' if it's the directory
# N+1 in the list. Somewhat like %cN in tcsh.
- r'\Y0': '${self.cwd_filt2(0)}',
- r'\Y1': '${self.cwd_filt2(1)}',
- r'\Y2': '${self.cwd_filt2(2)}',
- r'\Y3': '${self.cwd_filt2(3)}',
- r'\Y4': '${self.cwd_filt2(4)}',
- r'\Y5': '${self.cwd_filt2(5)}',
+ r'\Y0': '{cwd_y[0]}',
+ r'\Y1': '{cwd_y[1]}',
+ r'\Y2': '{cwd_y[2]}',
+ r'\Y3': '{cwd_y[3]}',
+ r'\Y4': '{cwd_y[4]}',
+ r'\Y5': '{cwd_y[5]}',
# Hostname up to first .
# Full hostname
@@ -184,253 +190,189 @@ def multiple_replace(dict, text):
-# A copy of the prompt_specials dictionary but with all color escapes removed,
-# so we can correctly compute the prompt length for the auto_rewrite method.
-prompt_specials_nocolor = prompt_specials_color.copy()
-prompt_specials_nocolor['%n'] = '${self.cache.prompt_count}'
-prompt_specials_nocolor[r'\#'] = '${self.cache.prompt_count}'
-# Add in all the InputTermColors color escapes as valid prompt characters.
-# They all get added as \\C_COLORNAME, so that we don't have any conflicts
-# with a color name which may begin with a letter used by any other of the
-# allowed specials. This of course means that \\C will never be allowed for
-# anything else.
-input_colors = coloransi.InputTermColors
-for _color in dir(input_colors):
- if _color[0] != '_':
- c_name = r'\C_'+_color
- prompt_specials_color[c_name] = getattr(input_colors,_color)
- prompt_specials_nocolor[c_name] = ''
-# we default to no color for safety. Note that prompt_specials is a global
-# variable used by all prompt objects.
-prompt_specials = prompt_specials_nocolor
# More utilities
-def str_safe(arg):
- """Convert to a string, without ever raising an exception.
- If str(arg) fails, <ERROR: ... > is returned, where ... is the exception
- error message."""
- try:
- out = str(arg)
- except UnicodeError:
- try:
- out = arg.encode('utf_8','replace')
- except Exception,msg:
- # let's keep this little duplication here, so that the most common
- # case doesn't suffer from a double try wrapping.
- out = '<ERROR: %s>' % msg
- except Exception,msg:
- out = '<ERROR: %s>' % msg
- #raise # dbg
- return out
+def cwd_filt(depth):
+ """Return the last depth elements of the current working directory.
-# Prompt classes
+ $HOME is always replaced with '~'.
+ If depth==0, the full path is returned."""
-class BasePrompt(object):
- """Interactive prompt similar to Mathematica's."""
- def _get_p_template(self):
- return self._p_template
- def _set_p_template(self,val):
- self._p_template = val
- self.set_p_str()
- p_template = property(_get_p_template,_set_p_template,
- doc='Template for prompt string creation')
- def __init__(self, cache, sep, prompt, pad_left=False):
- # Hack: we access information about the primary prompt through the
- # cache argument. We need this, because we want the secondary prompt
- # to be aligned with the primary one. Color table info is also shared
- # by all prompt classes through the cache. Nice OO spaghetti code!
- self.cache = cache
- self.sep = sep
- # regexp to count the number of spaces at the end of a prompt
- # expression, useful for prompt auto-rewriting
- self.rspace = re.compile(r'(\s*)$')
- # Flag to left-pad prompt strings to match the length of the primary
- # prompt
- self.pad_left = pad_left
- # Set template to create each actual prompt (where numbers change).
- # Use a property
- self.p_template = prompt
- self.set_p_str()
- def set_p_str(self):
- """ Set the interpolating prompt strings.
- This must be called every time the color settings change, because the
- prompt_specials global may have changed."""
- import os,time # needed in locals for prompt string handling
- loc = locals()
- try:
- self.p_str = ItplNS('%s%s%s' %
- ('${self.sep}${self.col_p}',
- multiple_replace(prompt_specials, self.p_template),
- '${self.col_norm}'),,loc)
- self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
- self.p_template),
- except:
- print "Illegal prompt template (check $ usage!):",self.p_template
- self.p_str = self.p_template
- self.p_str_nocolor = self.p_template
- def write(self, msg):
- sys.stdout.write(msg)
- return ''
+ cwd = os.getcwd().replace(HOME,"~")
+ out = os.sep.join(cwd.split(os.sep)[-depth:])
+ return out or os.sep
- def __str__(self):
- """Return a string form of the prompt.
- This for is useful for continuation and output prompts, since it is
- left-padded to match lengths with the primary one (if the
- self.pad_left attribute is set)."""
- out_str = str_safe(self.p_str)
- if self.pad_left:
- # We must find the amount of padding required to match lengths,
- # taking the color escapes (which are invisible on-screen) into
- # account.
- esc_pad = len(out_str) - len(str_safe(self.p_str_nocolor))
- format = '%%%ss' % (len(str(self.cache.last_prompt))+esc_pad)
- return format % out_str
- else:
- return out_str
+def cwd_filt2(depth):
+ """Return the last depth elements of the current working directory.
- # these path filters are put in as methods so that we can control the
- # namespace where the prompt strings get evaluated
- def cwd_filt(self, depth):
- """Return the last depth elements of the current working directory.
+ $HOME is always replaced with '~'.
+ If depth==0, the full path is returned."""
- $HOME is always replaced with '~'.
- If depth==0, the full path is returned."""
+ full_cwd = os.getcwd()
+ cwd = full_cwd.replace(HOME,"~").split(os.sep)
+ if '~' in cwd and len(cwd) == depth+1:
+ depth += 1
+ drivepart = ''
+ if sys.platform == 'win32' and len(cwd) > depth:
+ drivepart = os.path.splitdrive(full_cwd)[0]
+ out = drivepart + '/'.join(cwd[-depth:])
- cwd = os.getcwd().replace(HOME,"~")
- out = os.sep.join(cwd.split(os.sep)[-depth:])
- if out:
- return out
- else:
- return os.sep
+ return out or os.sep
- def cwd_filt2(self, depth):
- """Return the last depth elements of the current working directory.
- $HOME is always replaced with '~'.
- If depth==0, the full path is returned."""
- full_cwd = os.getcwd()
- cwd = full_cwd.replace(HOME,"~").split(os.sep)
- if '~' in cwd and len(cwd) == depth+1:
- depth += 1
- drivepart = ''
- if sys.platform == 'win32' and len(cwd) > depth:
- drivepart = os.path.splitdrive(full_cwd)[0]
- out = drivepart + '/'.join(cwd[-depth:])
+# Prompt classes
- if out:
- return out
+lazily_evaluate = {'time': LazyEvaluate(time.strftime, "%H:%M:%S"),
+ 'cwd': LazyEvaluate(os.getcwd),
+ 'cwd_last': LazyEvaluate(lambda: os.getcwd().split(os.sep)[-1]),
+ 'cwd_x': [LazyEvaluate(lambda: os.getcwd().replace("%s","~"))] +\
+ [LazyEvaluate(cwd_filt, x) for x in range(1,6)],
+ 'cwd_y': [LazyEvaluate(cwd_filt2, x) for x in range(6)]
+ }
+class PromptManager(Configurable):
+ """This is the primary interface for producing IPython's prompts."""
+ shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
+ color_scheme_table = Instance(coloransi.ColorSchemeTable)
+ color_scheme = Unicode('Linux', config=True)
+ def _color_scheme_changed(self, name, new_value):
+ self.color_scheme_table.set_active_scheme(new_value)
+ for pname in ['in', 'in2', 'out', 'rewrite']:
+ # We need to recalculate the number of invisible characters
+ self.update_prompt(pname)
+ lazy_evaluate_fields = Dict(help="""
+ This maps field names used in the prompt templates to functions which
+ will be called when the prompt is rendered. This allows us to include
+ things like the current time in the prompts. Functions are only called
+ if they are used in the prompt.
+ """)
+ def _lazy_evaluate_fields_default(self): return lazily_evaluate.copy()
+ in_template = Unicode('In [\\#]: ', config=True)
+ in2_template = Unicode(' .\\D.: ', config=True)
+ out_template = Unicode('Out[\\#]: ', config=True)
+ rewrite_template = Unicode("------> ", config=True)
+ justify = Bool(True, config=True, help="""
+ If True (default), each prompt will be right-aligned with the
+ preceding one.
+ """)
+ # We actually store the expanded templates here:
+ templates = Dict()
+ # The number of characters in the last prompt rendered, not including
+ # colour characters.
+ width = Int()
+ # The number of characters in each prompt which don't contribute to width
+ invisible_chars = Dict()
+ def _invisible_chars_default(self):
+ return {'in': 0, 'in2': 0, 'out': 0, 'rewrite': 0}
+ def __init__(self, shell, config=None):
+ super(PromptManager, self).__init__(shell=shell, config=config)
+ # Prepare colour scheme table
+ self.color_scheme_table = coloransi.ColorSchemeTable([PColNoColors,
+ PColLinux, PColLightBG], self.color_scheme)
+ # Prepare templates
+ self.update_prompt('in', self.in_template)
+ self.update_prompt('in2', self.in2_template)
+ self.update_prompt('out', self.out_template)
+ self.update_prompt('rewrite', self.rewrite_template)
+ self.on_trait_change(self._update_prompt_trait, ['in_template',
+ 'in2_template', 'out_template', 'rewrite_template'])
+ def update_prompt(self, name, new_template=None):
+ """This is called when a prompt template is updated. It processes
+ abbreviations used in the prompt template (like \#) and calculates how
+ many invisible characters (ANSI colour escapes) the resulting prompt
+ contains.
+ It is also called for each prompt on changing the colour scheme. In both
+ cases, traitlets should take care of calling this automatically.
+ """
+ if new_template is not None:
+ self.templates[name] = multiple_replace(prompt_abbreviations, new_template)
+ invis_chars = len(self.render(name, color=True, just=False)) - \
+ len(self.render(name, color=False, just=False))
+ self.invisible_chars[name] = invis_chars
+ def _update_prompt_trait(self, traitname, new_template):
+ name = traitname[:-9] # Cut off '_template'
+ self.update_prompt(name, new_template)
+ def render(self, name, color=True, just=None, **kwargs):
+ """
+ Render the selected prompt.
+ Parameters
+ ----------
+ name : str
+ Which prompt to render. One of 'in', 'in2', 'out', 'rewrite'
+ color : bool
+ If True (default), include ANSI escape sequences for a coloured prompt.
+ just : bool
+ If True, justify the prompt to the width of the last prompt. The
+ default is stored in self.justify.
+ **kwargs :
+ Additional arguments will be passed to the string formatting operation,
+ so they can override the values that would otherwise fill in the
+ template.
+ Returns
+ -------
+ A string containing the rendered prompt.
+ """
+ if color:
+ scheme = self.color_scheme_table.active_colors
+ if name=='out':
+ colors = color_lists['normal']
+ colors.number, colors.prompt, colors.normal = \
+ scheme.out_number, scheme.out_prompt, scheme.normal
+ elif name=='rewrite':
+ colors = color_lists['normal']
+ # We need a non-input version of these escapes
+ colors.number = scheme.in_number.replace("\001","").replace("\002","")
+ colors.prompt = scheme.in_prompt.replace("\001","").replace("\002","")
+ colors.normal = scheme.normal
+ else:
+ colors = color_lists['inp']
+ colors.number, colors.prompt, colors.normal = \
+ scheme.in_number, scheme.in_prompt, scheme.in_normal
+ if name=='in2':
+ colors.prompt = scheme.in_prompt2
- return os.sep
- def __nonzero__(self):
- """Implement boolean behavior.
- Checks whether the p_str attribute is non-empty"""
- return bool(self.p_template)
-class Prompt1(BasePrompt):
- """Input interactive prompt similar to Mathematica's."""
- def __init__(self, cache, sep='\n', prompt='In [\\#]: ', pad_left=True):
- BasePrompt.__init__(self, cache, sep, prompt, pad_left)
- def set_colors(self):
- self.set_p_str()
- Colors = self.cache.color_table.active_colors # shorthand
- self.col_p = Colors.in_prompt
- self.col_num = Colors.in_number
- self.col_norm = Colors.in_normal
- # We need a non-input version of these escapes for the '--->'
- # auto-call prompts used in the auto_rewrite() method.
- self.col_p_ni = self.col_p.replace('\001','').replace('\002','')
- self.col_norm_ni = Colors.normal
- def __str__(self):
- self.cache.last_prompt = str_safe(self.p_str_nocolor).split('\n')[-1]
- return str_safe(self.p_str)
- def auto_rewrite(self):
- """Return a string of the form '--->' which lines up with the previous
- input string. Useful for systems which re-write the user input when
- handling automatically special syntaxes."""
- curr = str(self.cache.last_prompt)
- nrspaces = len(
- return '%s%s>%s%s' % (self.col_p_ni,'-'*(len(curr)-nrspaces-1),
- ' '*nrspaces,self.col_norm_ni)
-class PromptOut(BasePrompt):
- """Output interactive prompt similar to Mathematica's."""
- def __init__(self, cache, sep='', prompt='Out[\\#]: ', pad_left=True):
- BasePrompt.__init__(self, cache, sep, prompt, pad_left)
- if not self.p_template:
- self.__str__ = lambda: ''
- def set_colors(self):
- self.set_p_str()
- Colors = self.cache.color_table.active_colors # shorthand
- self.col_p = Colors.out_prompt
- self.col_num = Colors.out_number
- self.col_norm = Colors.normal
-class Prompt2(BasePrompt):
- """Interactive continuation prompt."""
- def __init__(self, cache, prompt=' .\\D.: ', pad_left=True):
- self.cache = cache
- self.p_template = prompt
- self.pad_left = pad_left
- self.set_p_str()
- def set_p_str(self):
- import os,time # needed in locals for prompt string handling
- loc = locals()
- self.p_str = ItplNS('%s%s%s' %
- ('${self.col_p2}',
- multiple_replace(prompt_specials, self.p_template),
- '$self.col_norm'),
- self.p_str_nocolor = ItplNS(multiple_replace(prompt_specials_nocolor,
- self.p_template),
- def set_colors(self):
- self.set_p_str()
- Colors = self.cache.color_table.active_colors
- self.col_p2 = Colors.in_prompt2
- self.col_norm = Colors.in_normal
- # FIXME (2004-06-16) HACK: prevent crashes for users who haven't
- # updated their prompt_in2 definitions. Remove eventually.
- self.col_p = Colors.out_prompt
- self.col_num = Colors.out_number
+ # No color
+ colors = color_lists['nocolor']
+ colors.number, colors.prompt, colors.normal = '', '', ''
+ count = # Shorthand
+ # Build the dictionary to be passed to string formatting
+ fmtargs = dict(color=colors, count=count,
+ dots="."*len(str(count)) )
+ fmtargs.update(self.lazy_evaluate_fields)
+ fmtargs.update(kwargs)
+ # Prepare the prompt
+ prompt = colors.prompt + self.templates[name] + colors.normal
+ # Fill in required fields
+ res = prompt.format(**fmtargs)
+ # Handle justification of prompt
+ invis_chars = self.invisible_chars[name] if color else 0
+ just = self.justify if (just is None) else just
+ if just:
+ res = res.rjust(self.width + invis_chars)
+ self.width = len(res) - invis_chars
+ return res
2 IPython/core/tests/
@@ -148,7 +148,7 @@ def test_prompts(self):
"""Test that prompts correctly generate after %run"""
_ip = get_ipython()
- p2 = str(_ip.displayhook.prompt2).strip()
+ p2 = _ip.prompt_manager.render('in2').strip()
nt.assert_equals(p2[:3], '...')
def test_run_profile( self ):
4 IPython/frontend/terminal/
@@ -356,7 +356,7 @@ def interact(self, display_banner=None):
if more:
- prompt = self.hooks.generate_prompt(True)
+ prompt = self.prompt_manager.render('in2')
if self.autoindent:
@@ -364,7 +364,7 @@ def interact(self, display_banner=None):
- prompt = self.hooks.generate_prompt(False)
+ prompt = self.separate_in + self.prompt_manager.render('in')
20 IPython/utils/
@@ -15,12 +15,7 @@
from IPython.utils.ipstruct import Struct
-def make_color_table(in_class):
- """Build a set of color attributes in a class.
- Helper function for building the *TermColors classes."""
- color_templates = (
+color_templates = (
# Dark colors
("Black" , "0;30"),
("Red" , "0;31"),
@@ -50,6 +45,11 @@ def make_color_table(in_class):
("BlinkLightGray", "5;37"),
+def make_color_table(in_class):
+ """Build a set of color attributes in a class.
+ Helper function for building the *TermColors classes."""
for name,value in color_templates:
setattr(in_class,name,in_class._base % value)
@@ -98,6 +98,14 @@ class InputTermColors:
# Build the actual color table as a set of class attributes:
+class NoColors:
+ """This defines all the same names as the colour classes, but maps them to
+ empty strings, so it can easily be substituted to turn off colours."""
+ NoColor = ''
+for name, value in color_templates:
+ setattr(NoColors, name, '')
class ColorScheme:
"""Generic color scheme class. Just a name and a Struct."""
def __init__(self,__scheme_name_,colordict=None,**colormap):
4 IPython/utils/tests/
@@ -75,7 +75,6 @@ def eval_formatter_slicing_check(f):
nt.assert_equals(s, ns['stuff'][::2])
nt.assert_raises(SyntaxError, f.format, "{n:x}", **ns)
def eval_formatter_no_slicing_check(f):
ns = dict(n=12, pi=math.pi, stuff='hello there', os=os)
@@ -83,6 +82,9 @@ def eval_formatter_no_slicing_check(f):
s = f.format('{n:x} {pi**2:+f}', **ns)
nt.assert_equals(s, "c +9.869604")
+ s = f.format('{stuff[slice(1,4)]}', **ns)
+ nt.assert_equals(s, 'ell')
nt.assert_raises(SyntaxError, f.format, "{a[:]}")
def test_eval_formatter():
2 IPython/zmq/
@@ -133,7 +133,7 @@ def auto_rewrite_input(self, cmd):
FIXME: this payload is currently not correctly processed by the
- new = self.displayhook.prompt1.auto_rewrite() + cmd
+ new = self.prompt_manager.render('rewrite') + cmd
payload = dict(
9 docs/source/config/ipython.txt
@@ -124,11 +124,12 @@ attributes::
c.InteractiveShell.confirm_exit = False
c.InteractiveShell.deep_reload = True
c.InteractiveShell.editor = 'nano'
- c.InteractiveShell.prompt_in1 = 'In [\#]: '
- c.InteractiveShell.prompt_in2 = ' .\D.: '
- c.InteractiveShell.prompt_out = 'Out[\#]: '
- c.InteractiveShell.prompts_pad_left = True
c.InteractiveShell.xmode = 'Context'
+ c.PromptManager.in_template = 'In [\#]: '
+ c.PromptManager.in2_template = ' .\D.: '
+ c.PromptManager.out_template = 'Out[\#]: '
+ c.PromptManager.justify = True
c.PrefilterManager.multi_line_specials = True
9 docs/source/whatsnew/development.txt
@@ -117,6 +117,15 @@ Backwards incompatible changes
traits, rather than several ip/port pair ``_addr`` traits. This better matches the
rest of the code, where the ip cannot not be set separately for each channel.
+* Custom prompts are now configured using a new class,
+ :class:`~IPython.core.prompts.PromptManager`, which has traits for :attr:`in_template`,
+ :attr:`in2_template` (the ``...:`` continuation prompt), :attr:`out_template`
+ and :attr:`rewrite_template`. This uses Python's string formatting system, so
+ you can use ``{time}`` and ``{cwd}``, although we have preserved the abbreviations
+ from previous versions, e.g. ``\#`` (prompt number) and ``\w`` (working
+ directory). For the list of available fields, refer to the source of
+ :file:`IPython/core/`.
* The class inheritance of the Launchers in :mod:`IPython.parallel.apps.launcher`
used by ipcluster has changed, so that trait names are more consistent across
batch systems. This may require a few renames in your config files, if you
Something went wrong with that request. Please try again.