1 # -*- coding: iso-8859-1 -*- 2 """ 3 MoinMoin - MoinShare fragment parser 4 5 @copyright: 2011, 2012 by Paul Boddie <paul@boddie.org.uk> 6 @license: GNU GPL (v2 or later), see COPYING.txt for details. 7 """ 8 9 from MoinMoin import wikiutil 10 11 try: 12 from hashlib import sha1 13 except ImportError: 14 from sha import new as sha1 15 16 Dependencies = ["pages"] 17 18 # Parser support. 19 20 class Parser: 21 22 """ 23 Format shared content fragments of the form... 24 25 {{{#!MoinShare fragment=fragment-id ref=ref-fragment-id format=content-format 26 27 Content... 28 }}} 29 """ 30 31 def __init__(self, raw, request, **kw): 32 33 """ 34 Initialise the parser with the given 'raw' data, 'request' and any 35 keyword arguments that may have been supplied. 36 """ 37 38 self.raw = raw 39 self.request = request 40 41 attrs, msg = wikiutil.parseAttributes(request, kw.get("format_args", "")) 42 43 # The attributes returned from the formatting arguments are encoded like 44 # strings. 45 46 quotes = '"' + "'" 47 48 # Get any reference to this fragment, another fragment and the content 49 # format. 50 51 self.fragment = (attrs.get("fragment") or '').strip(quotes) 52 self.ref = (attrs.get("ref") or '').strip(quotes) 53 self.format_type = (attrs.get("format") or '').strip(quotes) 54 55 def getDigest(self): 56 57 "Make a message digest for the fragment's content." 58 59 return sha1(self.raw).hexdigest() 60 61 def format(self, fmt): 62 63 "Format a fragment using the given formatter 'fmt'." 64 65 request = self.request 66 67 if self.fragment: 68 request.write(fmt.anchordef(self.fragment)) 69 70 request.write(fmt.div(1, css_class="moinsharefragment")) 71 request.write(self.formatText(self.raw, fmt)) 72 request.write(fmt.div(0)) 73 74 def getFormat(self): 75 76 "Get the format used on this page." 77 78 return self.format_type 79 80 def getParserClass(self, format): 81 82 """ 83 Return a parser class for the given 'format', returning a plain text 84 parser if no parser can be found for the specified 'format'. 85 """ 86 87 cfg = self.request.cfg 88 89 try: 90 return wikiutil.searchAndImportPlugin(cfg, "parser", format or "wiki") 91 except wikiutil.PluginMissingError: 92 return wikiutil.searchAndImportPlugin(cfg, "parser", "plain") 93 94 def formatText(self, text, fmt): 95 96 """ 97 Format the given 'text' using the specified formatter 'fmt'. 98 """ 99 100 request = self.request 101 page = fmt.page = request.page 102 format = self.getFormat() 103 104 # Suppress line anchors. 105 106 parser_cls = self.getParserClass(format) 107 parser = parser_cls(text, request, line_anchors=False) 108 109 # Fix lists by indicating that a paragraph is already started. 110 111 kw = {} 112 if not format or format == "wiki": 113 kw["inhibit_p"] = True 114 115 return request.redirectedOutput(parser.format, fmt, **kw) 116 117 # vim: tabstop=4 expandtab shiftwidth=4