summaryrefslogtreecommitdiffstats
path: root/powerline/bindings/ipython
diff options
context:
space:
mode:
Diffstat (limited to 'powerline/bindings/ipython')
-rw-r--r--powerline/bindings/ipython/__init__.py0
-rw-r--r--powerline/bindings/ipython/post_0_11.py126
-rw-r--r--powerline/bindings/ipython/pre_0_11.py146
-rw-r--r--powerline/bindings/ipython/since_5.py81
-rw-r--r--powerline/bindings/ipython/since_7.py78
5 files changed, 431 insertions, 0 deletions
diff --git a/powerline/bindings/ipython/__init__.py b/powerline/bindings/ipython/__init__.py
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/powerline/bindings/ipython/__init__.py
diff --git a/powerline/bindings/ipython/post_0_11.py b/powerline/bindings/ipython/post_0_11.py
new file mode 100644
index 0000000..3213c51
--- /dev/null
+++ b/powerline/bindings/ipython/post_0_11.py
@@ -0,0 +1,126 @@
+# vim:fileencoding=utf-8:noet
+from __future__ import (unicode_literals, division,
+ absolute_import, print_function)
+
+from weakref import ref
+from warnings import warn
+
+try:
+ from IPython.core.prompts import PromptManager
+ has_prompt_manager = True
+except ImportError:
+ has_prompt_manager = False
+from IPython.core.magic import Magics, magics_class, line_magic
+
+from powerline.ipython import IPythonPowerline, IPythonInfo
+
+if has_prompt_manager:
+ from powerline.ipython import RewriteResult
+
+
+@magics_class
+class PowerlineMagics(Magics):
+ def __init__(self, ip, powerline):
+ super(PowerlineMagics, self).__init__(ip)
+ self._powerline = powerline
+
+ @line_magic
+ def powerline(self, line):
+ if line == 'reload':
+ self._powerline.reload()
+ else:
+ raise ValueError('Expected `reload`, but got {0}'.format(line))
+
+
+old_prompt_manager = None
+
+
+class ShutdownHook(object):
+ def __init__(self, ip):
+ self.powerline = lambda: None
+ ip.hooks.shutdown_hook.add(self)
+
+ def __call__(self):
+ from IPython.core.hooks import TryNext
+ powerline = self.powerline()
+ if powerline is not None:
+ powerline.shutdown()
+ raise TryNext()
+
+
+if has_prompt_manager:
+ class PowerlinePromptManager(PromptManager):
+ def __init__(self, powerline, shell):
+ self.powerline = powerline
+ self.powerline_segment_info = IPythonInfo(shell)
+ self.shell = shell
+
+ def render(self, name, color=True, *args, **kwargs):
+ res = self.powerline.render(
+ is_prompt=name.startswith('in'),
+ side='left',
+ output_width=True,
+ output_raw=not color,
+ matcher_info=name,
+ segment_info=self.powerline_segment_info,
+ )
+ self.txtwidth = res[-1]
+ self.width = res[-1]
+ ret = res[0] if color else res[1]
+ if name == 'rewrite':
+ return RewriteResult(ret)
+ else:
+ return ret
+
+ class ConfigurableIPythonPowerline(IPythonPowerline):
+ def init(self, ip):
+ config = ip.config.Powerline
+ self.config_overrides = config.get('config_overrides')
+ self.theme_overrides = config.get('theme_overrides', {})
+ self.config_paths = config.get('config_paths')
+ if has_prompt_manager:
+ renderer_module = '.pre_5'
+ else:
+ renderer_module = '.since_7'
+ super(ConfigurableIPythonPowerline, self).init(
+ renderer_module=renderer_module)
+
+ def do_setup(self, ip, shutdown_hook):
+ global old_prompt_manager
+
+ if old_prompt_manager is None:
+ old_prompt_manager = ip.prompt_manager
+ prompt_manager = PowerlinePromptManager(
+ powerline=self,
+ shell=ip.prompt_manager.shell,
+ )
+ ip.prompt_manager = prompt_manager
+
+ magics = PowerlineMagics(ip, self)
+ shutdown_hook.powerline = ref(self)
+ ip.register_magics(magics)
+
+
+def load_ipython_extension(ip):
+ if has_prompt_manager:
+ shutdown_hook = ShutdownHook(ip)
+ powerline = ConfigurableIPythonPowerline(ip)
+ powerline.setup(ip, shutdown_hook)
+ else:
+ from powerline.bindings.ipython.since_7 import PowerlinePrompts
+ ip.prompts_class = PowerlinePrompts
+ ip.prompts = PowerlinePrompts(ip)
+ warn(DeprecationWarning(
+ 'post_0_11 extension is deprecated since IPython 5, use\n'
+ ' from powerline.bindings.ipython.since_7 import PowerlinePrompts\n'
+ ' c.TerminalInteractiveShell.prompts_class = PowerlinePrompts\n'
+ 'or check: \n'
+ 'https://powerline.readthedocs.io/en/master/usage/other.html\n'
+ ))
+
+
+def unload_ipython_extension(ip):
+ global old_prompt_manager
+ if old_prompt_manager is not None:
+ ip.prompt_manager = old_prompt_manager
+ old_prompt_manager = None
diff --git a/powerline/bindings/ipython/pre_0_11.py b/powerline/bindings/ipython/pre_0_11.py
new file mode 100644
index 0000000..2bd8095
--- /dev/null
+++ b/powerline/bindings/ipython/pre_0_11.py
@@ -0,0 +1,146 @@
+# vim:fileencoding=utf-8:noet
+from __future__ import (unicode_literals, division, absolute_import, print_function)
+
+import re
+
+from weakref import ref
+
+from IPython.Prompts import BasePrompt
+from IPython.ipapi import get as get_ipython
+from IPython.ipapi import TryNext
+
+from powerline.ipython import IPythonPowerline, RewriteResult
+from powerline.lib.unicode import string
+
+
+class IPythonInfo(object):
+ def __init__(self, cache):
+ self._cache = cache
+
+ @property
+ def prompt_count(self):
+ return self._cache.prompt_count
+
+
+class PowerlinePrompt(BasePrompt):
+ def __init__(self, powerline, powerline_last_in, old_prompt):
+ self.powerline = powerline
+ self.powerline_last_in = powerline_last_in
+ self.powerline_segment_info = IPythonInfo(old_prompt.cache)
+ self.cache = old_prompt.cache
+ if hasattr(old_prompt, 'sep'):
+ self.sep = old_prompt.sep
+ self.pad_left = False
+
+ def __str__(self):
+ self.set_p_str()
+ return string(self.p_str)
+
+ def set_p_str(self):
+ self.p_str, self.p_str_nocolor, self.powerline_prompt_width = (
+ self.powerline.render(
+ is_prompt=self.powerline_is_prompt,
+ side='left',
+ output_raw=True,
+ output_width=True,
+ segment_info=self.powerline_segment_info,
+ matcher_info=self.powerline_prompt_type,
+ )
+ )
+
+ @staticmethod
+ def set_colors():
+ pass
+
+
+class PowerlinePrompt1(PowerlinePrompt):
+ powerline_prompt_type = 'in'
+ powerline_is_prompt = True
+ rspace = re.compile(r'(\s*)$')
+
+ def __str__(self):
+ self.cache.prompt_count += 1
+ self.set_p_str()
+ self.cache.last_prompt = self.p_str_nocolor.split('\n')[-1]
+ return string(self.p_str)
+
+ def set_p_str(self):
+ super(PowerlinePrompt1, self).set_p_str()
+ self.nrspaces = len(self.rspace.search(self.p_str_nocolor).group())
+ self.powerline_last_in['nrspaces'] = self.nrspaces
+
+ def auto_rewrite(self):
+ return RewriteResult(self.powerline.render(
+ is_prompt=False,
+ side='left',
+ matcher_info='rewrite',
+ segment_info=self.powerline_segment_info) + (' ' * self.nrspaces)
+ )
+
+
+class PowerlinePromptOut(PowerlinePrompt):
+ powerline_prompt_type = 'out'
+ powerline_is_prompt = False
+
+ def set_p_str(self):
+ super(PowerlinePromptOut, self).set_p_str()
+ spaces = ' ' * self.powerline_last_in['nrspaces']
+ self.p_str += spaces
+ self.p_str_nocolor += spaces
+
+
+class PowerlinePrompt2(PowerlinePromptOut):
+ powerline_prompt_type = 'in2'
+ powerline_is_prompt = True
+
+
+class ConfigurableIPythonPowerline(IPythonPowerline):
+ def init(self, config_overrides=None, theme_overrides={}, config_paths=None):
+ self.config_overrides = config_overrides
+ self.theme_overrides = theme_overrides
+ self.config_paths = config_paths
+ super(ConfigurableIPythonPowerline, self).init(renderer_module='.pre_5')
+
+ def ipython_magic(self, ip, parameter_s=''):
+ if parameter_s == 'reload':
+ self.reload()
+ else:
+ raise ValueError('Expected `reload`, but got {0}'.format(parameter_s))
+
+ def do_setup(self, ip, shutdown_hook):
+ last_in = {'nrspaces': 0}
+ for attr, prompt_class in (
+ ('prompt1', PowerlinePrompt1),
+ ('prompt2', PowerlinePrompt2),
+ ('prompt_out', PowerlinePromptOut)
+ ):
+ old_prompt = getattr(ip.IP.outputcache, attr)
+ prompt = prompt_class(self, last_in, old_prompt)
+ setattr(ip.IP.outputcache, attr, prompt)
+ ip.expose_magic('powerline', self.ipython_magic)
+ shutdown_hook.powerline = ref(self)
+
+
+class ShutdownHook(object):
+ powerline = lambda: None
+
+ def __call__(self):
+ from IPython.ipapi import TryNext
+ powerline = self.powerline()
+ if powerline is not None:
+ powerline.shutdown()
+ raise TryNext()
+
+
+def setup(**kwargs):
+ ip = get_ipython()
+
+ powerline = ConfigurableIPythonPowerline(**kwargs)
+ shutdown_hook = ShutdownHook()
+
+ def late_startup_hook():
+ powerline.setup(ip, shutdown_hook)
+ raise TryNext()
+
+ ip.IP.hooks.late_startup_hook.add(late_startup_hook)
+ ip.IP.hooks.shutdown_hook.add(shutdown_hook)
diff --git a/powerline/bindings/ipython/since_5.py b/powerline/bindings/ipython/since_5.py
new file mode 100644
index 0000000..5a899ae
--- /dev/null
+++ b/powerline/bindings/ipython/since_5.py
@@ -0,0 +1,81 @@
+# vim:fileencoding=utf-8:noet
+from __future__ import (unicode_literals, division, absolute_import, print_function)
+
+from weakref import ref
+
+from IPython.terminal.prompts import Prompts
+from pygments.token import Token # NOQA
+
+from powerline.ipython import IPythonPowerline
+from powerline.renderers.ipython.since_5 import PowerlinePromptStyle
+from powerline.bindings.ipython.post_0_11 import PowerlineMagics, ShutdownHook
+
+
+class ConfigurableIPythonPowerline(IPythonPowerline):
+ def init(self, ip):
+ config = ip.config.Powerline
+ self.config_overrides = config.get('config_overrides')
+ self.theme_overrides = config.get('theme_overrides', {})
+ self.config_paths = config.get('config_paths')
+ super(ConfigurableIPythonPowerline, self).init(
+ renderer_module='.since_5')
+
+ def do_setup(self, ip, prompts, shutdown_hook):
+ prompts.powerline = self
+
+ msfn_missing = ()
+ saved_msfn = getattr(ip, '_make_style_from_name', msfn_missing)
+
+ if hasattr(saved_msfn, 'powerline_original'):
+ saved_msfn = saved_msfn.powerline_original
+
+ def _make_style_from_name(ip, name):
+ prev_style = saved_msfn(name)
+ new_style = PowerlinePromptStyle(lambda: prev_style)
+ return new_style
+
+ _make_style_from_name.powerline_original = saved_msfn
+
+ if not isinstance(ip._style, PowerlinePromptStyle):
+ prev_style = ip._style
+ ip._style = PowerlinePromptStyle(lambda: prev_style)
+
+ if not isinstance(saved_msfn, type(self.init)):
+ _saved_msfn = saved_msfn
+ saved_msfn = lambda: _saved_msfn(ip)
+
+ if saved_msfn is not msfn_missing:
+ ip._make_style_from_name = _make_style_from_name
+
+ magics = PowerlineMagics(ip, self)
+ ip.register_magics(magics)
+
+ if shutdown_hook:
+ shutdown_hook.powerline = ref(self)
+
+
+class PowerlinePrompts(Prompts):
+ '''Class that returns powerline prompts
+ '''
+ def __init__(self, shell):
+ shutdown_hook = ShutdownHook(shell)
+ powerline = ConfigurableIPythonPowerline(shell)
+ self.shell = shell
+ powerline.do_setup(shell, self, shutdown_hook)
+ self.last_output_count = None
+ self.last_output = {}
+
+ for prompt in ('in', 'continuation', 'rewrite', 'out'):
+ exec((
+ 'def {0}_prompt_tokens(self, *args, **kwargs):\n'
+ ' if self.last_output_count != self.shell.execution_count:\n'
+ ' self.last_output.clear()\n'
+ ' self.last_output_count = self.shell.execution_count\n'
+ ' if "{0}" not in self.last_output:\n'
+ ' self.last_output["{0}"] = self.powerline.render('
+ ' side="left",'
+ ' matcher_info="{1}",'
+ ' segment_info=self.shell,'
+ ' ) + [(Token.Generic.Prompt, " ")]\n'
+ ' return self.last_output["{0}"]'
+ ).format(prompt, 'in2' if prompt == 'continuation' else prompt))
diff --git a/powerline/bindings/ipython/since_7.py b/powerline/bindings/ipython/since_7.py
new file mode 100644
index 0000000..4d35b68
--- /dev/null
+++ b/powerline/bindings/ipython/since_7.py
@@ -0,0 +1,78 @@
+# vim:fileencoding=utf-8:noet
+from weakref import ref
+from atexit import register as atexit
+
+from IPython.terminal.prompts import Prompts
+from pygments.token import Token # NOQA
+
+from powerline.ipython import IPythonPowerline
+from powerline.renderers.ipython.since_7 import PowerlinePromptStyle
+from powerline.bindings.ipython.post_0_11 import PowerlineMagics
+
+
+class ConfigurableIPythonPowerline(IPythonPowerline):
+ def init(self, ip):
+ config = ip.config.Powerline
+ self.config_overrides = config.get('config_overrides')
+ self.theme_overrides = config.get('theme_overrides', {})
+ self.config_paths = config.get('config_paths')
+ super(ConfigurableIPythonPowerline, self).init(
+ renderer_module='.since_7')
+
+ def do_setup(self, ip, prompts):
+ prompts.powerline = self
+
+ msfn_missing = ()
+ saved_msfn = getattr(ip, '_make_style_from_name', msfn_missing)
+
+ if hasattr(saved_msfn, 'powerline_original'):
+ saved_msfn = saved_msfn.powerline_original
+
+ def _make_style_from_name(ip, name):
+ prev_style = saved_msfn(name)
+ new_style = PowerlinePromptStyle(lambda: prev_style)
+ return new_style
+
+ _make_style_from_name.powerline_original = saved_msfn
+
+ if not isinstance(ip._style, PowerlinePromptStyle):
+ prev_style = ip._style
+ ip._style = PowerlinePromptStyle(lambda: prev_style)
+
+ if not isinstance(saved_msfn, type(self.init)):
+ _saved_msfn = saved_msfn
+ saved_msfn = lambda: _saved_msfn(ip)
+
+ if saved_msfn is not msfn_missing:
+ ip._make_style_from_name = _make_style_from_name
+
+ magics = PowerlineMagics(ip, self)
+ ip.register_magics(magics)
+
+ atexit(self.shutdown)
+
+
+class PowerlinePrompts(Prompts):
+ '''Class that returns powerline prompts
+ '''
+ def __init__(self, shell):
+ powerline = ConfigurableIPythonPowerline(shell)
+ self.shell = shell
+ powerline.do_setup(shell, self)
+ self.last_output_count = None
+ self.last_output = {}
+
+ for prompt in ('in', 'continuation', 'rewrite', 'out'):
+ exec((
+ 'def {0}_prompt_tokens(self, *args, **kwargs):\n'
+ ' if self.last_output_count != self.shell.execution_count:\n'
+ ' self.last_output.clear()\n'
+ ' self.last_output_count = self.shell.execution_count\n'
+ ' if "{0}" not in self.last_output:\n'
+ ' self.last_output["{0}"] = self.powerline.render('
+ ' side="left",'
+ ' matcher_info="{1}",'
+ ' segment_info=self.shell,'
+ ' ) + [(Token.Generic.Prompt, " ")]\n'
+ ' return self.last_output["{0}"]'
+ ).format(prompt, 'in2' if prompt == 'continuation' else prompt))