##// END OF EJS Templates
Improve decorator docstrings and clarify execution context for function decos.
Fernando Perez -
Show More
@@ -1,473 +1,485 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Magic functions for InteractiveShell.
2 """Magic functions for InteractiveShell.
3 """
3 """
4
4
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
6 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
7 # Copyright (C) 2001 Fernando Perez <fperez@colorado.edu>
7 # Copyright (C) 2001 Fernando Perez <fperez@colorado.edu>
8 # Copyright (C) 2008 The IPython Development Team
8 # Copyright (C) 2008 The IPython Development Team
9
9
10 # Distributed under the terms of the BSD License. The full license is in
10 # Distributed under the terms of the BSD License. The full license is in
11 # the file COPYING, distributed as part of this software.
11 # the file COPYING, distributed as part of this software.
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 #-----------------------------------------------------------------------------
14 #-----------------------------------------------------------------------------
15 # Imports
15 # Imports
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17 # Stdlib
17 # Stdlib
18 import os
18 import os
19 import re
19 import re
20 import sys
20 import sys
21 import types
21 import types
22 from getopt import getopt, GetoptError
22 from getopt import getopt, GetoptError
23
23
24 # Our own
24 # Our own
25 from IPython.config.configurable import Configurable
25 from IPython.config.configurable import Configurable
26 from IPython.core import oinspect
26 from IPython.core import oinspect
27 from IPython.core.error import UsageError
27 from IPython.core.error import UsageError
28 from IPython.core.prefilter import ESC_MAGIC
28 from IPython.core.prefilter import ESC_MAGIC
29 from IPython.external.decorator import decorator
29 from IPython.external.decorator import decorator
30 from IPython.utils.ipstruct import Struct
30 from IPython.utils.ipstruct import Struct
31 from IPython.utils.process import arg_split
31 from IPython.utils.process import arg_split
32 from IPython.utils.text import dedent
32 from IPython.utils.traitlets import Bool, Dict, Instance
33 from IPython.utils.traitlets import Bool, Dict, Instance
33 from IPython.utils.warn import error, warn
34 from IPython.utils.warn import error, warn
34
35
35 #-----------------------------------------------------------------------------
36 #-----------------------------------------------------------------------------
36 # Globals
37 # Globals
37 #-----------------------------------------------------------------------------
38 #-----------------------------------------------------------------------------
38
39
39 # A dict we'll use for each class that has magics, used as temporary storage to
40 # A dict we'll use for each class that has magics, used as temporary storage to
40 # pass information between the @line/cell_magic method decorators and the
41 # pass information between the @line/cell_magic method decorators and the
41 # @magics_class class decorator, because the method decorators have no
42 # @magics_class class decorator, because the method decorators have no
42 # access to the class when they run. See for more details:
43 # access to the class when they run. See for more details:
43 # http://stackoverflow.com/questions/2366713/can-a-python-decorator-of-an-instance-method-access-the-class
44 # http://stackoverflow.com/questions/2366713/can-a-python-decorator-of-an-instance-method-access-the-class
44
45
45 magics = dict(line={}, cell={})
46 magics = dict(line={}, cell={})
46
47
47 magic_kinds = ('line', 'cell')
48 magic_kinds = ('line', 'cell')
48 magic_spec = ('line', 'cell', 'line_cell')
49 magic_spec = ('line', 'cell', 'line_cell')
49
50
50 #-----------------------------------------------------------------------------
51 #-----------------------------------------------------------------------------
51 # Utility classes and functions
52 # Utility classes and functions
52 #-----------------------------------------------------------------------------
53 #-----------------------------------------------------------------------------
53
54
54 class Bunch: pass
55 class Bunch: pass
55
56
56
57
57 def on_off(tag):
58 def on_off(tag):
58 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
59 """Return an ON/OFF string for a 1/0 input. Simple utility function."""
59 return ['OFF','ON'][tag]
60 return ['OFF','ON'][tag]
60
61
61
62
62 def compress_dhist(dh):
63 def compress_dhist(dh):
63 head, tail = dh[:-10], dh[-10:]
64 head, tail = dh[:-10], dh[-10:]
64
65
65 newhead = []
66 newhead = []
66 done = set()
67 done = set()
67 for h in head:
68 for h in head:
68 if h in done:
69 if h in done:
69 continue
70 continue
70 newhead.append(h)
71 newhead.append(h)
71 done.add(h)
72 done.add(h)
72
73
73 return newhead + tail
74 return newhead + tail
74
75
75
76
76 def needs_local_scope(func):
77 def needs_local_scope(func):
77 """Decorator to mark magic functions which need to local scope to run."""
78 """Decorator to mark magic functions which need to local scope to run."""
78 func.needs_local_scope = True
79 func.needs_local_scope = True
79 return func
80 return func
80
81
81 #-----------------------------------------------------------------------------
82 #-----------------------------------------------------------------------------
82 # Class and method decorators for registering magics
83 # Class and method decorators for registering magics
83 #-----------------------------------------------------------------------------
84 #-----------------------------------------------------------------------------
84
85
85 def magics_class(cls):
86 def magics_class(cls):
86 cls.registered = True
87 cls.registered = True
87 cls.magics = dict(line = magics['line'],
88 cls.magics = dict(line = magics['line'],
88 cell = magics['cell'])
89 cell = magics['cell'])
89 magics['line'] = {}
90 magics['line'] = {}
90 magics['cell'] = {}
91 magics['cell'] = {}
91 return cls
92 return cls
92
93
93
94
94 def record_magic(dct, mtype, mname, func):
95 def record_magic(dct, mtype, mname, func):
95 if mtype == 'line_cell':
96 if mtype == 'line_cell':
96 dct['line'][mname] = dct['cell'][mname] = func
97 dct['line'][mname] = dct['cell'][mname] = func
97 else:
98 else:
98 dct[mtype][mname] = func
99 dct[mtype][mname] = func
99
100
100
101
101 def validate_type(magic_kind):
102 def validate_type(magic_kind):
102 if magic_kind not in magic_spec:
103 if magic_kind not in magic_spec:
103 raise ValueError('magic_kind must be one of %s, %s given' %
104 raise ValueError('magic_kind must be one of %s, %s given' %
104 magic_kinds, magic_kind)
105 magic_kinds, magic_kind)
105
106
106
107
107 # The docstrings for the decorator below will be fairly similar for the two
108 # The docstrings for the decorator below will be fairly similar for the two
108 # types (method and function), so we generate them here once and reuse the
109 # types (method and function), so we generate them here once and reuse the
109 # templates below.
110 # templates below.
110 _docstring_template = \
111 _docstring_template = \
111 """Decorate the given {0} as {1} magic.
112 """Decorate the given {0} as {1} magic.
112
113
113 The decorator can be used:
114 The decorator can be used with or without arguments, as follows.
114
115
115 i) without arguments: it will create a {1} magic named as the {0} being
116 i) without arguments: it will create a {1} magic named as the {0} being
116 decorated::
117 decorated::
117
118
118 @deco
119 @deco
119 def foo(...)
120 def foo(...)
120
121
121 will create a {1} magic named `foo`.
122 will create a {1} magic named `foo`.
122
123
123 ii) with one string argument: which will be used as the actual name of the
124 ii) with one string argument: which will be used as the actual name of the
124 resulting magic::
125 resulting magic::
125
126
126 @deco('bar')
127 @deco('bar')
127 def foo(...)
128 def foo(...)
128
129
129 will create a {1} magic named `bar`.
130 will create a {1} magic named `bar`.
130 """
131 """
131
132
132 # These two are decorator factories. While they are conceptually very similar,
133 # These two are decorator factories. While they are conceptually very similar,
133 # there are enough differences in the details that it's simpler to have them
134 # there are enough differences in the details that it's simpler to have them
134 # written as completely standalone functions rather than trying to share code
135 # written as completely standalone functions rather than trying to share code
135 # and make a single one with convoluted logic.
136 # and make a single one with convoluted logic.
136
137
137 def _method_magic_marker(magic_kind):
138 def _method_magic_marker(magic_kind):
138 """Decorator factory for methods in Magics subclasses.
139 """Decorator factory for methods in Magics subclasses.
139 """
140 """
140
141
141 validate_type(magic_kind)
142 validate_type(magic_kind)
142
143
143 # This is a closure to capture the magic_kind. We could also use a class,
144 # This is a closure to capture the magic_kind. We could also use a class,
144 # but it's overkill for just that one bit of state.
145 # but it's overkill for just that one bit of state.
145 def magic_deco(arg):
146 def magic_deco(arg):
146 call = lambda f, *a, **k: f(*a, **k)
147 call = lambda f, *a, **k: f(*a, **k)
147
148
148 if callable(arg):
149 if callable(arg):
149 # "Naked" decorator call (just @foo, no args)
150 # "Naked" decorator call (just @foo, no args)
150 func = arg
151 func = arg
151 name = func.func_name
152 name = func.func_name
152 retval = decorator(call, func)
153 retval = decorator(call, func)
153 record_magic(magics, magic_kind, name, name)
154 record_magic(magics, magic_kind, name, name)
154 elif isinstance(arg, basestring):
155 elif isinstance(arg, basestring):
155 # Decorator called with arguments (@foo('bar'))
156 # Decorator called with arguments (@foo('bar'))
156 name = arg
157 name = arg
157 def mark(func, *a, **kw):
158 def mark(func, *a, **kw):
158 record_magic(magics, magic_kind, name, func.func_name)
159 record_magic(magics, magic_kind, name, func.func_name)
159 return decorator(call, func)
160 return decorator(call, func)
160 retval = mark
161 retval = mark
161 else:
162 else:
162 raise ValueError("Decorator can only be called with "
163 raise ValueError("Decorator can only be called with "
163 "string or function")
164 "string or function")
164 return retval
165 return retval
165
166
166 # Ensure the resulting decorator has a usable docstring
167 # Ensure the resulting decorator has a usable docstring
167 magic_deco.__doc__ = _docstring_template.format('method', magic_kind)
168 magic_deco.__doc__ = _docstring_template.format('method', magic_kind)
168 return magic_deco
169 return magic_deco
169
170
170
171
171 def _function_magic_marker(magic_kind):
172 def _function_magic_marker(magic_kind):
172 """Decorator factory for standalone functions.
173 """Decorator factory for standalone functions.
173 """
174 """
174
175
175 validate_type(magic_kind)
176 validate_type(magic_kind)
176
177
177 # This is a closure to capture the magic_kind. We could also use a class,
178 # This is a closure to capture the magic_kind. We could also use a class,
178 # but it's overkill for just that one bit of state.
179 # but it's overkill for just that one bit of state.
179 def magic_deco(arg):
180 def magic_deco(arg):
180 call = lambda f, *a, **k: f(*a, **k)
181 call = lambda f, *a, **k: f(*a, **k)
181
182
182 # Find get_ipython() in the caller's namespace
183 # Find get_ipython() in the caller's namespace
183 caller = sys._getframe(1)
184 caller = sys._getframe(1)
184 for ns in ['f_locals', 'f_globals', 'f_builtins']:
185 for ns in ['f_locals', 'f_globals', 'f_builtins']:
185 get_ipython = getattr(caller, ns).get('get_ipython')
186 get_ipython = getattr(caller, ns).get('get_ipython')
186 if get_ipython is not None:
187 if get_ipython is not None:
187 break
188 break
188 else:
189 else:
189 raise('Decorator can only run in context where `get_ipython` exists')
190 raise('Decorator can only run in context where `get_ipython` exists')
190
191
191 ip = get_ipython()
192 ip = get_ipython()
192
193
193 if callable(arg):
194 if callable(arg):
194 # "Naked" decorator call (just @foo, no args)
195 # "Naked" decorator call (just @foo, no args)
195 func = arg
196 func = arg
196 name = func.func_name
197 name = func.func_name
197 ip.register_magic_function(func, magic_kind, name)
198 ip.register_magic_function(func, magic_kind, name)
198 retval = decorator(call, func)
199 retval = decorator(call, func)
199 elif isinstance(arg, basestring):
200 elif isinstance(arg, basestring):
200 # Decorator called with arguments (@foo('bar'))
201 # Decorator called with arguments (@foo('bar'))
201 name = arg
202 name = arg
202 def mark(func, *a, **kw):
203 def mark(func, *a, **kw):
203 ip.register_magic_function(func, magic_kind, name)
204 ip.register_magic_function(func, magic_kind, name)
204 return decorator(call, func)
205 return decorator(call, func)
205 retval = mark
206 retval = mark
206 else:
207 else:
207 raise ValueError("Decorator can only be called with "
208 raise ValueError("Decorator can only be called with "
208 "string or function")
209 "string or function")
209 return retval
210 return retval
210
211
211 # Ensure the resulting decorator has a usable docstring
212 # Ensure the resulting decorator has a usable docstring
212 magic_deco.__doc__ = _docstring_template.format('function', magic_kind)
213 ds = _docstring_template.format('function', magic_kind)
214
215 ds += dedent("""
216 Note: this decorator can only be used in a context where IPython is already
217 active, so that the `get_ipython()` call succeeds. You can therefore use
218 it in your startup files loaded after IPython initializes, but *not* in the
219 IPython configuration file itself, which is executed before IPython is
220 fully up and running. Any file located in the `startup` subdirectory of
221 your configuration profile will be OK in this sense.
222 """)
223
224 magic_deco.__doc__ = ds
213 return magic_deco
225 return magic_deco
214
226
215
227
216 # Create the actual decorators for public use
228 # Create the actual decorators for public use
217
229
218 # These three are used to decorate methods in class definitions
230 # These three are used to decorate methods in class definitions
219 line_magic = _method_magic_marker('line')
231 line_magic = _method_magic_marker('line')
220 cell_magic = _method_magic_marker('cell')
232 cell_magic = _method_magic_marker('cell')
221 line_cell_magic = _method_magic_marker('line_cell')
233 line_cell_magic = _method_magic_marker('line_cell')
222
234
223 # These three decorate standalone functions and perform the decoration
235 # These three decorate standalone functions and perform the decoration
224 # immediately. They can only run where get_ipython() works
236 # immediately. They can only run where get_ipython() works
225 register_line_magic = _function_magic_marker('line')
237 register_line_magic = _function_magic_marker('line')
226 register_cell_magic = _function_magic_marker('cell')
238 register_cell_magic = _function_magic_marker('cell')
227 register_line_cell_magic = _function_magic_marker('line_cell')
239 register_line_cell_magic = _function_magic_marker('line_cell')
228
240
229 #-----------------------------------------------------------------------------
241 #-----------------------------------------------------------------------------
230 # Core Magic classes
242 # Core Magic classes
231 #-----------------------------------------------------------------------------
243 #-----------------------------------------------------------------------------
232
244
233 class MagicsManager(Configurable):
245 class MagicsManager(Configurable):
234 """Object that handles all magic-related functionality for IPython.
246 """Object that handles all magic-related functionality for IPython.
235 """
247 """
236 # Non-configurable class attributes
248 # Non-configurable class attributes
237
249
238 # A two-level dict, first keyed by magic type, then by magic function, and
250 # A two-level dict, first keyed by magic type, then by magic function, and
239 # holding the actual callable object as value. This is the dict used for
251 # holding the actual callable object as value. This is the dict used for
240 # magic function dispatch
252 # magic function dispatch
241 magics = Dict
253 magics = Dict
242
254
243 # A registry of the original objects that we've been given holding magics.
255 # A registry of the original objects that we've been given holding magics.
244 registry = Dict
256 registry = Dict
245
257
246 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
258 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
247
259
248 auto_magic = Bool
260 auto_magic = Bool
249
261
250 _auto_status = [
262 _auto_status = [
251 'Automagic is OFF, % prefix IS needed for magic functions.',
263 'Automagic is OFF, % prefix IS needed for magic functions.',
252 'Automagic is ON, % prefix IS NOT needed for magic functions.']
264 'Automagic is ON, % prefix IS NOT needed for magic functions.']
253
265
254 user_magics = Instance('IPython.core.magics.UserMagics')
266 user_magics = Instance('IPython.core.magics.UserMagics')
255
267
256 def __init__(self, shell=None, config=None, user_magics=None, **traits):
268 def __init__(self, shell=None, config=None, user_magics=None, **traits):
257
269
258 super(MagicsManager, self).__init__(shell=shell, config=config,
270 super(MagicsManager, self).__init__(shell=shell, config=config,
259 user_magics=user_magics, **traits)
271 user_magics=user_magics, **traits)
260 self.magics = dict(line={}, cell={})
272 self.magics = dict(line={}, cell={})
261 # Let's add the user_magics to the registry for uniformity, so *all*
273 # Let's add the user_magics to the registry for uniformity, so *all*
262 # registered magic containers can be found there.
274 # registered magic containers can be found there.
263 self.registry[user_magics.__class__.__name__] = user_magics
275 self.registry[user_magics.__class__.__name__] = user_magics
264
276
265 def auto_status(self):
277 def auto_status(self):
266 """Return descriptive string with automagic status."""
278 """Return descriptive string with automagic status."""
267 return self._auto_status[self.auto_magic]
279 return self._auto_status[self.auto_magic]
268
280
269 def lsmagic(self):
281 def lsmagic(self):
270 """Return a dict of currently available magic functions.
282 """Return a dict of currently available magic functions.
271
283
272 The return dict has the keys 'line' and 'cell', corresponding to the
284 The return dict has the keys 'line' and 'cell', corresponding to the
273 two types of magics we support. Each value is a list of names.
285 two types of magics we support. Each value is a list of names.
274 """
286 """
275 return self.magics
287 return self.magics
276
288
277 def register(self, *magic_objects):
289 def register(self, *magic_objects):
278 """Register one or more instances of Magics.
290 """Register one or more instances of Magics.
279 """
291 """
280 # Start by validating them to ensure they have all had their magic
292 # Start by validating them to ensure they have all had their magic
281 # methods registered at the instance level
293 # methods registered at the instance level
282 for m in magic_objects:
294 for m in magic_objects:
283 if not m.registered:
295 if not m.registered:
284 raise ValueError("Class of magics %r was constructed without "
296 raise ValueError("Class of magics %r was constructed without "
285 "the @register_macics class decorator")
297 "the @register_macics class decorator")
286 if type(m) is type:
298 if type(m) is type:
287 # If we're given an uninstantiated class
299 # If we're given an uninstantiated class
288 m = m(self.shell)
300 m = m(self.shell)
289
301
290 # Now that we have an instance, we can register it and update the
302 # Now that we have an instance, we can register it and update the
291 # table of callables
303 # table of callables
292 self.registry[m.__class__.__name__] = m
304 self.registry[m.__class__.__name__] = m
293 for mtype in magic_kinds:
305 for mtype in magic_kinds:
294 self.magics[mtype].update(m.magics[mtype])
306 self.magics[mtype].update(m.magics[mtype])
295
307
296 def register_function(self, func, magic_kind='line', magic_name=None):
308 def register_function(self, func, magic_kind='line', magic_name=None):
297 """Expose a standalone function as magic function for ipython.
309 """Expose a standalone function as magic function for ipython.
298 """
310 """
299
311
300 # Create the new method in the user_magics and register it in the
312 # Create the new method in the user_magics and register it in the
301 # global table
313 # global table
302 validate_type(magic_kind)
314 validate_type(magic_kind)
303 magic_name = func.func_name if magic_name is None else magic_name
315 magic_name = func.func_name if magic_name is None else magic_name
304 setattr(self.user_magics, magic_name, func)
316 setattr(self.user_magics, magic_name, func)
305 record_magic(self.magics, magic_kind, magic_name, func)
317 record_magic(self.magics, magic_kind, magic_name, func)
306
318
307 def define_magic(self, name, func):
319 def define_magic(self, name, func):
308 """Support for deprecated API.
320 """Support for deprecated API.
309
321
310 This method exists only to support the old-style definition of magics.
322 This method exists only to support the old-style definition of magics.
311 It will eventually be removed. Deliberately not documented further.
323 It will eventually be removed. Deliberately not documented further.
312 """
324 """
313 meth = types.MethodType(func, self.user_magics)
325 meth = types.MethodType(func, self.user_magics)
314 setattr(self.user_magics, name, meth)
326 setattr(self.user_magics, name, meth)
315 record_magic(self.magics, 'line', name, meth)
327 record_magic(self.magics, 'line', name, meth)
316
328
317 # Key base class that provides the central functionality for magics.
329 # Key base class that provides the central functionality for magics.
318
330
319 class Magics(object):
331 class Magics(object):
320 """Base class for implementing magic functions.
332 """Base class for implementing magic functions.
321
333
322 Shell functions which can be reached as %function_name. All magic
334 Shell functions which can be reached as %function_name. All magic
323 functions should accept a string, which they can parse for their own
335 functions should accept a string, which they can parse for their own
324 needs. This can make some functions easier to type, eg `%cd ../`
336 needs. This can make some functions easier to type, eg `%cd ../`
325 vs. `%cd("../")`
337 vs. `%cd("../")`
326
338
327 Classes providing magic functions need to subclass this class, and they
339 Classes providing magic functions need to subclass this class, and they
328 MUST:
340 MUST:
329
341
330 - Use the method decorators `@line_magic` and `@cell_magic` to decorate
342 - Use the method decorators `@line_magic` and `@cell_magic` to decorate
331 individual methods as magic functions, AND
343 individual methods as magic functions, AND
332
344
333 - Use the class decorator `@magics_class` to ensure that the magic
345 - Use the class decorator `@magics_class` to ensure that the magic
334 methods are properly registered at the instance level upon instance
346 methods are properly registered at the instance level upon instance
335 initialization.
347 initialization.
336
348
337 See :mod:`magic_functions` for examples of actual implementation classes.
349 See :mod:`magic_functions` for examples of actual implementation classes.
338 """
350 """
339 # Dict holding all command-line options for each magic.
351 # Dict holding all command-line options for each magic.
340 options_table = None
352 options_table = None
341 # Dict for the mapping of magic names to methods, set by class decorator
353 # Dict for the mapping of magic names to methods, set by class decorator
342 magics = None
354 magics = None
343 # Flag to check that the class decorator was properly applied
355 # Flag to check that the class decorator was properly applied
344 registered = False
356 registered = False
345 # Instance of IPython shell
357 # Instance of IPython shell
346 shell = None
358 shell = None
347
359
348 def __init__(self, shell):
360 def __init__(self, shell):
349 if not(self.__class__.registered):
361 if not(self.__class__.registered):
350 raise ValueError('Magics subclass without registration - '
362 raise ValueError('Magics subclass without registration - '
351 'did you forget to apply @magics_class?')
363 'did you forget to apply @magics_class?')
352 self.shell = shell
364 self.shell = shell
353 self.options_table = {}
365 self.options_table = {}
354 # The method decorators are run when the instance doesn't exist yet, so
366 # The method decorators are run when the instance doesn't exist yet, so
355 # they can only record the names of the methods they are supposed to
367 # they can only record the names of the methods they are supposed to
356 # grab. Only now, that the instance exists, can we create the proper
368 # grab. Only now, that the instance exists, can we create the proper
357 # mapping to bound methods. So we read the info off the original names
369 # mapping to bound methods. So we read the info off the original names
358 # table and replace each method name by the actual bound method.
370 # table and replace each method name by the actual bound method.
359 for mtype in magic_kinds:
371 for mtype in magic_kinds:
360 tab = self.magics[mtype]
372 tab = self.magics[mtype]
361 # must explicitly use keys, as we're mutating this puppy
373 # must explicitly use keys, as we're mutating this puppy
362 for magic_name in tab.keys():
374 for magic_name in tab.keys():
363 meth_name = tab[magic_name]
375 meth_name = tab[magic_name]
364 if isinstance(meth_name, basestring):
376 if isinstance(meth_name, basestring):
365 tab[magic_name] = getattr(self, meth_name)
377 tab[magic_name] = getattr(self, meth_name)
366
378
367 def arg_err(self,func):
379 def arg_err(self,func):
368 """Print docstring if incorrect arguments were passed"""
380 """Print docstring if incorrect arguments were passed"""
369 print 'Error in arguments:'
381 print 'Error in arguments:'
370 print oinspect.getdoc(func)
382 print oinspect.getdoc(func)
371
383
372 def format_latex(self, strng):
384 def format_latex(self, strng):
373 """Format a string for latex inclusion."""
385 """Format a string for latex inclusion."""
374
386
375 # Characters that need to be escaped for latex:
387 # Characters that need to be escaped for latex:
376 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
388 escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE)
377 # Magic command names as headers:
389 # Magic command names as headers:
378 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
390 cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC,
379 re.MULTILINE)
391 re.MULTILINE)
380 # Magic commands
392 # Magic commands
381 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
393 cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC,
382 re.MULTILINE)
394 re.MULTILINE)
383 # Paragraph continue
395 # Paragraph continue
384 par_re = re.compile(r'\\$',re.MULTILINE)
396 par_re = re.compile(r'\\$',re.MULTILINE)
385
397
386 # The "\n" symbol
398 # The "\n" symbol
387 newline_re = re.compile(r'\\n')
399 newline_re = re.compile(r'\\n')
388
400
389 # Now build the string for output:
401 # Now build the string for output:
390 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
402 #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng)
391 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
403 strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:',
392 strng)
404 strng)
393 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
405 strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng)
394 strng = par_re.sub(r'\\\\',strng)
406 strng = par_re.sub(r'\\\\',strng)
395 strng = escape_re.sub(r'\\\1',strng)
407 strng = escape_re.sub(r'\\\1',strng)
396 strng = newline_re.sub(r'\\textbackslash{}n',strng)
408 strng = newline_re.sub(r'\\textbackslash{}n',strng)
397 return strng
409 return strng
398
410
399 def parse_options(self, arg_str, opt_str, *long_opts, **kw):
411 def parse_options(self, arg_str, opt_str, *long_opts, **kw):
400 """Parse options passed to an argument string.
412 """Parse options passed to an argument string.
401
413
402 The interface is similar to that of getopt(), but it returns back a
414 The interface is similar to that of getopt(), but it returns back a
403 Struct with the options as keys and the stripped argument string still
415 Struct with the options as keys and the stripped argument string still
404 as a string.
416 as a string.
405
417
406 arg_str is quoted as a true sys.argv vector by using shlex.split.
418 arg_str is quoted as a true sys.argv vector by using shlex.split.
407 This allows us to easily expand variables, glob files, quote
419 This allows us to easily expand variables, glob files, quote
408 arguments, etc.
420 arguments, etc.
409
421
410 Options:
422 Options:
411 -mode: default 'string'. If given as 'list', the argument string is
423 -mode: default 'string'. If given as 'list', the argument string is
412 returned as a list (split on whitespace) instead of a string.
424 returned as a list (split on whitespace) instead of a string.
413
425
414 -list_all: put all option values in lists. Normally only options
426 -list_all: put all option values in lists. Normally only options
415 appearing more than once are put in a list.
427 appearing more than once are put in a list.
416
428
417 -posix (True): whether to split the input line in POSIX mode or not,
429 -posix (True): whether to split the input line in POSIX mode or not,
418 as per the conventions outlined in the shlex module from the
430 as per the conventions outlined in the shlex module from the
419 standard library."""
431 standard library."""
420
432
421 # inject default options at the beginning of the input line
433 # inject default options at the beginning of the input line
422 caller = sys._getframe(1).f_code.co_name
434 caller = sys._getframe(1).f_code.co_name
423 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
435 arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str)
424
436
425 mode = kw.get('mode','string')
437 mode = kw.get('mode','string')
426 if mode not in ['string','list']:
438 if mode not in ['string','list']:
427 raise ValueError,'incorrect mode given: %s' % mode
439 raise ValueError,'incorrect mode given: %s' % mode
428 # Get options
440 # Get options
429 list_all = kw.get('list_all',0)
441 list_all = kw.get('list_all',0)
430 posix = kw.get('posix', os.name == 'posix')
442 posix = kw.get('posix', os.name == 'posix')
431 strict = kw.get('strict', True)
443 strict = kw.get('strict', True)
432
444
433 # Check if we have more than one argument to warrant extra processing:
445 # Check if we have more than one argument to warrant extra processing:
434 odict = {} # Dictionary with options
446 odict = {} # Dictionary with options
435 args = arg_str.split()
447 args = arg_str.split()
436 if len(args) >= 1:
448 if len(args) >= 1:
437 # If the list of inputs only has 0 or 1 thing in it, there's no
449 # If the list of inputs only has 0 or 1 thing in it, there's no
438 # need to look for options
450 # need to look for options
439 argv = arg_split(arg_str, posix, strict)
451 argv = arg_split(arg_str, posix, strict)
440 # Do regular option processing
452 # Do regular option processing
441 try:
453 try:
442 opts,args = getopt(argv,opt_str,*long_opts)
454 opts,args = getopt(argv,opt_str,*long_opts)
443 except GetoptError,e:
455 except GetoptError,e:
444 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
456 raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str,
445 " ".join(long_opts)))
457 " ".join(long_opts)))
446 for o,a in opts:
458 for o,a in opts:
447 if o.startswith('--'):
459 if o.startswith('--'):
448 o = o[2:]
460 o = o[2:]
449 else:
461 else:
450 o = o[1:]
462 o = o[1:]
451 try:
463 try:
452 odict[o].append(a)
464 odict[o].append(a)
453 except AttributeError:
465 except AttributeError:
454 odict[o] = [odict[o],a]
466 odict[o] = [odict[o],a]
455 except KeyError:
467 except KeyError:
456 if list_all:
468 if list_all:
457 odict[o] = [a]
469 odict[o] = [a]
458 else:
470 else:
459 odict[o] = a
471 odict[o] = a
460
472
461 # Prepare opts,args for return
473 # Prepare opts,args for return
462 opts = Struct(odict)
474 opts = Struct(odict)
463 if mode == 'string':
475 if mode == 'string':
464 args = ' '.join(args)
476 args = ' '.join(args)
465
477
466 return opts,args
478 return opts,args
467
479
468 def default_option(self, fn, optstr):
480 def default_option(self, fn, optstr):
469 """Make an entry in the options_table for fn, with value optstr"""
481 """Make an entry in the options_table for fn, with value optstr"""
470
482
471 if fn not in self.lsmagic():
483 if fn not in self.lsmagic():
472 error("%s is not a magic function" % fn)
484 error("%s is not a magic function" % fn)
473 self.options_table[fn] = optstr
485 self.options_table[fn] = optstr
General Comments 0
You need to be logged in to leave comments. Login now