Exemple #1
0
def include_pymod(context, modulename, title=None):
    """
	|!Usage|{{{<<include_pymod modulename title>>}}}|
	|!Description|<<echo <quote>Include the source code for a Python module. 
	Module must be in {{{sys.path}}} or {{{'.'}}}.
	{{{title}}} is the title for the box. If not given it defaults to ''modulename''.</quote> >>|
	|!Example|{{{<<include_pymod statvfs "A Title">>}}}|
	|!Result|<<include_pymod statvfs "A Title">>|
	"""
    modulename = modulename.text

    try:
        mod = load_module(modulename)
        src = inspect.getsource(mod)
    except:
        return warnbox(
            context, Text(u'ERROR', 'TextMacroArg'),
            Text(u"Unable to import module '%s'" % modulename, 'TextMacroArg'))

    if title is None:
        title = modulename
    else:
        title = title.text

    txt = ''

    for line in src.splitlines():
        txt += line + '\n'

    del sys.modules[modulename]

    return codebox(context, Text(title, 'TextMacroArg'),
                   Text(txt, "TextMacroArg"))
Exemple #2
0
def wikiwordify(node, wcontext, wikiwords, on_unknown=on_unknown_camelword):
    """
	Given an ElementTree generated by wikklytext.buildXML, turn all
	wikiwords into links.
	
	node = ElementTree node (typically the rootnode from the parser).
	wcontext = WikContext
	wikiwords = Dict of wikiwords as:
		wikiwords[word] = URL
		
	on_unknown_camelword = callback when unknown camelwords are found.
		called as:
		   (text, needs_eval) = on_unknown(word)
		   
		Where: 
			text = replacement text.
			needs_eval = True/False if returned text is wikitext that needs
						 to be evaluated.

	Modifies the tree in place.
	"""
    from wikklytext.eval import eval_wiki_text
    from wikklytext.base import xmltrace, ElementList

    if node.tag == 'Text':
        raise Exception("<Text> cannot be at toplevel here.")

    # ignore <Text> nodes under these tags
    if node.tag in ('Link', 'Image', 'CreateAnchor'):
        return

    for i in range(len(node)):
        subnode = node[i]

        #print '<%s>' % subnode.tag
        # only <Text> nodes are eligible for wikiword substitution,
        # don't look in <TextCode>, <TextHTML>, etc.
        if subnode.tag == 'Text':
            #print "CONSIDER:",subnode.text
            wtext, needs_eval = wikiwordify_text(subnode.text or '', wikiwords,
                                                 on_unknown)
            if needs_eval:
                nodes = eval_wiki_text(wcontext, wtext)
            else:
                # saves a lot of time to only eval as needed
                nodes = [Text(wtext)]

            #print "GOT",xmltrace(nodes)
            # place all under a single ElementList
            elist = ElementList()
            for n in nodes:
                elist.append(n)

            #print "GOT",xmltrace(elist)

            # replace <Text> with <ElementList>
            node[i] = elist

        else:
            wikiwordify(subnode, wcontext, wikiwords, on_unknown)
Exemple #3
0
def codebox(context, title, codetext):
    """
	|!Usage|{{{<<codebox title arg [arg ...]>>}}}|
	|!Description|Like a regular code box, except with a title.|
	|!Example|{{{<<codebox "A Title" '''
for i in range(10):
	print i'''>>}}}|
	|!Result|<<codebox "A Title" '''
for i in range(10):
	print i'''>>|
	"""
    if codetext.tag != 'TextMacroArg':
        raise WikError("'codetext' must be a single text argument - got %s" %
                       codetext.tag)

    container = DIV('wikkly-codebox-container')
    titlediv = DIV('wikkly-codebox-title')
    for node in eval_wiki_macro_args(context, [title]):
        titlediv.append(node)

    container.append(titlediv)

    body = DIV('wikkly-codebox-body')

    # place in TextCode element so it will get the proper code-style escaping
    #textnode = etree.Element('TextCode')
    #textnode.text = codetext.text
    textnode = Text(codetext.text, 'TextCode')

    body.append(textnode)

    container.append(body)

    return [container]
Exemple #4
0
 def endDoc(self):
     # make sure there is at least one node under <Content>
     node = self.rootnode.find('Content')
     if len(node) == 0:
         # add an empty Text node, simplifies other code
         # to always have at least one node under <Content>
         node.append(Text(""))
Exemple #5
0
def closeAll(context):
    """
	|!Usage|{{{<<closeAll>>}}}|
	|!Description|//This only exists for compatibility with ~TiddlyWiki texts.<br><br>It does not do anything.//|
	|!Example|{{{<<closeAll>>}}}|
	|!Result|<<closeAll>>|
	"""
    return Text('')
Exemple #6
0
def include_code(context, filename, title=None):
    """
	|!Usage|{{{<<include_pyfunc filename title>>}}}|
	|!Description|<<echo <quote>Include a file as a block of code (as if it
	were included inside {{{{{{ .. }}&#x200b;}&#x200b;}}}). Searches in {{{sys.path}}} and {{{'.'}}} if
	absolute path not given. {{{title}}} is the title for the box. If not given it defaults to ''filename''.</quote> >>|
	|!Example|{{{<<include_code doc/sample.py>>}}}|
	|!Result|<<include_code doc/sample.py>>|
	"""
    from pkg_resources import resource_string, resource_exists

    name = filename.text
    fullname = filepath(context, name)

    # search in sys.path also
    if not os.path.isfile(fullname):
        for path in sys.path:
            if os.path.isfile(os.path.join(path, name)):
                fullname = os.path.join(path, name)
                break

    # if still not found, try resources
    if not os.path.isfile(fullname):
        if resource_exists('wikklytext', filename.text):
            buf = resource_string('wikklytext', filename.text)
            if title is None:
                title = os.path.basename(filename.text)
            else:
                title = title.text
        else:
            return eval_wiki_text(
                context,
                u'{{highlight{ERROR - No such file or resource "%s"}}}' %
                filename.text)
    else:
        buf = open(fullname, 'r').read()

        if title is None:
            title = os.path.basename(fullname)
        else:
            title = title.text

    return codebox(context, Text(title, 'TextMacroArg'),
                   Text(buf, 'TextMacroArg'))
Exemple #7
0
def version(context):
    """
	|!Usage|{{{<<version>>}}}|
	|!Description|Get the ~WikklyText version number.|
	|!Example|{{{<<version>>}}}|
	|!Result|<<version>>|
	"""
    from wikklytext.base import get_version

    return Text(get_version())
Exemple #8
0
def debug(context, *elements):
    """
	|!Usage|{{{<<debug arg arg ...>>}}}|
	|!Description|Prints arguments to stdout - does //not// become part of document.|
	|!Example|//No example, to prevent console noise.//|
	|!Result||
	"""
    print "** DEBUGGING TRACE **"
    elements = eval_wiki_macro_args(context, elements)
    print xmltrace(elements)
    print "**********END DEBUG***********"

    return Text('')
Exemple #9
0
def include_pyfunc(context, modulename, funcname, title=None):
    """
	|!Usage|{{{<<include_pyfunc modulename funcname title>>}}}|
	|!Description|<<echo <quote>Include the source code for a single Python function from 
	the named module. Module must be in {{{sys.path}}} or {{{'.'}}}.
	{{{title}}} is the title for the box. If not given it defaults to ''modulename.funcname()''.</quote> >>|
	|!Example|{{{<<include_pyfunc atexit register>>}}}|
	|!Result|<<include_pyfunc atexit register>>|
	"""
    # these must both be Text* nodes
    modulename = modulename.text
    funcname = funcname.text

    if title is None:
        title = '%s.%s()' % (modulename, funcname)
    else:
        title = title.text

    try:
        mod = load_module(modulename)
        func = getattr(mod, funcname)
        src = inspect.getsource(func)
    except:
        return warnbox(
            context, Text(u'ERROR', 'TextMacroArg'),
            Text(u'Unable to get source for "%s.%s"' % (modulename, funcname),
                 'TextMacroArg'))

    code = ''

    for line in src.splitlines():
        code += line + '\n'

    del sys.modules[modulename]

    # pass it off to codebox() to do formatting (remember it expects <TextMacroArg> args)
    return codebox(context, Text(title, 'TextMacroArg'),
                   Text(code, 'TextMacroArg'))
Exemple #10
0
def echos(context, *elements):
    """
	|!Usage|{{{<<echos arg arg ...>>}}}|
	|!Description|Like {{{echo}}} but adds a space between arguments.|
	|!Example|{{{<<echos "AAA" BBB '''CCC'''>>}}}|
	|!Result|<<echos "AAA" BBB '''CCC'''>>|
	"""
    elements = eval_wiki_macro_args(context, elements)
    out = ElementList()
    for e in elements:
        out.append(e)
        out.append(Text(' '))

    return out