##// END OF EJS Templates
adopt traitlets 4.2 API...
Min RK -
Show More
@@ -192,8 +192,8 b' class Alias(object):'
192
192
193 class AliasManager(Configurable):
193 class AliasManager(Configurable):
194
194
195 default_aliases = List(default_aliases(), config=True)
195 default_aliases = List(default_aliases()).tag(config=True)
196 user_aliases = List(default_value=[], config=True)
196 user_aliases = List(default_value=[]).tag(config=True)
197 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
197 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
198
198
199 def __init__(self, shell=None, **kwargs):
199 def __init__(self, shell=None, **kwargs):
@@ -26,7 +26,10 b' from IPython.core.profiledir import ProfileDir, ProfileDirError'
26 from IPython.paths import get_ipython_dir, get_ipython_package_dir
26 from IPython.paths import get_ipython_dir, get_ipython_package_dir
27 from IPython.utils.path import ensure_dir_exists
27 from IPython.utils.path import ensure_dir_exists
28 from IPython.utils import py3compat
28 from IPython.utils import py3compat
29 from traitlets import List, Unicode, Type, Bool, Dict, Set, Instance, Undefined
29 from traitlets import (
30 List, Unicode, Type, Bool, Dict, Set, Instance, Undefined,
31 default, observe,
32 )
30
33
31 if os.name == 'nt':
34 if os.name == 'nt':
32 programdata = os.environ.get('PROGRAMDATA', None)
35 programdata = os.environ.get('PROGRAMDATA', None)
@@ -96,11 +99,13 b' class BaseIPythonApplication(Application):'
96 config_file_specified = Set()
99 config_file_specified = Set()
97
100
98 config_file_name = Unicode()
101 config_file_name = Unicode()
102 @default('config_file_name')
99 def _config_file_name_default(self):
103 def _config_file_name_default(self):
100 return self.name.replace('-','_') + u'_config.py'
104 return self.name.replace('-','_') + u'_config.py'
101 def _config_file_name_changed(self, name, old, new):
105 @observe('config_file_name')
102 if new != old:
106 def _config_file_name_changed(self, change):
103 self.config_file_specified.add(new)
107 if change['new'] != change['old']:
108 self.config_file_specified.add(change['new'])
104
109
105 # The directory that contains IPython's builtin profiles.
110 # The directory that contains IPython's builtin profiles.
106 builtin_profile_dir = Unicode(
111 builtin_profile_dir = Unicode(
@@ -108,15 +113,19 b' class BaseIPythonApplication(Application):'
108 )
113 )
109
114
110 config_file_paths = List(Unicode())
115 config_file_paths = List(Unicode())
116 @default('config_file_paths')
111 def _config_file_paths_default(self):
117 def _config_file_paths_default(self):
112 return [py3compat.getcwd()]
118 return [py3compat.getcwd()]
113
119
114 extra_config_file = Unicode(config=True,
120 extra_config_file = Unicode(
115 help="""Path to an extra config file to load.
121 help="""Path to an extra config file to load.
116
122
117 If specified, load this config file in addition to any other IPython config.
123 If specified, load this config file in addition to any other IPython config.
118 """)
124 """).tag(config=True)
119 def _extra_config_file_changed(self, name, old, new):
125 @observe('extra_config_file')
126 def _extra_config_file_changed(self, change):
127 old = change['old']
128 new = change['new']
120 try:
129 try:
121 self.config_files.remove(old)
130 self.config_files.remove(old)
122 except ValueError:
131 except ValueError:
@@ -124,30 +133,37 b' class BaseIPythonApplication(Application):'
124 self.config_file_specified.add(new)
133 self.config_file_specified.add(new)
125 self.config_files.append(new)
134 self.config_files.append(new)
126
135
127 profile = Unicode(u'default', config=True,
136 profile = Unicode(u'default',
128 help="""The IPython profile to use."""
137 help="""The IPython profile to use."""
129 )
138 ).tag(config=True)
130
139
131 def _profile_changed(self, name, old, new):
140 @observe('profile')
141 def _profile_changed(self, change):
132 self.builtin_profile_dir = os.path.join(
142 self.builtin_profile_dir = os.path.join(
133 get_ipython_package_dir(), u'config', u'profile', new
143 get_ipython_package_dir(), u'config', u'profile', change['new']
134 )
144 )
135
145
136 ipython_dir = Unicode(config=True,
146 ipython_dir = Unicode(
137 help="""
147 help="""
138 The name of the IPython directory. This directory is used for logging
148 The name of the IPython directory. This directory is used for logging
139 configuration (through profiles), history storage, etc. The default
149 configuration (through profiles), history storage, etc. The default
140 is usually $HOME/.ipython. This option can also be specified through
150 is usually $HOME/.ipython. This option can also be specified through
141 the environment variable IPYTHONDIR.
151 the environment variable IPYTHONDIR.
142 """
152 """
143 )
153 ).tag(config=True)
154 @default('ipython_dir')
144 def _ipython_dir_default(self):
155 def _ipython_dir_default(self):
145 d = get_ipython_dir()
156 d = get_ipython_dir()
146 self._ipython_dir_changed('ipython_dir', d, d)
157 self._ipython_dir_changed({
158 'name': 'ipython_dir',
159 'old': d,
160 'new': d,
161 })
147 return d
162 return d
148
163
149 _in_init_profile_dir = False
164 _in_init_profile_dir = False
150 profile_dir = Instance(ProfileDir, allow_none=True)
165 profile_dir = Instance(ProfileDir, allow_none=True)
166 @default('profile_dir')
151 def _profile_dir_default(self):
167 def _profile_dir_default(self):
152 # avoid recursion
168 # avoid recursion
153 if self._in_init_profile_dir:
169 if self._in_init_profile_dir:
@@ -156,26 +172,29 b' class BaseIPythonApplication(Application):'
156 self.init_profile_dir()
172 self.init_profile_dir()
157 return self.profile_dir
173 return self.profile_dir
158
174
159 overwrite = Bool(False, config=True,
175 overwrite = Bool(False,
160 help="""Whether to overwrite existing config files when copying""")
176 help="""Whether to overwrite existing config files when copying"""
161 auto_create = Bool(False, config=True,
177 ).tag(config=True)
162 help="""Whether to create profile dir if it doesn't exist""")
178 auto_create = Bool(False,
179 help="""Whether to create profile dir if it doesn't exist"""
180 ).tag(config=True)
163
181
164 config_files = List(Unicode())
182 config_files = List(Unicode())
183 @default('config_files')
165 def _config_files_default(self):
184 def _config_files_default(self):
166 return [self.config_file_name]
185 return [self.config_file_name]
167
186
168 copy_config_files = Bool(False, config=True,
187 copy_config_files = Bool(False,
169 help="""Whether to install the default config files into the profile dir.
188 help="""Whether to install the default config files into the profile dir.
170 If a new profile is being created, and IPython contains config files for that
189 If a new profile is being created, and IPython contains config files for that
171 profile, then they will be staged into the new directory. Otherwise,
190 profile, then they will be staged into the new directory. Otherwise,
172 default config files will be automatically generated.
191 default config files will be automatically generated.
173 """)
192 """).tag(config=True)
174
193
175 verbose_crash = Bool(False, config=True,
194 verbose_crash = Bool(False,
176 help="""Create a massive crash report when IPython encounters what may be an
195 help="""Create a massive crash report when IPython encounters what may be an
177 internal error. The default is to append a short message to the
196 internal error. The default is to append a short message to the
178 usual traceback""")
197 usual traceback""").tag(config=True)
179
198
180 # The class to use as the crash handler.
199 # The class to use as the crash handler.
181 crash_handler_class = Type(crashhandler.CrashHandler)
200 crash_handler_class = Type(crashhandler.CrashHandler)
@@ -199,7 +218,6 b' class BaseIPythonApplication(Application):'
199
218
200 def initialize_subcommand(self, subc, argv=None):
219 def initialize_subcommand(self, subc, argv=None):
201 if subc in self.deprecated_subcommands:
220 if subc in self.deprecated_subcommands:
202 import time
203 self.log.warning("Subcommand `ipython {sub}` is deprecated and will be removed "
221 self.log.warning("Subcommand `ipython {sub}` is deprecated and will be removed "
204 "in future versions.".format(sub=subc))
222 "in future versions.".format(sub=subc))
205 self.log.warning("You likely want to use `jupyter {sub}` in the "
223 self.log.warning("You likely want to use `jupyter {sub}` in the "
@@ -225,8 +243,11 b' class BaseIPythonApplication(Application):'
225 return self.crash_handler(etype, evalue, tb)
243 return self.crash_handler(etype, evalue, tb)
226 else:
244 else:
227 return crashhandler.crash_handler_lite(etype, evalue, tb)
245 return crashhandler.crash_handler_lite(etype, evalue, tb)
228
246
229 def _ipython_dir_changed(self, name, old, new):
247 @observe('ipython_dir')
248 def _ipython_dir_changed(self, change):
249 old = change['old']
250 new = change['new']
230 if old is not Undefined:
251 if old is not Undefined:
231 str_old = py3compat.cast_bytes_py2(os.path.abspath(old),
252 str_old = py3compat.cast_bytes_py2(os.path.abspath(old),
232 sys.getfilesystemencoding()
253 sys.getfilesystemencoding()
@@ -66,7 +66,7 b' import sys'
66 import unicodedata
66 import unicodedata
67 import string
67 import string
68
68
69 from traitlets.config.configurable import Configurable
69 from traitlets.config.configurable import Configurable
70 from IPython.core.error import TryNext
70 from IPython.core.error import TryNext
71 from IPython.core.inputsplitter import ESC_MAGIC
71 from IPython.core.inputsplitter import ESC_MAGIC
72 from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol
72 from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol
@@ -75,7 +75,7 b' from IPython.utils.decorators import undoc'
75 from IPython.utils.dir2 import dir2, get_real_method
75 from IPython.utils.dir2 import dir2, get_real_method
76 from IPython.utils.process import arg_split
76 from IPython.utils.process import arg_split
77 from IPython.utils.py3compat import builtin_mod, string_types, PY3, cast_unicode_py2
77 from IPython.utils.py3compat import builtin_mod, string_types, PY3, cast_unicode_py2
78 from traitlets import CBool, Enum
78 from traitlets import Bool, Enum, observe
79
79
80 import jedi
80 import jedi
81 import jedi.api.helpers
81 import jedi.api.helpers
@@ -174,7 +174,6 b' def compress_user(path, tilde_expand, tilde_val):'
174 return path
174 return path
175
175
176
176
177
178 def completions_sorting_key(word):
177 def completions_sorting_key(word):
179 """key for sorting completions
178 """key for sorting completions
180
179
@@ -273,14 +272,14 b' class CompletionSplitter(object):'
273
272
274 class Completer(Configurable):
273 class Completer(Configurable):
275
274
276 greedy = CBool(False, config=True,
275 greedy = Bool(False,
277 help="""Activate greedy completion
276 help="""Activate greedy completion
278 PENDING DEPRECTION. this is now mostly taken care of with Jedi.
277 PENDING DEPRECTION. this is now mostly taken care of with Jedi.
279
278
280 This will enable completion on elements of lists, results of function calls, etc.,
279 This will enable completion on elements of lists, results of function calls, etc.,
281 but can be unsafe because the code is actually evaluated on TAB.
280 but can be unsafe because the code is actually evaluated on TAB.
282 """
281 """
283 )
282 ).tag(config=True)
284
283
285
284
286 def __init__(self, namespace=None, global_namespace=None, **kwargs):
285 def __init__(self, namespace=None, global_namespace=None, **kwargs):
@@ -505,7 +504,7 b' def back_unicode_name_matches(text):'
505 try :
504 try :
506 unic = unicodedata.name(char)
505 unic = unicodedata.name(char)
507 return '\\'+char,['\\'+unic]
506 return '\\'+char,['\\'+unic]
508 except KeyError as e:
507 except KeyError:
509 pass
508 pass
510 return u'', ()
509 return u'', ()
511
510
@@ -532,17 +531,18 b' def back_latex_name_matches(text):'
532 latex = reverse_latex_symbol[char]
531 latex = reverse_latex_symbol[char]
533 # '\\' replace the \ as well
532 # '\\' replace the \ as well
534 return '\\'+char,[latex]
533 return '\\'+char,[latex]
535 except KeyError as e:
534 except KeyError:
536 pass
535 pass
537 return u'', ()
536 return u'', ()
538
537
539
538
540 class IPCompleter(Completer):
539 class IPCompleter(Completer):
541 """Extension of the completer class with IPython-specific features"""
540 """Extension of the completer class with IPython-specific features"""
542
541
543 def _greedy_changed(self, name, old, new):
542 @observe('greedy')
543 def _greedy_changed(self, change):
544 """update the splitter and readline delims when greedy is changed"""
544 """update the splitter and readline delims when greedy is changed"""
545 if new:
545 if change['new']:
546 self.splitter.delims = GREEDY_DELIMS
546 self.splitter.delims = GREEDY_DELIMS
547 else:
547 else:
548 self.splitter.delims = DELIMS
548 self.splitter.delims = DELIMS
@@ -550,14 +550,14 b' class IPCompleter(Completer):'
550 if self.readline:
550 if self.readline:
551 self.readline.set_completer_delims(self.splitter.delims)
551 self.readline.set_completer_delims(self.splitter.delims)
552
552
553 merge_completions = CBool(True, config=True,
553 merge_completions = Bool(True,
554 help="""Whether to merge completion results into a single list
554 help="""Whether to merge completion results into a single list
555
555
556 If False, only the completion results from the first non-empty
556 If False, only the completion results from the first non-empty
557 completer will be returned.
557 completer will be returned.
558 """
558 """
559 )
559 ).tag(config=True)
560 omit__names = Enum((0,1,2), default_value=2, config=True,
560 omit__names = Enum((0,1,2), default_value=2,
561 help="""Instruct the completer to omit private method names
561 help="""Instruct the completer to omit private method names
562
562
563 Specifically, when completing on ``object.<tab>``.
563 Specifically, when completing on ``object.<tab>``.
@@ -568,8 +568,8 b' class IPCompleter(Completer):'
568
568
569 When 0: nothing will be excluded.
569 When 0: nothing will be excluded.
570 """
570 """
571 )
571 ).tag(config=True)
572 limit_to__all__ = CBool(default_value=False, config=True,
572 limit_to__all__ = Bool(False,
573 help="""
573 help="""
574 DEPRECATED as of version 5.0.
574 DEPRECATED as of version 5.0.
575
575
@@ -580,8 +580,8 b' class IPCompleter(Completer):'
580 When True: only those names in obj.__all__ will be included.
580 When True: only those names in obj.__all__ will be included.
581
581
582 When False [default]: the __all__ attribute is ignored
582 When False [default]: the __all__ attribute is ignored
583 """
583 """,
584 )
584 ).tag(config=True)
585
585
586 def __init__(self, shell=None, namespace=None, global_namespace=None,
586 def __init__(self, shell=None, namespace=None, global_namespace=None,
587 use_readline=True, config=None, **kwargs):
587 use_readline=True, config=None, **kwargs):
@@ -1101,7 +1101,7 b' class IPCompleter(Completer):'
1101 # allow combining chars
1101 # allow combining chars
1102 if ('a'+unic).isidentifier():
1102 if ('a'+unic).isidentifier():
1103 return '\\'+s,[unic]
1103 return '\\'+s,[unic]
1104 except KeyError as e:
1104 except KeyError:
1105 pass
1105 pass
1106 return u'', []
1106 return u'', []
1107
1107
@@ -26,6 +26,7 b' from IPython.lib import pretty'
26 from traitlets import (
26 from traitlets import (
27 Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List,
27 Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List,
28 ForwardDeclaredInstance,
28 ForwardDeclaredInstance,
29 default, observe,
29 )
30 )
30 from IPython.utils.py3compat import (
31 from IPython.utils.py3compat import (
31 with_metaclass, string_types, unicode_type,
32 with_metaclass, string_types, unicode_type,
@@ -49,29 +50,34 b' class DisplayFormatter(Configurable):'
49 else:
50 else:
50 self.active_types = self.format_types
51 self.active_types = self.format_types
51
52
52 active_types = List(Unicode()).tag(config=True,
53 active_types = List(Unicode(),
53 help="""List of currently active mime-types to display.
54 help="""List of currently active mime-types to display.
54 You can use this to set a white-list for formats to display.
55 You can use this to set a white-list for formats to display.
55
56
56 Most users will not need to change this value.
57 Most users will not need to change this value.
57 """)
58 """).tag(config=True)
59
60 @default('active_types')
58 def _active_types_default(self):
61 def _active_types_default(self):
59 return self.format_types
62 return self.format_types
60
63
61 def _active_types_changed(self, name, old, new):
64 @observe('active_types')
65 def _active_types_changed(self, change):
62 for key, formatter in self.formatters.items():
66 for key, formatter in self.formatters.items():
63 if key in new:
67 if key in change['new']:
64 formatter.enabled = True
68 formatter.enabled = True
65 else:
69 else:
66 formatter.enabled = False
70 formatter.enabled = False
67
71
68 ipython_display_formatter = ForwardDeclaredInstance('FormatterABC')
72 ipython_display_formatter = ForwardDeclaredInstance('FormatterABC')
69 def _ipython_display_formatter_default(self):
73 @default('ipython_display_formatter')
74 def _default_formatter(self):
70 return IPythonDisplayFormatter(parent=self)
75 return IPythonDisplayFormatter(parent=self)
71
76
72 # A dict of formatter whose keys are format types (MIME types) and whose
77 # A dict of formatter whose keys are format types (MIME types) and whose
73 # values are subclasses of BaseFormatter.
78 # values are subclasses of BaseFormatter.
74 formatters = Dict()
79 formatters = Dict()
80 @default('formatters')
75 def _formatters_default(self):
81 def _formatters_default(self):
76 """Activate the default formatters."""
82 """Activate the default formatters."""
77 formatter_classes = [
83 formatter_classes = [
@@ -570,12 +576,12 b' class PlainTextFormatter(BaseFormatter):'
570 # something.
576 # something.
571 enabled = Bool(True).tag(config=False)
577 enabled = Bool(True).tag(config=False)
572
578
573 max_seq_length = Integer(pretty.MAX_SEQ_LENGTH).tag(config=True,
579 max_seq_length = Integer(pretty.MAX_SEQ_LENGTH,
574 help="""Truncate large collections (lists, dicts, tuples, sets) to this size.
580 help="""Truncate large collections (lists, dicts, tuples, sets) to this size.
575
581
576 Set to 0 to disable truncation.
582 Set to 0 to disable truncation.
577 """
583 """
578 )
584 ).tag(config=True)
579
585
580 # Look for a _repr_pretty_ methods to use for pretty printing.
586 # Look for a _repr_pretty_ methods to use for pretty printing.
581 print_method = ObjectName('_repr_pretty_')
587 print_method = ObjectName('_repr_pretty_')
@@ -643,14 +649,17 b' class PlainTextFormatter(BaseFormatter):'
643 self.float_format = fmt
649 self.float_format = fmt
644
650
645 # Use the default pretty printers from IPython.lib.pretty.
651 # Use the default pretty printers from IPython.lib.pretty.
652 @default('singleton_printers')
646 def _singleton_printers_default(self):
653 def _singleton_printers_default(self):
647 return pretty._singleton_pprinters.copy()
654 return pretty._singleton_pprinters.copy()
648
655
656 @default('type_printers')
649 def _type_printers_default(self):
657 def _type_printers_default(self):
650 d = pretty._type_pprinters.copy()
658 d = pretty._type_pprinters.copy()
651 d[float] = lambda obj,p,cycle: p.text(self.float_format%obj)
659 d[float] = lambda obj,p,cycle: p.text(self.float_format%obj)
652 return d
660 return d
653
661
662 @default('deferred_printers')
654 def _deferred_printers_default(self):
663 def _deferred_printers_default(self):
655 return pretty._deferred_type_pprinters.copy()
664 return pretty._deferred_type_pprinters.copy()
656
665
@@ -25,6 +25,7 b' from IPython.utils.path import locate_profile'
25 from IPython.utils import py3compat
25 from IPython.utils import py3compat
26 from traitlets import (
26 from traitlets import (
27 Any, Bool, Dict, Instance, Integer, List, Unicode, TraitError,
27 Any, Bool, Dict, Instance, Integer, List, Unicode, TraitError,
28 default, observe,
28 )
29 )
29 from warnings import warn
30 from warnings import warn
30
31
@@ -148,7 +149,7 b' class HistoryAccessor(HistoryAccessorBase):'
148 _corrupt_db_limit = 2
149 _corrupt_db_limit = 2
149
150
150 # String holding the path to the history file
151 # String holding the path to the history file
151 hist_file = Unicode(config=True,
152 hist_file = Unicode(
152 help="""Path to file to use for SQLite history database.
153 help="""Path to file to use for SQLite history database.
153
154
154 By default, IPython will put the history database in the IPython
155 By default, IPython will put the history database in the IPython
@@ -161,9 +162,9 b' class HistoryAccessor(HistoryAccessorBase):'
161
162
162 ipython --HistoryManager.hist_file=/tmp/ipython_hist.sqlite
163 ipython --HistoryManager.hist_file=/tmp/ipython_hist.sqlite
163
164
164 """)
165 """).tag(config=True)
165
166
166 enabled = Bool(True, config=True,
167 enabled = Bool(True,
167 help="""enable the SQLite history
168 help="""enable the SQLite history
168
169
169 set enabled=False to disable the SQLite history,
170 set enabled=False to disable the SQLite history,
@@ -171,20 +172,22 b' class HistoryAccessor(HistoryAccessorBase):'
171 and no background saving thread. This may be necessary in some
172 and no background saving thread. This may be necessary in some
172 threaded environments where IPython is embedded.
173 threaded environments where IPython is embedded.
173 """
174 """
174 )
175 ).tag(config=True)
175
176
176 connection_options = Dict(config=True,
177 connection_options = Dict(
177 help="""Options for configuring the SQLite connection
178 help="""Options for configuring the SQLite connection
178
179
179 These options are passed as keyword args to sqlite3.connect
180 These options are passed as keyword args to sqlite3.connect
180 when establishing database conenctions.
181 when establishing database conenctions.
181 """
182 """
182 )
183 ).tag(config=True)
183
184
184 # The SQLite database
185 # The SQLite database
185 db = Any()
186 db = Any()
186 def _db_changed(self, name, old, new):
187 @observe('db')
188 def _db_changed(self, change):
187 """validate the db, since it can be an Instance of two different types"""
189 """validate the db, since it can be an Instance of two different types"""
190 new = change['new']
188 connection_types = (DummyDB,)
191 connection_types = (DummyDB,)
189 if sqlite3 is not None:
192 if sqlite3 is not None:
190 connection_types = (DummyDB, sqlite3.Connection)
193 connection_types = (DummyDB, sqlite3.Connection)
@@ -479,6 +482,7 b' class HistoryManager(HistoryAccessor):'
479 input_hist_raw = List([""])
482 input_hist_raw = List([""])
480 # A list of directories visited during session
483 # A list of directories visited during session
481 dir_hist = List()
484 dir_hist = List()
485 @default('dir_hist')
482 def _dir_hist_default(self):
486 def _dir_hist_default(self):
483 try:
487 try:
484 return [py3compat.getcwd()]
488 return [py3compat.getcwd()]
@@ -494,13 +498,13 b' class HistoryManager(HistoryAccessor):'
494 # The number of the current session in the history database
498 # The number of the current session in the history database
495 session_number = Integer()
499 session_number = Integer()
496
500
497 db_log_output = Bool(False, config=True,
501 db_log_output = Bool(False,
498 help="Should the history database include output? (default: no)"
502 help="Should the history database include output? (default: no)"
499 )
503 ).tag(config=True)
500 db_cache_size = Integer(0, config=True,
504 db_cache_size = Integer(0,
501 help="Write to database every x commands (higher values save disk access & power).\n"
505 help="Write to database every x commands (higher values save disk access & power).\n"
502 "Values of 1 or less effectively disable caching."
506 "Values of 1 or less effectively disable caching."
503 )
507 ).tag(config=True)
504 # The input and output caches
508 # The input and output caches
505 db_input_cache = List()
509 db_input_cache = List()
506 db_output_cache = List()
510 db_output_cache = List()
@@ -49,7 +49,7 b' from IPython.core.error import InputRejected, UsageError'
49 from IPython.core.extensions import ExtensionManager
49 from IPython.core.extensions import ExtensionManager
50 from IPython.core.formatters import DisplayFormatter
50 from IPython.core.formatters import DisplayFormatter
51 from IPython.core.history import HistoryManager
51 from IPython.core.history import HistoryManager
52 from IPython.core.inputsplitter import IPythonInputSplitter, ESC_MAGIC, ESC_MAGIC2
52 from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
53 from IPython.core.logger import Logger
53 from IPython.core.logger import Logger
54 from IPython.core.macro import Macro
54 from IPython.core.macro import Macro
55 from IPython.core.payload import PayloadManager
55 from IPython.core.payload import PayloadManager
@@ -75,8 +75,10 b' from IPython.utils.strdispatch import StrDispatch'
75 from IPython.utils.syspathcontext import prepended_to_syspath
75 from IPython.utils.syspathcontext import prepended_to_syspath
76 from IPython.utils.text import (format_screen, LSString, SList,
76 from IPython.utils.text import (format_screen, LSString, SList,
77 DollarFormatter)
77 DollarFormatter)
78 from traitlets import (Integer, Bool, CBool, CaselessStrEnum, Enum,
78 from traitlets import (
79 List, Dict, Unicode, Instance, Type)
79 Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type,
80 observe, default,
81 )
80 from warnings import warn
82 from warnings import warn
81 from logging import error
83 from logging import error
82 import IPython.core.hooks
84 import IPython.core.hooks
@@ -114,9 +116,6 b' def no_op(*a, **kw): pass'
114
116
115 class SpaceInInput(Exception): pass
117 class SpaceInInput(Exception): pass
116
118
117 @undoc
118 class Bunch: pass
119
120
119
121 def get_default_colors():
120 def get_default_colors():
122 if sys.platform=='darwin':
121 if sys.platform=='darwin':
@@ -173,14 +172,14 b' class InteractiveShell(SingletonConfigurable):'
173
172
174 _instance = None
173 _instance = None
175
174
176 ast_transformers = List([], config=True, help=
175 ast_transformers = List([], help=
177 """
176 """
178 A list of ast.NodeTransformer subclass instances, which will be applied
177 A list of ast.NodeTransformer subclass instances, which will be applied
179 to user input before code is run.
178 to user input before code is run.
180 """
179 """
181 )
180 ).tag(config=True)
182
181
183 autocall = Enum((0,1,2), default_value=0, config=True, help=
182 autocall = Enum((0,1,2), default_value=0, help=
184 """
183 """
185 Make IPython automatically call any callable object even if you didn't
184 Make IPython automatically call any callable object even if you didn't
186 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
185 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
@@ -189,28 +188,28 b' class InteractiveShell(SingletonConfigurable):'
189 arguments on the line, and '2' for 'full' autocall, where all callable
188 arguments on the line, and '2' for 'full' autocall, where all callable
190 objects are automatically called (even if no arguments are present).
189 objects are automatically called (even if no arguments are present).
191 """
190 """
192 )
191 ).tag(config=True)
193 # TODO: remove all autoindent logic and put into frontends.
192 # TODO: remove all autoindent logic and put into frontends.
194 # We can't do this yet because even runlines uses the autoindent.
193 # We can't do this yet because even runlines uses the autoindent.
195 autoindent = CBool(True, config=True, help=
194 autoindent = Bool(True, help=
196 """
195 """
197 Autoindent IPython code entered interactively.
196 Autoindent IPython code entered interactively.
198 """
197 """
199 )
198 ).tag(config=True)
200 automagic = CBool(True, config=True, help=
199 automagic = Bool(True, help=
201 """
200 """
202 Enable magic commands to be called without the leading %.
201 Enable magic commands to be called without the leading %.
203 """
202 """
204 )
203 ).tag(config=True)
205
204
206 banner1 = Unicode(default_banner, config=True,
205 banner1 = Unicode(default_banner,
207 help="""The part of the banner to be printed before the profile"""
206 help="""The part of the banner to be printed before the profile"""
208 )
207 ).tag(config=True)
209 banner2 = Unicode('', config=True,
208 banner2 = Unicode('',
210 help="""The part of the banner to be printed after the profile"""
209 help="""The part of the banner to be printed after the profile"""
211 )
210 ).tag(config=True)
212
211
213 cache_size = Integer(1000, config=True, help=
212 cache_size = Integer(1000, help=
214 """
213 """
215 Set the size of the output cache. The default is 1000, you can
214 Set the size of the output cache. The default is 1000, you can
216 change it permanently in your config file. Setting it to 0 completely
215 change it permanently in your config file. Setting it to 0 completely
@@ -219,19 +218,19 b' class InteractiveShell(SingletonConfigurable):'
219 issued). This limit is defined because otherwise you'll spend more
218 issued). This limit is defined because otherwise you'll spend more
220 time re-flushing a too small cache than working
219 time re-flushing a too small cache than working
221 """
220 """
222 )
221 ).tag(config=True)
223 color_info = CBool(True, config=True, help=
222 color_info = Bool(True, help=
224 """
223 """
225 Use colors for displaying information about objects. Because this
224 Use colors for displaying information about objects. Because this
226 information is passed through a pager (like 'less'), and some pagers
225 information is passed through a pager (like 'less'), and some pagers
227 get confused with color codes, this capability can be turned off.
226 get confused with color codes, this capability can be turned off.
228 """
227 """
229 )
228 ).tag(config=True)
230 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
229 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
231 default_value=get_default_colors(), config=True,
230 default_value=get_default_colors(),
232 help="Set the color scheme (NoColor, Linux, or LightBG)."
231 help="Set the color scheme (NoColor, Linux, or LightBG)."
233 )
232 ).tag(config=True)
234 colors_force = CBool(False, help=
233 colors_force = Bool(False, help=
235 """
234 """
236 Force use of ANSI color codes, regardless of OS and readline
235 Force use of ANSI color codes, regardless of OS and readline
237 availability.
236 availability.
@@ -240,8 +239,8 b' class InteractiveShell(SingletonConfigurable):'
240 # without readline on Win32. When the ZMQ formatting system is
239 # without readline on Win32. When the ZMQ formatting system is
241 # refactored, this should be removed.
240 # refactored, this should be removed.
242 )
241 )
243 debug = CBool(False, config=True)
242 debug = Bool(False).tag(config=True)
244 deep_reload = CBool(False, config=True, help=
243 deep_reload = Bool(False, help=
245 """
244 """
246 **Deprecated**
245 **Deprecated**
247
246
@@ -255,23 +254,24 b' class InteractiveShell(SingletonConfigurable):'
255 deep_reload is off, IPython will use the normal reload(), but
254 deep_reload is off, IPython will use the normal reload(), but
256 deep_reload will still be available as dreload().
255 deep_reload will still be available as dreload().
257 """
256 """
258 )
257 ).tag(config=True)
259 disable_failing_post_execute = CBool(False, config=True,
258 disable_failing_post_execute = Bool(False,
260 help="Don't call post-execute functions that have failed in the past."
259 help="Don't call post-execute functions that have failed in the past."
261 )
260 ).tag(config=True)
262 display_formatter = Instance(DisplayFormatter, allow_none=True)
261 display_formatter = Instance(DisplayFormatter, allow_none=True)
263 displayhook_class = Type(DisplayHook)
262 displayhook_class = Type(DisplayHook)
264 display_pub_class = Type(DisplayPublisher)
263 display_pub_class = Type(DisplayPublisher)
265 data_pub_class = None
264 data_pub_class = None
266
265
267 exit_now = CBool(False)
266 exit_now = Bool(False)
268 exiter = Instance(ExitAutocall)
267 exiter = Instance(ExitAutocall)
268 @default('exiter')
269 def _exiter_default(self):
269 def _exiter_default(self):
270 return ExitAutocall(self)
270 return ExitAutocall(self)
271 # Monotonically increasing execution counter
271 # Monotonically increasing execution counter
272 execution_count = Integer(1)
272 execution_count = Integer(1)
273 filename = Unicode("<ipython console>")
273 filename = Unicode("<ipython console>")
274 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
274 ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
275
275
276 # Input splitter, to transform input line by line and detect when a block
276 # Input splitter, to transform input line by line and detect when a block
277 # is ready to be executed.
277 # is ready to be executed.
@@ -283,88 +283,91 b' class InteractiveShell(SingletonConfigurable):'
283 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
283 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
284 (), {'line_input_checker': False})
284 (), {'line_input_checker': False})
285
285
286 logstart = CBool(False, config=True, help=
286 logstart = Bool(False, help=
287 """
287 """
288 Start logging to the default log file in overwrite mode.
288 Start logging to the default log file in overwrite mode.
289 Use `logappend` to specify a log file to **append** logs to.
289 Use `logappend` to specify a log file to **append** logs to.
290 """
290 """
291 )
291 ).tag(config=True)
292 logfile = Unicode('', config=True, help=
292 logfile = Unicode('', help=
293 """
293 """
294 The name of the logfile to use.
294 The name of the logfile to use.
295 """
295 """
296 )
296 ).tag(config=True)
297 logappend = Unicode('', config=True, help=
297 logappend = Unicode('', help=
298 """
298 """
299 Start logging to the given file in append mode.
299 Start logging to the given file in append mode.
300 Use `logfile` to specify a log file to **overwrite** logs to.
300 Use `logfile` to specify a log file to **overwrite** logs to.
301 """
301 """
302 )
302 ).tag(config=True)
303 object_info_string_level = Enum((0,1,2), default_value=0,
303 object_info_string_level = Enum((0,1,2), default_value=0,
304 config=True)
304 ).tag(config=True)
305 pdb = CBool(False, config=True, help=
305 pdb = Bool(False, help=
306 """
306 """
307 Automatically call the pdb debugger after every exception.
307 Automatically call the pdb debugger after every exception.
308 """
308 """
309 )
309 ).tag(config=True)
310 multiline_history = CBool(sys.platform != 'win32', config=True,
310 multiline_history = Bool(sys.platform != 'win32',
311 help="Save multi-line entries as one entry in readline history"
311 help="Save multi-line entries as one entry in readline history"
312 )
312 ).tag(config=True)
313 display_page = Bool(False, config=True,
313 display_page = Bool(False,
314 help="""If True, anything that would be passed to the pager
314 help="""If True, anything that would be passed to the pager
315 will be displayed as regular output instead."""
315 will be displayed as regular output instead."""
316 )
316 ).tag(config=True)
317
317
318 # deprecated prompt traits:
318 # deprecated prompt traits:
319
319
320 prompt_in1 = Unicode('In [\\#]: ', config=True,
320 prompt_in1 = Unicode('In [\\#]: ',
321 help="Deprecated, will be removed in IPython 5.0, use PromptManager.in_template")
321 help="Deprecated, will be removed in IPython 5.0, use PromptManager.in_template"
322 prompt_in2 = Unicode(' .\\D.: ', config=True,
322 ).tag(config=True)
323 help="Deprecated, will be removed in IPython 5.0, use PromptManager.in2_template")
323 prompt_in2 = Unicode(' .\\D.: ',
324 prompt_out = Unicode('Out[\\#]: ', config=True,
324 help="Deprecated, will be removed in IPython 5.0, use PromptManager.in2_template"
325 help="Deprecated, will be removed in IPython 5.0, use PromptManager.out_template")
325 ).tag(config=True)
326 prompts_pad_left = CBool(True, config=True,
326 prompt_out = Unicode('Out[\\#]: ',
327 help="Deprecated, will be removed in IPython 5.0, use PromptManager.justify")
327 help="Deprecated, will be removed in IPython 5.0, use PromptManager.out_template"
328 ).tag(config=True)
329 prompts_pad_left = Bool(True,
330 help="Deprecated, will be removed in IPython 5.0, use PromptManager.justify"
331 ).tag(config=True)
328
332
329 def _prompt_trait_changed(self, name, old, new):
333 @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left')
334 def _prompt_trait_changed(self, change):
330 table = {
335 table = {
331 'prompt_in1' : 'in_template',
336 'prompt_in1' : 'in_template',
332 'prompt_in2' : 'in2_template',
337 'prompt_in2' : 'in2_template',
333 'prompt_out' : 'out_template',
338 'prompt_out' : 'out_template',
334 'prompts_pad_left' : 'justify',
339 'prompts_pad_left' : 'justify',
335 }
340 }
341 name = change['name']
336 warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}".format(
342 warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}".format(
337 name=name, newname=table[name])
343 name=name, newname=table[name])
338 )
344 )
339 # protect against weird cases where self.config may not exist:
345 # protect against weird cases where self.config may not exist:
340 if self.config is not None:
346 if self.config is not None:
341 # propagate to corresponding PromptManager trait
347 # propagate to corresponding PromptManager trait
342 setattr(self.config.PromptManager, table[name], new)
348 setattr(self.config.PromptManager, table[name], change['new'])
343
344 _prompt_in1_changed = _prompt_trait_changed
345 _prompt_in2_changed = _prompt_trait_changed
346 _prompt_out_changed = _prompt_trait_changed
347 _prompt_pad_left_changed = _prompt_trait_changed
348
349
349 show_rewritten_input = CBool(True, config=True,
350 show_rewritten_input = Bool(True,
350 help="Show rewritten input, e.g. for autocall."
351 help="Show rewritten input, e.g. for autocall."
351 )
352 ).tag(config=True)
352
353
353 quiet = CBool(False, config=True)
354 quiet = Bool(False).tag(config=True)
354
355
355 history_length = Integer(10000, config=True)
356 history_length = Integer(10000,
357 help='Total length of command history'
358 ).tag(config=True)
356
359
357 history_load_length = Integer(1000, config=True, help=
360 history_load_length = Integer(1000, help=
358 """
361 """
359 The number of saved history entries to be loaded
362 The number of saved history entries to be loaded
360 into the readline buffer at startup.
363 into the readline buffer at startup.
361 """
364 """
362 )
365 ).tag(config=True)
363
366
364 # The readline stuff will eventually be moved to the terminal subclass
367 # The readline stuff will eventually be moved to the terminal subclass
365 # but for now, we can't do that as readline is welded in everywhere.
368 # but for now, we can't do that as readline is welded in everywhere.
366 readline_use = CBool(True, config=True)
369 readline_use = Bool(True).tag(config=True)
367 readline_remove_delims = Unicode('-/~', config=True)
370 readline_remove_delims = Unicode('-/~').tag(config=True)
368 readline_delims = Unicode() # set by init_readline()
371 readline_delims = Unicode() # set by init_readline()
369 # don't use \M- bindings by default, because they
372 # don't use \M- bindings by default, because they
370 # conflict with 8-bit encodings. See gh-58,gh-88
373 # conflict with 8-bit encodings. See gh-58,gh-88
@@ -381,29 +384,31 b' class InteractiveShell(SingletonConfigurable):'
381 '"\e[B": history-search-forward',
384 '"\e[B": history-search-forward',
382 '"\C-k": kill-line',
385 '"\C-k": kill-line',
383 '"\C-u": unix-line-discard',
386 '"\C-u": unix-line-discard',
384 ], config=True)
387 ]).tag(config=True)
385
388
386 _custom_readline_config = False
389 _custom_readline_config = False
387
390
388 def _readline_parse_and_bind_changed(self, name, old, new):
391 @observe('readline_parse_and_bind')
392 def _readline_parse_and_bind_changed(self, change):
389 # notice that readline config is customized
393 # notice that readline config is customized
390 # indicates that it should have higher priority than inputrc
394 # indicates that it should have higher priority than inputrc
391 self._custom_readline_config = True
395 self._custom_readline_config = True
392
396
393 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
397 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
394 default_value='last_expr', config=True,
398 default_value='last_expr',
395 help="""
399 help="""
396 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
400 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
397 run interactively (displaying output from expressions).""")
401 run interactively (displaying output from expressions)."""
402 ).tag(config=True)
398
403
399 # TODO: this part of prompt management should be moved to the frontends.
404 # TODO: this part of prompt management should be moved to the frontends.
400 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
405 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
401 separate_in = SeparateUnicode('\n', config=True)
406 separate_in = SeparateUnicode('\n').tag(config=True)
402 separate_out = SeparateUnicode('', config=True)
407 separate_out = SeparateUnicode('').tag(config=True)
403 separate_out2 = SeparateUnicode('', config=True)
408 separate_out2 = SeparateUnicode('').tag(config=True)
404 wildcards_case_sensitive = CBool(True, config=True)
409 wildcards_case_sensitive = Bool(True).tag(config=True)
405 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
410 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
406 default_value='Context', config=True)
411 default_value='Context').tag(config=True)
407
412
408 # Subcomponents of InteractiveShell
413 # Subcomponents of InteractiveShell
409 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
414 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
@@ -522,9 +527,9 b' class InteractiveShell(SingletonConfigurable):'
522 #-------------------------------------------------------------------------
527 #-------------------------------------------------------------------------
523 # Trait changed handlers
528 # Trait changed handlers
524 #-------------------------------------------------------------------------
529 #-------------------------------------------------------------------------
525
530 @observe('ipython_dir')
526 def _ipython_dir_changed(self, name, new):
531 def _ipython_dir_changed(self, change):
527 ensure_dir_exists(new)
532 ensure_dir_exists(change['new'])
528
533
529 def set_autoindent(self,value=None):
534 def set_autoindent(self,value=None):
530 """Set the autoindent flag.
535 """Set the autoindent flag.
@@ -785,7 +790,7 b' class InteractiveShell(SingletonConfigurable):'
785 def show_banner(self, banner=None):
790 def show_banner(self, banner=None):
786 if banner is None:
791 if banner is None:
787 banner = self.banner
792 banner = self.banner
788 self.write(banner)
793 sys.stdout.write(banner)
789
794
790 #-------------------------------------------------------------------------
795 #-------------------------------------------------------------------------
791 # Things related to hooks
796 # Things related to hooks
@@ -12,17 +12,12 b' from __future__ import print_function'
12 # the file COPYING, distributed as part of this software.
12 # the file COPYING, distributed as part of this software.
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 #-----------------------------------------------------------------------------
16 # Imports
17 #-----------------------------------------------------------------------------
18 # Stdlib
19 import os
15 import os
20 import re
16 import re
21 import sys
17 import sys
22 import types
18 import types
23 from getopt import getopt, GetoptError
19 from getopt import getopt, GetoptError
24
20
25 # Our own
26 from traitlets.config.configurable import Configurable
21 from traitlets.config.configurable import Configurable
27 from IPython.core import oinspect
22 from IPython.core import oinspect
28 from IPython.core.error import UsageError
23 from IPython.core.error import UsageError
@@ -32,7 +27,7 b' from IPython.utils.ipstruct import Struct'
32 from IPython.utils.process import arg_split
27 from IPython.utils.process import arg_split
33 from IPython.utils.py3compat import string_types, iteritems
28 from IPython.utils.py3compat import string_types, iteritems
34 from IPython.utils.text import dedent
29 from IPython.utils.text import dedent
35 from traitlets import Bool, Dict, Instance
30 from traitlets import Bool, Dict, Instance, observe
36 from logging import error
31 from logging import error
37
32
38 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
@@ -303,11 +298,12 b' class MagicsManager(Configurable):'
303
298
304 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
299 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
305
300
306 auto_magic = Bool(True, config=True, help=
301 auto_magic = Bool(True, help=
307 "Automatically call line magics without requiring explicit % prefix")
302 "Automatically call line magics without requiring explicit % prefix"
308
303 ).tag(config=True)
309 def _auto_magic_changed(self, name, value):
304 @observe('auto_magic')
310 self.shell.automagic = value
305 def _auto_magic_changed(self, change):
306 self.shell.automagic = change['new']
311
307
312 _auto_status = [
308 _auto_status = [
313 'Automagic is OFF, % prefix IS needed for line magics.',
309 'Automagic is OFF, % prefix IS needed for line magics.',
@@ -1,18 +1,9 b''
1 """Magic functions for running cells in various scripts."""
1 """Magic functions for running cells in various scripts."""
2 from __future__ import print_function
2 from __future__ import print_function
3 #-----------------------------------------------------------------------------
4 # Copyright (c) 2012 The IPython Development Team.
5 #
6 # Distributed under the terms of the Modified BSD License.
7 #
8 # The full license is in the file COPYING.txt, distributed with this software.
9 #-----------------------------------------------------------------------------
10
3
11 #-----------------------------------------------------------------------------
4 # Copyright (c) IPython Development Team.
12 # Imports
5 # Distributed under the terms of the Modified BSD License.
13 #-----------------------------------------------------------------------------
14
6
15 # Stdlib
16 import errno
7 import errno
17 import os
8 import os
18 import sys
9 import sys
@@ -21,8 +12,6 b' import time'
21 from subprocess import Popen, PIPE
12 from subprocess import Popen, PIPE
22 import atexit
13 import atexit
23
14
24 # Our own packages
25 from traitlets.config.configurable import Configurable
26 from IPython.core import magic_arguments
15 from IPython.core import magic_arguments
27 from IPython.core.magic import (
16 from IPython.core.magic import (
28 Magics, magics_class, line_magic, cell_magic
17 Magics, magics_class, line_magic, cell_magic
@@ -30,7 +19,7 b' from IPython.core.magic import ('
30 from IPython.lib.backgroundjobs import BackgroundJobManager
19 from IPython.lib.backgroundjobs import BackgroundJobManager
31 from IPython.utils import py3compat
20 from IPython.utils import py3compat
32 from IPython.utils.process import arg_split
21 from IPython.utils.process import arg_split
33 from traitlets import List, Dict
22 from traitlets import List, Dict, default
34
23
35 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
36 # Magic implementation classes
25 # Magic implementation classes
@@ -79,7 +68,7 b' class ScriptMagics(Magics):'
79 with a program in a subprocess, and registers a few top-level
68 with a program in a subprocess, and registers a few top-level
80 magics that call %%script with common interpreters.
69 magics that call %%script with common interpreters.
81 """
70 """
82 script_magics = List(config=True,
71 script_magics = List(
83 help="""Extra script cell magics to define
72 help="""Extra script cell magics to define
84
73
85 This generates simple wrappers of `%%script foo` as `%%foo`.
74 This generates simple wrappers of `%%script foo` as `%%foo`.
@@ -87,7 +76,8 b' class ScriptMagics(Magics):'
87 If you want to add script magics that aren't on your path,
76 If you want to add script magics that aren't on your path,
88 specify them in script_paths
77 specify them in script_paths
89 """,
78 """,
90 )
79 ).tag(config=True)
80 @default('script_magics')
91 def _script_magics_default(self):
81 def _script_magics_default(self):
92 """default to a common list of programs"""
82 """default to a common list of programs"""
93
83
@@ -108,13 +98,13 b' class ScriptMagics(Magics):'
108
98
109 return defaults
99 return defaults
110
100
111 script_paths = Dict(config=True,
101 script_paths = Dict(
112 help="""Dict mapping short 'ruby' names to full paths, such as '/opt/secret/bin/ruby'
102 help="""Dict mapping short 'ruby' names to full paths, such as '/opt/secret/bin/ruby'
113
103
114 Only necessary for items in script_magics where the default path will not
104 Only necessary for items in script_magics where the default path will not
115 find the right interpreter.
105 find the right interpreter.
116 """
106 """
117 )
107 ).tag(config=True)
118
108
119 def __init__(self, shell=None):
109 def __init__(self, shell=None):
120 super(ScriptMagics, self).__init__(shell=shell)
110 super(ScriptMagics, self).__init__(shell=shell)
@@ -4,25 +4,10 b' Prefiltering components.'
4
4
5 Prefilters transform user input before it is exec'd by Python. These
5 Prefilters transform user input before it is exec'd by Python. These
6 transforms are used to implement additional syntax such as !ls and %magic.
6 transforms are used to implement additional syntax such as !ls and %magic.
7
8 Authors:
9
10 * Brian Granger
11 * Fernando Perez
12 * Dan Milstein
13 * Ville Vainio
14 """
7 """
15
8
16 #-----------------------------------------------------------------------------
9 # Copyright (c) IPython Development Team.
17 # Copyright (C) 2008-2011 The IPython Development Team
10 # Distributed under the terms of the Modified BSD License.
18 #
19 # Distributed under the terms of the BSD License. The full license is in
20 # the file COPYING, distributed as part of this software.
21 #-----------------------------------------------------------------------------
22
23 #-----------------------------------------------------------------------------
24 # Imports
25 #-----------------------------------------------------------------------------
26
11
27 from keyword import iskeyword
12 from keyword import iskeyword
28 import re
13 import re
@@ -39,7 +24,7 b' from IPython.core.macro import Macro'
39 from IPython.core.splitinput import LineInfo
24 from IPython.core.splitinput import LineInfo
40
25
41 from traitlets import (
26 from traitlets import (
42 List, Integer, Unicode, CBool, Bool, Instance, CRegExp
27 List, Integer, Unicode, Bool, Instance, CRegExp
43 )
28 )
44
29
45 #-----------------------------------------------------------------------------
30 #-----------------------------------------------------------------------------
@@ -129,7 +114,7 b' class PrefilterManager(Configurable):'
129 or :meth:`sort_transformers` method after changing the priority.
114 or :meth:`sort_transformers` method after changing the priority.
130 """
115 """
131
116
132 multi_line_specials = CBool(True).tag(config=True)
117 multi_line_specials = Bool(True).tag(config=True)
133 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
118 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
134
119
135 def __init__(self, shell=None, **kwargs):
120 def __init__(self, shell=None, **kwargs):
@@ -12,7 +12,7 b' from traitlets.config.configurable import LoggingConfigurable'
12 from IPython.paths import get_ipython_package_dir
12 from IPython.paths import get_ipython_package_dir
13 from IPython.utils.path import expand_path, ensure_dir_exists
13 from IPython.utils.path import expand_path, ensure_dir_exists
14 from IPython.utils import py3compat
14 from IPython.utils import py3compat
15 from traitlets import Unicode, Bool
15 from traitlets import Unicode, Bool, observe
16
16
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18 # Module errors
18 # Module errors
@@ -47,17 +47,18 b' class ProfileDir(LoggingConfigurable):'
47 pid_dir = Unicode(u'')
47 pid_dir = Unicode(u'')
48 static_dir = Unicode(u'')
48 static_dir = Unicode(u'')
49
49
50 location = Unicode(u'', config=True,
50 location = Unicode(u'',
51 help="""Set the profile location directly. This overrides the logic used by the
51 help="""Set the profile location directly. This overrides the logic used by the
52 `profile` option.""",
52 `profile` option.""",
53 )
53 ).tag(config=True)
54
54
55 _location_isset = Bool(False) # flag for detecting multiply set location
55 _location_isset = Bool(False) # flag for detecting multiply set location
56
56 @observe('location')
57 def _location_changed(self, name, old, new):
57 def _location_changed(self, change):
58 if self._location_isset:
58 if self._location_isset:
59 raise RuntimeError("Cannot set profile location more than once.")
59 raise RuntimeError("Cannot set profile location more than once.")
60 self._location_isset = True
60 self._location_isset = True
61 new = change['new']
61 ensure_dir_exists(new)
62 ensure_dir_exists(new)
62
63
63 # ensure config files exist:
64 # ensure config files exist:
@@ -67,10 +68,7 b' class ProfileDir(LoggingConfigurable):'
67 self.pid_dir = os.path.join(new, self.pid_dir_name)
68 self.pid_dir = os.path.join(new, self.pid_dir_name)
68 self.static_dir = os.path.join(new, self.static_dir_name)
69 self.static_dir = os.path.join(new, self.static_dir_name)
69 self.check_dirs()
70 self.check_dirs()
70
71
71 def _log_dir_changed(self, name, old, new):
72 self.check_log_dir()
73
74 def _mkdir(self, path, mode=None):
72 def _mkdir(self, path, mode=None):
75 """ensure a directory exists at a given path
73 """ensure a directory exists at a given path
76
74
@@ -104,14 +102,13 b' class ProfileDir(LoggingConfigurable):'
104 raise
102 raise
105
103
106 return True
104 return True
107
105
108 def check_log_dir(self):
106 @observe('log_dir')
107 def check_log_dir(self, change=None):
109 self._mkdir(self.log_dir)
108 self._mkdir(self.log_dir)
110
109
111 def _startup_dir_changed(self, name, old, new):
110 @observe('startup_dir')
112 self.check_startup_dir()
111 def check_startup_dir(self, change=None):
113
114 def check_startup_dir(self):
115 self._mkdir(self.startup_dir)
112 self._mkdir(self.startup_dir)
116
113
117 readme = os.path.join(self.startup_dir, 'README')
114 readme = os.path.join(self.startup_dir, 'README')
@@ -123,21 +120,14 b' class ProfileDir(LoggingConfigurable):'
123 if os.path.exists(src) and not os.path.exists(readme):
120 if os.path.exists(src) and not os.path.exists(readme):
124 shutil.copy(src, readme)
121 shutil.copy(src, readme)
125
122
126 def _security_dir_changed(self, name, old, new):
123 @observe('security_dir')
127 self.check_security_dir()
124 def check_security_dir(self, change=None):
128
129 def check_security_dir(self):
130 self._mkdir(self.security_dir, 0o40700)
125 self._mkdir(self.security_dir, 0o40700)
131
126
132 def _pid_dir_changed(self, name, old, new):
127 @observe('pid_dir')
133 self.check_pid_dir()
128 def check_pid_dir(self, change=None):
134
135 def check_pid_dir(self):
136 self._mkdir(self.pid_dir, 0o40700)
129 self._mkdir(self.pid_dir, 0o40700)
137
130
138 def _static_dir_changed(self, name, old, new):
139 self.check_startup_dir()
140
141 def check_dirs(self):
131 def check_dirs(self):
142 self.check_security_dir()
132 self.check_security_dir()
143 self.check_log_dir()
133 self.check_log_dir()
@@ -1,24 +1,9 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Classes for handling input/output prompts.
2 """Classes for handling input/output prompts."""
3
3
4 Authors:
4 # Copyright (c) 2001-2007 Fernando Perez <fperez@colorado.edu>
5
5 # Copyright (c) IPython Development Team.
6 * Fernando Perez
6 # Distributed under the terms of the Modified BSD License.
7 * Brian Granger
8 * Thomas Kluyver
9 """
10
11 #-----------------------------------------------------------------------------
12 # Copyright (C) 2008-2011 The IPython Development Team
13 # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu>
14 #
15 # Distributed under the terms of the BSD License. The full license is in
16 # the file COPYING, distributed as part of this software.
17 #-----------------------------------------------------------------------------
18
19 #-----------------------------------------------------------------------------
20 # Imports
21 #-----------------------------------------------------------------------------
22
7
23 import os
8 import os
24 import re
9 import re
@@ -31,7 +16,7 b' from string import Formatter'
31 from traitlets.config.configurable import Configurable
16 from traitlets.config.configurable import Configurable
32 from IPython.core import release
17 from IPython.core import release
33 from IPython.utils import coloransi, py3compat
18 from IPython.utils import coloransi, py3compat
34 from traitlets import Unicode, Instance, Dict, Bool, Int, observe
19 from traitlets import Unicode, Instance, Dict, Bool, Int, observe, default
35
20
36 from IPython.utils.PyColorize import LightBGColors, LinuxColors, NoColor
21 from IPython.utils.PyColorize import LightBGColors, LinuxColors, NoColor
37
22
@@ -271,7 +256,6 b' class PromptManager(Configurable):'
271 things like the current time in the prompts. Functions are only called
256 things like the current time in the prompts. Functions are only called
272 if they are used in the prompt.
257 if they are used in the prompt.
273 """)
258 """)
274 def _lazy_evaluate_fields_default(self): return lazily_evaluate.copy()
275
259
276 in_template = Unicode('In [\\#]: ',
260 in_template = Unicode('In [\\#]: ',
277 help="Input prompt. '\\#' will be transformed to the prompt number"
261 help="Input prompt. '\\#' will be transformed to the prompt number"
@@ -282,6 +266,10 b' class PromptManager(Configurable):'
282 help="Output prompt. '\\#' will be transformed to the prompt number"
266 help="Output prompt. '\\#' will be transformed to the prompt number"
283 ).tag(config=True)
267 ).tag(config=True)
284
268
269 @default('lazy_evaluate_fields')
270 def _lazy_evaluate_fields_default(self):
271 return lazily_evaluate.copy()
272
285 justify = Bool(True, help="""
273 justify = Bool(True, help="""
286 If True (default), each prompt will be right-aligned with the
274 If True (default), each prompt will be right-aligned with the
287 preceding one.
275 preceding one.
@@ -297,6 +285,7 b' class PromptManager(Configurable):'
297
285
298 # The number of characters in each prompt which don't contribute to width
286 # The number of characters in each prompt which don't contribute to width
299 invisible_chars = Dict()
287 invisible_chars = Dict()
288 @default('invisible_chars')
300 def _invisible_chars_default(self):
289 def _invisible_chars_default(self):
301 return {'in': 0, 'in2': 0, 'out': 0, 'rewrite':0}
290 return {'in': 0, 'in2': 0, 'out': 0, 'rewrite':0}
302
291
@@ -313,8 +302,8 b' class PromptManager(Configurable):'
313 self.update_prompt('in2', self.in2_template)
302 self.update_prompt('in2', self.in2_template)
314 self.update_prompt('out', self.out_template)
303 self.update_prompt('out', self.out_template)
315 self.update_prompt('rewrite')
304 self.update_prompt('rewrite')
316 self.on_trait_change(self._update_prompt_trait, ['in_template',
305 self.observe(self._update_prompt_trait,
317 'in2_template', 'out_template'])
306 names=['in_template', 'in2_template', 'out_template'])
318
307
319 def update_prompt(self, name, new_template=None):
308 def update_prompt(self, name, new_template=None):
320 """This is called when a prompt template is updated. It processes
309 """This is called when a prompt template is updated. It processes
@@ -22,7 +22,7 b' from IPython.utils import py3compat'
22 from IPython.utils.contexts import preserve_keys
22 from IPython.utils.contexts import preserve_keys
23 from IPython.utils.path import filefind
23 from IPython.utils.path import filefind
24 from traitlets import (
24 from traitlets import (
25 Unicode, Instance, List, Bool, CaselessStrEnum
25 Unicode, Instance, List, Bool, CaselessStrEnum, default, observe,
26 )
26 )
27 from IPython.lib.inputhook import guis
27 from IPython.lib.inputhook import guis
28
28
@@ -135,76 +135,73 b' class InteractiveShellApp(Configurable):'
135 - :meth:`init_extensions`
135 - :meth:`init_extensions`
136 - :meth:`init_code`
136 - :meth:`init_code`
137 """
137 """
138 extensions = List(Unicode(), config=True,
138 extensions = List(Unicode(),
139 help="A list of dotted module names of IPython extensions to load."
139 help="A list of dotted module names of IPython extensions to load."
140 )
140 ).tag(config=True)
141 extra_extension = Unicode('', config=True,
141 extra_extension = Unicode('',
142 help="dotted module name of an IPython extension to load."
142 help="dotted module name of an IPython extension to load."
143 )
143 ).tag(config=True)
144
144
145 reraise_ipython_extension_failures = Bool(
145 reraise_ipython_extension_failures = Bool(False,
146 False,
147 config=True,
148 help="Reraise exceptions encountered loading IPython extensions?",
146 help="Reraise exceptions encountered loading IPython extensions?",
149 )
147 ).tag(config=True)
150
148
151 # Extensions that are always loaded (not configurable)
149 # Extensions that are always loaded (not configurable)
152 default_extensions = List(Unicode(), [u'storemagic'], config=False)
150 default_extensions = List(Unicode(), [u'storemagic']).tag(config=False)
153
151
154 hide_initial_ns = Bool(True, config=True,
152 hide_initial_ns = Bool(True,
155 help="""Should variables loaded at startup (by startup files, exec_lines, etc.)
153 help="""Should variables loaded at startup (by startup files, exec_lines, etc.)
156 be hidden from tools like %who?"""
154 be hidden from tools like %who?"""
157 )
155 ).tag(config=True)
158
156
159 exec_files = List(Unicode(), config=True,
157 exec_files = List(Unicode(),
160 help="""List of files to run at IPython startup."""
158 help="""List of files to run at IPython startup."""
161 )
159 ).tag(config=True)
162 exec_PYTHONSTARTUP = Bool(True, config=True,
160 exec_PYTHONSTARTUP = Bool(True,
163 help="""Run the file referenced by the PYTHONSTARTUP environment
161 help="""Run the file referenced by the PYTHONSTARTUP environment
164 variable at IPython startup."""
162 variable at IPython startup."""
165 )
163 ).tag(config=True)
166 file_to_run = Unicode('', config=True,
164 file_to_run = Unicode('',
167 help="""A file to be run""")
165 help="""A file to be run""").tag(config=True)
168
166
169 exec_lines = List(Unicode(), config=True,
167 exec_lines = List(Unicode(),
170 help="""lines of code to run at IPython startup."""
168 help="""lines of code to run at IPython startup."""
171 )
169 ).tag(config=True)
172 code_to_run = Unicode('', config=True,
170 code_to_run = Unicode('',
173 help="Execute the given command string."
171 help="Execute the given command string."
174 )
172 ).tag(config=True)
175 module_to_run = Unicode('', config=True,
173 module_to_run = Unicode('',
176 help="Run the module as a script."
174 help="Run the module as a script."
177 )
175 ).tag(config=True)
178 gui = CaselessStrEnum(gui_keys, config=True, allow_none=True,
176 gui = CaselessStrEnum(gui_keys, allow_none=True,
179 help="Enable GUI event loop integration with any of {0}.".format(gui_keys)
177 help="Enable GUI event loop integration with any of {0}.".format(gui_keys)
180 )
178 ).tag(config=True)
181 matplotlib = CaselessStrEnum(backend_keys, allow_none=True,
179 matplotlib = CaselessStrEnum(backend_keys, allow_none=True,
182 config=True,
183 help="""Configure matplotlib for interactive use with
180 help="""Configure matplotlib for interactive use with
184 the default matplotlib backend."""
181 the default matplotlib backend."""
185 )
182 ).tag(config=True)
186 pylab = CaselessStrEnum(backend_keys, allow_none=True,
183 pylab = CaselessStrEnum(backend_keys, allow_none=True,
187 config=True,
188 help="""Pre-load matplotlib and numpy for interactive use,
184 help="""Pre-load matplotlib and numpy for interactive use,
189 selecting a particular matplotlib backend and loop integration.
185 selecting a particular matplotlib backend and loop integration.
190 """
186 """
191 )
187 ).tag(config=True)
192 pylab_import_all = Bool(True, config=True,
188 pylab_import_all = Bool(True,
193 help="""If true, IPython will populate the user namespace with numpy, pylab, etc.
189 help="""If true, IPython will populate the user namespace with numpy, pylab, etc.
194 and an ``import *`` is done from numpy and pylab, when using pylab mode.
190 and an ``import *`` is done from numpy and pylab, when using pylab mode.
195
191
196 When False, pylab mode should not import any names into the user namespace.
192 When False, pylab mode should not import any names into the user namespace.
197 """
193 """
198 )
194 ).tag(config=True)
199 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
195 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
200 allow_none=True)
196 allow_none=True)
201 # whether interact-loop should start
197 # whether interact-loop should start
202 interact = Bool(True)
198 interact = Bool(True)
203
199
204 user_ns = Instance(dict, args=None, allow_none=True)
200 user_ns = Instance(dict, args=None, allow_none=True)
205 def _user_ns_changed(self, name, old, new):
201 @observe('user_ns')
202 def _user_ns_changed(self, change):
206 if self.shell is not None:
203 if self.shell is not None:
207 self.shell.user_ns = new
204 self.shell.user_ns = change['new']
208 self.shell.init_user_ns()
205 self.shell.init_user_ns()
209
206
210 def init_path(self):
207 def init_path(self):
@@ -10,30 +10,17 b' To automatically restore stored variables at startup, add this to your'
10 c.StoreMagics.autorestore = True
10 c.StoreMagics.autorestore = True
11 """
11 """
12 from __future__ import print_function
12 from __future__ import print_function
13 #-----------------------------------------------------------------------------
13
14 # Copyright (c) 2012, The IPython Development Team.
14 # Copyright (c) IPython Development Team.
15 #
15 # Distributed under the terms of the Modified BSD License.
16 # Distributed under the terms of the Modified BSD License.
16
17 #
18 # The full license is in the file COPYING.txt, distributed with this software.
19 #-----------------------------------------------------------------------------
20
21 #-----------------------------------------------------------------------------
22 # Imports
23 #-----------------------------------------------------------------------------
24
25 # Stdlib
26 import inspect, os, sys, textwrap
17 import inspect, os, sys, textwrap
27
18
28 # Our own
29 from IPython.core.error import UsageError
19 from IPython.core.error import UsageError
30 from IPython.core.magic import Magics, magics_class, line_magic
20 from IPython.core.magic import Magics, magics_class, line_magic
31 from traitlets import Bool
21 from traitlets import Bool
32 from IPython.utils.py3compat import string_types
22 from IPython.utils.py3compat import string_types
33
23
34 #-----------------------------------------------------------------------------
35 # Functions and classes
36 #-----------------------------------------------------------------------------
37
24
38 def restore_aliases(ip):
25 def restore_aliases(ip):
39 staliases = ip.db.get('stored_aliases', {})
26 staliases = ip.db.get('stored_aliases', {})
@@ -74,11 +61,11 b' class StoreMagics(Magics):'
74
61
75 Provides the %store magic."""
62 Provides the %store magic."""
76
63
77 autorestore = Bool(False, config=True, help=
64 autorestore = Bool(False, help=
78 """If True, any %store-d variables will be automatically restored
65 """If True, any %store-d variables will be automatically restored
79 when IPython starts.
66 when IPython starts.
80 """
67 """
81 )
68 ).tag(config=True)
82
69
83 def __init__(self, shell):
70 def __init__(self, shell):
84 super(StoreMagics, self).__init__(shell=shell)
71 super(StoreMagics, self).__init__(shell=shell)
@@ -14,6 +14,7 b' from __future__ import print_function'
14 import logging
14 import logging
15 import os
15 import os
16 import sys
16 import sys
17 import warnings
17
18
18 from traitlets.config.loader import Config
19 from traitlets.config.loader import Config
19 from traitlets.config.application import boolean_flag, catch_config_error, Application
20 from traitlets.config.application import boolean_flag, catch_config_error, Application
@@ -33,10 +34,9 b' from IPython.core.shellapp import ('
33 )
34 )
34 from IPython.extensions.storemagic import StoreMagics
35 from IPython.extensions.storemagic import StoreMagics
35 from .ptshell import TerminalInteractiveShell
36 from .ptshell import TerminalInteractiveShell
36 from IPython.utils import warn
37 from IPython.paths import get_ipython_dir
37 from IPython.paths import get_ipython_dir
38 from traitlets import (
38 from traitlets import (
39 Bool, List, Dict,
39 Bool, List, Dict, default, observe,
40 )
40 )
41
41
42 #-----------------------------------------------------------------------------
42 #-----------------------------------------------------------------------------
@@ -183,6 +183,7 b' class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):'
183 flags = Dict(flags)
183 flags = Dict(flags)
184 aliases = Dict(aliases)
184 aliases = Dict(aliases)
185 classes = List()
185 classes = List()
186 @default('classes')
186 def _classes_default(self):
187 def _classes_default(self):
187 """This has to be in a method, for TerminalIPythonApp to be available."""
188 """This has to be in a method, for TerminalIPythonApp to be available."""
188 return [
189 return [
@@ -241,35 +242,37 b' class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):'
241 # *do* autocreate requested profile, but don't create the config file.
242 # *do* autocreate requested profile, but don't create the config file.
242 auto_create=Bool(True)
243 auto_create=Bool(True)
243 # configurables
244 # configurables
244 quick = Bool(False, config=True,
245 quick = Bool(False,
245 help="""Start IPython quickly by skipping the loading of config files."""
246 help="""Start IPython quickly by skipping the loading of config files."""
246 )
247 ).tag(config=True)
247 def _quick_changed(self, name, old, new):
248 @observe('quick')
248 if new:
249 def _quick_changed(self, change):
250 if change['new']:
249 self.load_config_file = lambda *a, **kw: None
251 self.load_config_file = lambda *a, **kw: None
250
252
251 display_banner = Bool(True, config=True,
253 display_banner = Bool(True,
252 help="Whether to display a banner upon starting IPython."
254 help="Whether to display a banner upon starting IPython."
253 )
255 ).tag(config=True)
254
256
255 # if there is code of files to run from the cmd line, don't interact
257 # if there is code of files to run from the cmd line, don't interact
256 # unless the --i flag (App.force_interact) is true.
258 # unless the --i flag (App.force_interact) is true.
257 force_interact = Bool(False, config=True,
259 force_interact = Bool(False,
258 help="""If a command or file is given via the command-line,
260 help="""If a command or file is given via the command-line,
259 e.g. 'ipython foo.py', start an interactive shell after executing the
261 e.g. 'ipython foo.py', start an interactive shell after executing the
260 file or command."""
262 file or command."""
261 )
263 ).tag(config=True)
262 def _force_interact_changed(self, name, old, new):
264 @observe('force_interact')
263 if new:
265 def _force_interact_changed(self, change):
266 if change['new']:
264 self.interact = True
267 self.interact = True
265
268
266 def _file_to_run_changed(self, name, old, new):
269 @observe('file_to_run', 'code_to_run', 'module_to_run')
270 def _file_to_run_changed(self, change):
271 new = change['new']
267 if new:
272 if new:
268 self.something_to_run = True
273 self.something_to_run = True
269 if new and not self.force_interact:
274 if new and not self.force_interact:
270 self.interact = False
275 self.interact = False
271 _code_to_run_changed = _file_to_run_changed
272 _module_to_run_changed = _file_to_run_changed
273
276
274 # internal, not-configurable
277 # internal, not-configurable
275 something_to_run=Bool(False)
278 something_to_run=Bool(False)
@@ -284,7 +287,7 b' class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):'
284 # warn and transform into current syntax
287 # warn and transform into current syntax
285 argv = argv[:] # copy, don't clobber
288 argv = argv[:] # copy, don't clobber
286 idx = argv.index('-pylab')
289 idx = argv.index('-pylab')
287 warn.warn("`-pylab` flag has been deprecated.\n"
290 warnings.warn("`-pylab` flag has been deprecated.\n"
288 " Use `--matplotlib <backend>` and import pylab manually.")
291 " Use `--matplotlib <backend>` and import pylab manually.")
289 argv[idx] = '--pylab'
292 argv[idx] = '--pylab'
290
293
@@ -331,7 +334,7 b' class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):'
331 def _pylab_changed(self, name, old, new):
334 def _pylab_changed(self, name, old, new):
332 """Replace --pylab='inline' with --pylab='auto'"""
335 """Replace --pylab='inline' with --pylab='auto'"""
333 if new == 'inline':
336 if new == 'inline':
334 warn.warn("'inline' not available as pylab backend, "
337 warnings.warn("'inline' not available as pylab backend, "
335 "using 'auto' instead.")
338 "using 'auto' instead.")
336 self.pylab = 'auto'
339 self.pylab = 'auto'
337
340
@@ -13,7 +13,7 b' from IPython.core.interactiveshell import InteractiveShell'
13 from IPython.utils.py3compat import PY3, cast_unicode_py2, input
13 from IPython.utils.py3compat import PY3, cast_unicode_py2, input
14 from IPython.utils.terminal import toggle_set_term_title, set_term_title
14 from IPython.utils.terminal import toggle_set_term_title, set_term_title
15 from IPython.utils.process import abbrev_cwd
15 from IPython.utils.process import abbrev_cwd
16 from traitlets import Bool, CBool, Unicode, Dict, Integer, observe
16 from traitlets import Bool, Unicode, Dict, Integer, observe
17
17
18 from prompt_toolkit.completion import Completer, Completion
18 from prompt_toolkit.completion import Completer, Completion
19 from prompt_toolkit.enums import DEFAULT_BUFFER, SEARCH_BUFFER, EditingMode
19 from prompt_toolkit.enums import DEFAULT_BUFFER, SEARCH_BUFFER, EditingMode
@@ -100,15 +100,18 b' class TerminalInteractiveShell(InteractiveShell):'
100
100
101 pt_cli = None
101 pt_cli = None
102
102
103 autoedit_syntax = CBool(False).tag(config=True,
103 autoedit_syntax = Bool(False,
104 help="auto editing of files with syntax errors.")
104 help="auto editing of files with syntax errors.",
105 ).tag(config=True)
106
105
107
106 confirm_exit = CBool(True).tag(config=True,
108 confirm_exit = Bool(True,
107 help="""
109 help="""
108 Set to confirm when you try to exit IPython with an EOF (Control-D
110 Set to confirm when you try to exit IPython with an EOF (Control-D
109 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
111 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
110 you can force a direct exit without any confirmation.""",
112 you can force a direct exit without any confirmation.""",
111 )
113 ).tag(config=True)
114
112 editing_mode = Unicode('emacs',
115 editing_mode = Unicode('emacs',
113 help="Shortcut style to use at the prompt. 'vi' or 'emacs'.",
116 help="Shortcut style to use at the prompt. 'vi' or 'emacs'.",
114 ).tag(config=True)
117 ).tag(config=True)
@@ -121,7 +124,9 b' class TerminalInteractiveShell(InteractiveShell):'
121 help="The name of a Pygments style to use for syntax highlighting: \n %s" % ', '.join(get_all_styles())
124 help="The name of a Pygments style to use for syntax highlighting: \n %s" % ', '.join(get_all_styles())
122 ).tag(config=True)
125 ).tag(config=True)
123
126
124 def _highlighting_style_changed(self, old, new):
127
128 @observe('highlighting_style')
129 def _highlighting_style_changed(self, change):
125 self._style = self._make_style_from_name(self.highlighting_style)
130 self._style = self._make_style_from_name(self.highlighting_style)
126
131
127 highlighting_style_overrides = Dict(
132 highlighting_style_overrides = Dict(
@@ -140,11 +145,9 b' class TerminalInteractiveShell(InteractiveShell):'
140 help="Display a multi column completion menu.",
145 help="Display a multi column completion menu.",
141 ).tag(config=True)
146 ).tag(config=True)
142
147
143 @observe('term_title')
144 def _term_title_changed(self, change):
145 self.init_term_title()
146
148
147 def init_term_title(self):
149 @observe('term_title')
150 def init_term_title(self, change=None):
148 # Enable or disable the terminal title.
151 # Enable or disable the terminal title.
149 if self.term_title:
152 if self.term_title:
150 toggle_set_term_title(True)
153 toggle_set_term_title(True)
@@ -22,5 +22,5 b' class Colorable(Configurable):'
22 """
22 """
23 A subclass of configurable for all the classes that have a `default_scheme`
23 A subclass of configurable for all the classes that have a `default_scheme`
24 """
24 """
25 default_style=Unicode('lightbg', config=True)
25 default_style=Unicode('lightbg').tag(config=True)
26
26
General Comments 0
You need to be logged in to leave comments. Login now