Back to index

moin  1.9.0~rc2
Public Member Functions | Public Attributes | Static Public Attributes | Private Member Functions | Private Attributes
MoinMoin.macro.Macro Class Reference

Macros - Handlers for <<macroname>> markup. More...

List of all members.

Public Member Functions

def __init__
def execute
def get_dependencies
def macro_TitleSearch
def macro_TemplateList
def macro_TitleIndex
def macro_WordIndex
def macro_GoTo
def macro_Icon
def macro_Date
def macro_DateTime
def macro_Anchor
def macro_MailTo
def macro_GetVal

Public Attributes

 parser
 request
 formatter
 cfg
 name

Static Public Attributes

list defaultDependency = ["time"]
dictionary Dependencies

Private Member Functions

def _m_lang
def _make_index
def __get_Date

Private Attributes

 _

Detailed Description

Macros - Handlers for <<macroname>> markup.

Macro handler

There are three kinds of macros:
 * Builtin Macros - implemented in this file and named macro_[name]
 * Language Pseudo Macros - any lang the wiki knows can be use as
   macro and is implemented here by _m_lang()
 * External macros - implemented in either MoinMoin.macro package, or
   in the specific wiki instance in the plugin/macro directory

Definition at line 52 of file __init__.py.


Constructor & Destructor Documentation

def MoinMoin.macro.Macro.__init__ (   self,
  parser 
)

Definition at line 84 of file __init__.py.

00084 
00085     def __init__(self, parser):
00086         self.parser = parser
00087         #self.form --> gone, please use self.request.{form,args,values}
00088         self.request = self.parser.request
00089         self.formatter = self.request.formatter
00090         self._ = self.request.getText
00091         self.cfg = self.request.cfg
00092 
00093         # Initialized on execute
00094         self.name = None


Member Function Documentation

def MoinMoin.macro.Macro.__get_Date (   self,
  args,
  format_date 
) [private]

Definition at line 309 of file __init__.py.

00309 
00310     def __get_Date(self, args, format_date):
00311         _ = self._
00312         if args is None:
00313             tm = time.time() # always UTC
00314         elif len(args) >= 19 and args[4] == '-' and args[7] == '-' \
00315                 and args[10] == 'T' and args[13] == ':' and args[16] == ':':
00316             # we ignore any time zone offsets here, assume UTC,
00317             # and accept (and ignore) any trailing stuff
00318             try:
00319                 year, month, day = int(args[0:4]), int(args[5:7]), int(args[8:10])
00320                 hour, minute, second = int(args[11:13]), int(args[14:16]), int(args[17:19])
00321                 tz = args[19:] # +HHMM, -HHMM or Z or nothing (then we assume Z)
00322                 tzoffset = 0 # we assume UTC no matter if there is a Z
00323                 if tz:
00324                     sign = tz[0]
00325                     if sign in '+-':
00326                         tzh, tzm = int(tz[1:3]), int(tz[3:])
00327                         tzoffset = (tzh*60+tzm)*60
00328                         if sign == '-':
00329                             tzoffset = -tzoffset
00330                 tm = (year, month, day, hour, minute, second, 0, 0, 0)
00331             except ValueError, err:
00332                 raise ValueError("Bad timestamp %r: %s" % (args, err))
00333             # as mktime wants a localtime argument (but we only have UTC),
00334             # we adjust by our local timezone's offset
00335             try:
00336                 tm = time.mktime(tm) - time.timezone - tzoffset
00337             except (OverflowError, ValueError):
00338                 tm = 0 # incorrect, but we avoid an ugly backtrace
00339         else:
00340             # try raw seconds since epoch in UTC
00341             try:
00342                 tm = float(args)
00343             except ValueError, err:
00344                 raise ValueError("Bad timestamp %r: %s" % (args, err))
00345         return format_date(tm)

Here is the caller graph for this function:

def MoinMoin.macro.Macro._m_lang (   self,
  text 
) [private]
Set the current language for page content.

    Language macro are used in two ways:
     * [lang] - set the current language until next lang macro
     * [lang(text)] - insert text with specific lang inside page

Definition at line 138 of file __init__.py.

00138 
00139     def _m_lang(self, text):
00140         """ Set the current language for page content.
00141 
00142             Language macro are used in two ways:
00143              * [lang] - set the current language until next lang macro
00144              * [lang(text)] - insert text with specific lang inside page
00145         """
00146         if text:
00147             return (self.formatter.lang(1, self.name) +
00148                     self.formatter.text(text) +
00149                     self.formatter.lang(0, self.name))
00150 
00151         self.request.current_lang = self.name
00152         return ''

def MoinMoin.macro.Macro._make_index (   self,
  word_re = u'.+' 
) [private]
make an index page (used for TitleIndex and WordIndex macro)

    word_re is a regex used for splitting a pagename into fragments
    matched by it (used for WordIndex). For TitleIndex, we just match
    the whole page name, so we only get one fragment that is the same
    as the pagename.

    TODO: _make_index could get a macro on its own, more powerful / less special than WordIndex and TitleIndex.
  It should be able to filter for specific mimetypes, maybe match pagenames by regex (replace PageList?), etc.

Definition at line 189 of file __init__.py.

00189 
00190     def _make_index(self, word_re=u'.+'):
00191         """ make an index page (used for TitleIndex and WordIndex macro)
00192 
00193             word_re is a regex used for splitting a pagename into fragments
00194             matched by it (used for WordIndex). For TitleIndex, we just match
00195             the whole page name, so we only get one fragment that is the same
00196             as the pagename.
00197 
00198             TODO: _make_index could get a macro on its own, more powerful / less special than WordIndex and TitleIndex.
00199                   It should be able to filter for specific mimetypes, maybe match pagenames by regex (replace PageList?), etc.
00200         """
00201         _ = self._
00202         request = self.request
00203         fmt = self.formatter
00204         allpages = int(request.values.get('allpages', 0)) != 0
00205         # Get page list readable by current user, filter by isSystemPage if needed
00206         if allpages:
00207             pages = request.rootpage.getPageList()
00208         else:
00209             def nosyspage(name):
00210                 return not wikiutil.isSystemPage(request, name)
00211             pages = request.rootpage.getPageList(filter=nosyspage)
00212 
00213         word_re = re.compile(word_re, re.UNICODE)
00214         wordmap = {}
00215         for name in pages:
00216             for word in word_re.findall(name):
00217                 try:
00218                     if not wordmap[word].count(name):
00219                         wordmap[word].append(name)
00220                 except KeyError:
00221                     wordmap[word] = [name]
00222 
00223         # Sort ignoring case
00224         tmp = [(word.upper(), word) for word in wordmap]
00225         tmp.sort()
00226         all_words = [item[1] for item in tmp]
00227 
00228         index_letters = []
00229         current_letter = None
00230         output = []
00231         for word in all_words:
00232             letter = wikiutil.getUnicodeIndexGroup(word)
00233             if letter != current_letter:
00234                 anchor = "idx-%s" % letter
00235                 output.append(fmt.anchordef(anchor))
00236                 output.append(fmt.heading(1, 2))
00237                 output.append(fmt.text(letter.replace('~', 'Others')))
00238                 output.append(fmt.heading(0, 2))
00239                 current_letter = letter
00240             if letter not in index_letters:
00241                 index_letters.append(letter)
00242             links = wordmap[word]
00243             if len(links) and links[0] != word: # show word fragment as on WordIndex
00244                 output.append(fmt.strong(1))
00245                 output.append(word)
00246                 output.append(fmt.strong(0))
00247 
00248             output.append(fmt.bullet_list(1))
00249             links.sort()
00250             last_page = None
00251             for name in links:
00252                 if name == last_page:
00253                     continue
00254                 output.append(fmt.listitem(1))
00255                 output.append(Page(request, name).link_to(request, attachment_indicator=1))
00256                 output.append(fmt.listitem(0))
00257             output.append(fmt.bullet_list(0))
00258 
00259         def _make_index_key(index_letters):
00260             index_letters.sort()
00261             def letter_link(ch):
00262                 anchor = "idx-%s" % ch
00263                 return fmt.anchorlink(1, anchor) + fmt.text(ch.replace('~', 'Others')) + fmt.anchorlink(0)
00264             links = [letter_link(letter) for letter in index_letters]
00265             return ' | '.join(links)
00266 
00267         page = fmt.page
00268         allpages_txt = (_('Include system pages'), _('Exclude system pages'))[allpages]
00269         allpages_url = page.url(request, querystr={'allpages': allpages and '0' or '1'})
00270 
00271         output = [fmt.paragraph(1), _make_index_key(index_letters), fmt.linebreak(0),
00272                   fmt.url(1, allpages_url), fmt.text(allpages_txt), fmt.url(0), fmt.paragraph(0)] + output
00273         return u''.join(output)
00274 

Here is the caller graph for this function:

def MoinMoin.macro.Macro.execute (   self,
  macro_name,
  args 
)
Get and execute a macro

Try to get a plugin macro, or a builtin macro or a language
macro, or just raise ImportError.

Definition at line 95 of file __init__.py.

00095 
00096     def execute(self, macro_name, args):
00097         """ Get and execute a macro
00098 
00099         Try to get a plugin macro, or a builtin macro or a language
00100         macro, or just raise ImportError.
00101         """
00102         self.name = macro_name
00103         try:
00104             call = wikiutil.importPlugin(self.cfg, 'macro', macro_name,
00105                                          function='macro_%s' % macro_name)
00106             execute = lambda _self, _args: wikiutil.invoke_extension_function(
00107                                                _self.request, call, _args, [_self])
00108         except wikiutil.PluginAttributeError:
00109             # fall back to old execute() method, no longer recommended
00110             execute = wikiutil.importPlugin(self.cfg, 'macro', macro_name)
00111         except wikiutil.PluginMissingError:
00112             try:
00113                 call = getattr(self, 'macro_%s' % macro_name)
00114                 execute = lambda _self, _args: wikiutil.invoke_extension_function(
00115                                                    _self.request, call, _args, [])
00116             except AttributeError:
00117                 if macro_name in i18n.wikiLanguages():
00118                     execute = self.__class__._m_lang
00119                 else:
00120                     raise ImportError("Cannot load macro %s" % macro_name)
00121         try:
00122             return execute(self, args)
00123         except Exception, err:
00124             # we do not want that a faulty macro aborts rendering of the page
00125             # and makes the wiki UI unusable (by emitting a Server Error),
00126             # thus, in case of exceptions, we just log the problem and return
00127             # some standard text.
00128             try:
00129                 page_spec = " (page: '%s')" % self.formatter.page.page_name
00130             except:
00131                 page_spec = ""
00132             logging.exception("Macro %s%s raised an exception:" % (self.name, page_spec))
00133             _ = self.request.getText
00134             return self.formatter.text(_('<<%(macro_name)s: execution failed [%(error_msg)s] (see also the log)>>') % {
00135                    'macro_name': self.name,
00136                    'error_msg': err.args[0], # note: str(err) or unicode(err) does not work for py2.4/5/6
00137                  })

Here is the caller graph for this function:

def MoinMoin.macro.Macro.get_dependencies (   self,
  macro_name 
)

Definition at line 153 of file __init__.py.

00153 
00154     def get_dependencies(self, macro_name):
00155         if macro_name in self.Dependencies:
00156             return self.Dependencies[macro_name]
00157         try:
00158             return wikiutil.importPlugin(self.request.cfg, 'macro',
00159                                          macro_name, 'Dependencies')
00160         except wikiutil.PluginError:
00161             return self.defaultDependency

def MoinMoin.macro.Macro.macro_Anchor (   self,
  anchor = None 
)

Definition at line 352 of file __init__.py.

00352 
00353     def macro_Anchor(self, anchor=None):
00354         anchor = wikiutil.get_unicode(self.request, anchor, 'anchor', u'anchor')
00355         return self.formatter.anchordef(anchor)

def MoinMoin.macro.Macro.macro_Date (   self,
  stamp = None 
)

Definition at line 346 of file __init__.py.

00346 
00347     def macro_Date(self, stamp=None):
00348         return self.__get_Date(stamp, self.request.user.getFormattedDate)

Here is the call graph for this function:

def MoinMoin.macro.Macro.macro_DateTime (   self,
  stamp = None 
)

Definition at line 349 of file __init__.py.

00349 
00350     def macro_DateTime(self, stamp=None):
00351         return self.__get_Date(stamp, self.request.user.getFormattedDateTime)

Here is the call graph for this function:

def MoinMoin.macro.Macro.macro_GetVal (   self,
  page = None,
  key = None 
)

Definition at line 383 of file __init__.py.

00383 
00384     def macro_GetVal(self, page=None, key=None):
00385         page = wikiutil.get_unicode(self.request, page, 'page')
00386 
00387         key = wikiutil.get_unicode(self.request, key, 'key')
00388         if page is None or key is None:
00389             raise ValueError("You need to give: pagename, key")
00390 
00391         d = self.request.dicts.get(page, {})
00392 
00393         # Check acl only if dictionary is defined on a wiki page.
00394         if isinstance(d, WikiDict) and not self.request.user.may.read(page):
00395             raise ValueError("You don't have enough rights on this page")
00396 
00397         result = d.get(key, '')
00398 
00399         return self.formatter.text(result)
00400 
Make a goto box

@rtype: unicode
@return: goto box html fragment

Definition at line 284 of file __init__.py.

00284 
00285     def macro_GoTo(self):
00286         """ Make a goto box
00287 
00288         @rtype: unicode
00289         @return: goto box html fragment
00290         """
00291         _ = self._
00292         html = [
00293             u'<form method="get" action="%s"><div>' % self.request.href(self.formatter.page.page_name),
00294             u'<div>',
00295             u'<input type="hidden" name="action" value="goto">',
00296             u'<input type="text" name="target" size="30">',
00297             u'<input type="submit" value="%s">' % _("Go To Page"),
00298             u'</div>',
00299             u'</form>',
00300             ]
00301         html = u'\n'.join(html)
00302         return self.formatter.rawHTML(html)

def MoinMoin.macro.Macro.macro_Icon (   self,
  icon = u'' 
)

Definition at line 303 of file __init__.py.

00303 
00304     def macro_Icon(self, icon=u''):
00305         # empty icon name isn't valid either
00306         if not icon:
00307             raise ValueError("You need to give a non-empty icon name")
00308         return self.formatter.icon(icon.lower())

def MoinMoin.macro.Macro.macro_MailTo (   self,
  email = unicode,
  text = u'' 
)

Definition at line 356 of file __init__.py.

00356 
00357     def macro_MailTo(self, email=unicode, text=u''):
00358         if not email:
00359             raise ValueError("You need to give an (obfuscated) email address")
00360 
00361         from MoinMoin.mail.sendmail import decodeSpamSafeEmail
00362 
00363         if self.request.user.valid:
00364             # decode address and generate mailto: link
00365             email = decodeSpamSafeEmail(email)
00366             result = (self.formatter.url(1, 'mailto:' + email, css='mailto') +
00367                       self.formatter.text(text or email) +
00368                       self.formatter.url(0))
00369         else:
00370             # unknown user, maybe even a spambot, so
00371             # just return text as given in macro args
00372 
00373             if text:
00374                 result = self.formatter.text(text + " ")
00375             else:
00376                 result = ''
00377 
00378             result += (self.formatter.code(1) +
00379                        self.formatter.text("<%s>" % email) +
00380                        self.formatter.code(0))
00381 
00382         return result

Here is the call graph for this function:

def MoinMoin.macro.Macro.macro_TemplateList (   self,
  needle = u'.+' 
)

Definition at line 166 of file __init__.py.

00166 
00167     def macro_TemplateList(self, needle=u'.+'):
00168         # TODO: this should be renamed (RegExPageNameList?), it does not list only Templates...
00169         _ = self._
00170         try:
00171             needle_re = re.compile(needle, re.IGNORECASE)
00172         except re.error, err:
00173             raise ValueError("Error in regex %r: %s" % (needle, err))
00174 
00175         # Get page list readable by current user, filtered by needle
00176         hits = self.request.rootpage.getPageList(filter=needle_re.search)
00177         hits.sort()
00178 
00179         result = []
00180         result.append(self.formatter.bullet_list(1))
00181         for pagename in hits:
00182             result.append(self.formatter.listitem(1))
00183             result.append(self.formatter.pagelink(1, pagename, generated=1))
00184             result.append(self.formatter.text(pagename))
00185             result.append(self.formatter.pagelink(0, pagename))
00186             result.append(self.formatter.listitem(0))
00187         result.append(self.formatter.bullet_list(0))
00188         return ''.join(result)

Definition at line 275 of file __init__.py.

00275 
00276     def macro_TitleIndex(self):
00277         return self._make_index()

Here is the call graph for this function:

Definition at line 162 of file __init__.py.

00162 
00163     def macro_TitleSearch(self):
00164         from MoinMoin.macro.FullSearch import search_box
00165         return search_box("titlesearch", self)

Here is the call graph for this function:

Definition at line 278 of file __init__.py.

00278 
00279     def macro_WordIndex(self):
00280         if self.request.isSpiderAgent: # reduce bot cpu usage
00281             return ''
00282         word_re = u'[%s][%s]+' % (config.chars_upper, config.chars_lower)
00283         return self._make_index(word_re=word_re)

Here is the call graph for this function:


Member Data Documentation

Definition at line 89 of file __init__.py.

Definition at line 90 of file __init__.py.

list MoinMoin.macro.Macro.defaultDependency = ["time"] [static]

Definition at line 62 of file __init__.py.

dictionary MoinMoin.macro.Macro.Dependencies [static]
Initial value:
{
        "TitleSearch": ["namespace"],
        "TemplateList": ["namespace"],
        "WordIndex": ["namespace"],
        "TitleIndex": ["namespace"],
        "Goto": [],
        "Icon": ["user"], # users have different themes and user prefs
        "Date": ["time"],
        "DateTime": ["time"],
        "Anchor": [],
        "Mailto": ["user"],
        "GetVal": ["pages"],
        }

Definition at line 64 of file __init__.py.

Definition at line 88 of file __init__.py.

Definition at line 93 of file __init__.py.

Definition at line 85 of file __init__.py.

Definition at line 87 of file __init__.py.


The documentation for this class was generated from the following file: