def test_extended_pre_block_with_many_newlines(): """Extra newlines in an extended pre block should not get cut down to only two.""" text = '''pre.. word another word yet anothe word''' expect = '''<pre>word another word yet anothe word</pre>''' result = textile.textile(text) assert result == expect text = 'p. text text\n\n\nh1. Hello\n' expect = '\t<p>text text</p>\n\n\n\t<h1>Hello</h1>' result = textile.textile(text) assert result == expect
def save(self): if self.title: self.title_html = OAAMarkupToHTML(self.title) self.title_text = OAAMarkupToText(self.title) if self.description: self.description_html = textile.textile(self.description) if self.keyboard: self.keyboard_html = textile.textile(self.keyboard) if self.style: self.style_code = OAAMarkupRemoveHighlightCode(self.style) self.style_source = HTMLToSourceCodeFormat(self.style) if self.html: self.html_code = OAAMarkupRemoveHighlightCode(self.html) self.html_source = HTMLToSourceCodeFormat(self.html) if self.script: self.script_code = OAAMarkupRemoveHighlightCode(self.script) self.script_source = HTMLToSourceCodeFormat(self.script) self.updated_date = datetime.datetime.now() #self.rule_categories.clear() #self.success_criteria.clear() # for rr in self.rule_references.all(): # self.rule_categories.add(rr.rule.rule_category) # self.success_criteria.add(rr.rule.wcag_primary) super(Example, self).save() # Call the "real" save() method.
def test_issue_35(): result = textile.textile('"z"') expect = '\t<p>“z” </p>' assert result == expect result = textile.textile('" z"') expect = '\t<p>“ z” </p>' assert result == expect
def index(self): try: article = get_article("index") data = {"content": textile(article["content"]), "title": article["title"]} except ErrorNoSuchRecord as not_found_err: data = {"content": textile(open("readme.textile").read())} self.response = Template.render(filename="index.html", **data)
def TestIssue035(self): result = textile.textile('"z"') expect = '\t<p>“z” </p>' eq_(result, expect) result = textile.textile('" z"') expect = '\t<p>“ z” </p>' eq_(result, expect)
def save(self): self.title_html = OAAMarkupToHTML(self.title) self.title_text = OAAMarkupToText(self.title) if self.web_resources: self.web_resources_html = textile.textile(self.web_resources) if self.description: self.description_html = textile.textile(self.description) super(RulesetNLS, self).save() # Call the "real" save() method.
def test_github_issue_30(): text ='"Tëxtíle (Tëxtíle)":http://lala.com' result = textile.textile(text) expect = '\t<p><a href="http://lala.com" title="Tëxtíle">Tëxtíle</a></p>' assert result == expect text ='!http://lala.com/lol.gif(♡ imáges)!' result = textile.textile(text) expect = '\t<p><img alt="♡ imáges" src="http://lala.com/lol.gif" title="♡ imáges" /></p>' assert result == expect
def testRelativeURLs(self): test = '!test/sample.jpg!' result = '\t<p><img src="http://example.com/imgs/test/sample.jpg" alt="" /></p>' expect = textile.textile(test, base_image_url='http://example.com/imgs/') eq_(result, expect) test = 'I searched "here":./?q=hello%20world.' result = '\t<p>I searched <a href="http://google.com/?q=hello%20world">here</a>.</p>' expect = textile.textile(test, base_url='http://google.com/') eq_(result, expect)
def TestIssue036(self): test = '"signup":signup\n[signup]http://myservice.com/signup' result = textile.textile(test) expect = '\t<p><a href="http://myservice.com/signup">signup</a></p>' eq_(result, expect) test = '"signup":signup\n[signup]https://myservice.com/signup' result = textile.textile(test) expect = '\t<p><a href="https://myservice.com/signup">signup</a></p>' eq_(result, expect)
def render(content, format=None, linenos=False): if re.match(linenos, "true", re.I) is not None: linenos = True else: linenos = False if format is "textile": html_content = textile(content, linenos) else: html_content = textile(content, linenos) return html_content
def testNestedFormatting(self): test = "*_test text_*" result = textile.textile(test) expect = "\t<p><strong><em>test text</em></strong></p>" eq_(result, expect) test = "_*test text*_" result = textile.textile(test) expect = "\t<p><em><strong>test text</strong></em></p>" eq_(result, expect)
def test_github_issue_55(): """Incorrect handling of quote entities in extended pre block""" test = ('pre.. this is the first line\n\nbut "quotes" in an extended pre ' 'block need to be handled properly.') result = textile.textile(test) expect = ('<pre>this is the first line\n\nbut "quotes" in an ' 'extended pre block need to be handled properly.</pre>') assert result == expect # supplied input test = ('pre.. import org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;' '\nimport ru.onyma.job.Context;\nimport ru.onyma.job.' 'RescheduleTask;\n\nimport java.util.concurrent.' 'ScheduledExecutorService;\nimport java.util.concurrent.TimeUnit;' '\n\n/**\n* @author ustits\n*/\npublic abstract class ' 'MainService<T> extends RescheduleTask implements Context<T> {\n\n' 'private static final Logger log = LoggerFactory.getLogger(' 'MainService.class);\nprivate final ScheduledExecutorService ' 'scheduler;\n\nprivate boolean isFirstRun = true;\nprivate T ' 'configs;\n\npublic MainService(final ScheduledExecutorService ' 'scheduler) {\nsuper(scheduler);\nthis.scheduler = scheduler;\n}\n' '\n@Override\npublic void setConfig(final T configs) {\nthis.' 'configs = configs;\nif (isFirstRun) {\nscheduler.schedule(this, ' '0, TimeUnit.SECONDS);\nisFirstRun = false;\n}\n}\n\n@Override\n' 'public void stop() {\nsuper.stop();\nscheduler.shutdown();\ntry {' '\nscheduler.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);\n} ' 'catch (InterruptedException ie) {\nlog.warn("Unable to wait for ' 'syncs termination", ie);\nThread.currentThread().interrupt();\n}' '\n}\n\nprotected final T getConfigs() {\nreturn configs;\n}\n}') result = textile.textile(test) expect = ('<pre>import org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;' '\nimport ru.onyma.job.Context;\nimport ru.onyma.job.' 'RescheduleTask;\n\nimport java.util.concurrent.' 'ScheduledExecutorService;\nimport java.util.concurrent.' 'TimeUnit;\n\n/**\n* @author ustits\n*/\npublic abstract class ' 'MainService<T> extends RescheduleTask implements ' 'Context<T> {\n\nprivate static final Logger log = ' 'LoggerFactory.getLogger(MainService.class);\nprivate final ' 'ScheduledExecutorService scheduler;\n\nprivate boolean ' 'isFirstRun = true;\nprivate T configs;\n\npublic MainService(' 'final ScheduledExecutorService scheduler) {\nsuper(scheduler);' '\nthis.scheduler = scheduler;\n}\n\n@Override\npublic void ' 'setConfig(final T configs) {\nthis.configs = configs;\nif (' 'isFirstRun) {\nscheduler.schedule(this, 0, TimeUnit.SECONDS);' '\nisFirstRun = false;\n}\n}\n\n@Override\npublic void stop() {' '\nsuper.stop();\nscheduler.shutdown();\ntry {\nscheduler.' 'awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);\n} catch ' '(InterruptedException ie) {\nlog.warn("Unable to wait ' 'for syncs termination", ie);\nThread.currentThread().' 'interrupt();\n}\n}\n\nprotected final T getConfigs() {\n' 'return configs;\n}\n}</pre>') assert result == expect
def test_Footnote(): html = textile.textile('This is covered elsewhere[1].\n\nfn1. Down here, in fact.\n\nfn2. Here is another footnote.') assert re.search(r'^\t<p>This is covered elsewhere<sup class="footnote" id="fnrev([a-f0-9]{32})-1"><a href="#fn\1-1">1</a></sup>.</p>\n\n\t<p class="footnote" id="fn\1-1"><sup>1</sup> Down here, in fact.</p>\n\n\t<p class="footnote" id="fn\1-2"><sup>2</sup> Here is another footnote.</p>$', html) is not None html = textile.textile('''See[1] for details -- or perhaps[100] at a push.\n\nfn1. Here are the details.\n\nfn100(footy#otherid). A totally unrelated footnote.''') assert re.search(r'^\t<p>See<sup class="footnote" id="fnrev([a-f0-9]{32})-1"><a href="#fn\1-1">1</a></sup> for details — or perhaps<sup class="footnote" id="fnrev\1-2"><a href="#fn\1-2">100</a></sup> at a push.</p>\n\n\t<p class="footnote" id="fn\1-1"><sup>1</sup> Here are the details.</p>\n\n\t<p class="footy" id="otherid"><sup id="fn\1-2">100</sup> A totally unrelated footnote.</p>$', html) is not None html = textile.textile('''See[2] for details, and later, reference it again[2].\n\nfn2^(footy#otherid)[en]. Here are the details.''') assert re.search(r'^\t<p>See<sup class="footnote" id="fnrev([a-f0-9]{32})-1"><a href="#fn\1-1">2</a></sup> for details, and later, reference it again<sup class="footnote"><a href="#fn\1-1">2</a></sup>.</p>\n\n\t<p class="footy" id="otherid" lang="en"><sup id="fn\1-1"><a href="#fnrev\1-1">2</a></sup> Here are the details.</p>$', html) is not None html = textile.textile('''See[3!] for details.\n\nfn3. Here are the details.''') assert re.search(r'^\t<p>See<sup class="footnote" id="fnrev([a-f0-9]{32})-1">3</sup> for details.</p>\n\n\t<p class="footnote" id="fn\1-1"><sup>3</sup> Here are the details.</p>$', html) is not None html = textile.textile('''See[4!] for details.\n\nfn4^. Here are the details.''') assert re.search(r'^\t<p>See<sup class="footnote" id="fnrev([a-f0-9]{32})-1">4</sup> for details.</p>\n\n\t<p class="footnote" id="fn\1-1"><sup><a href="#fnrev\1-1">4</a></sup> Here are the details.</p>$', html) is not None
def test_blockcode_in_README(): with open('README.textile') as f: readme = ''.join(f.readlines()) result = textile.textile(readme) with open('tests/fixtures/README.txt') as f: expect = ''.join(f.readlines()) assert result == expect
def GET(self): station = StationSingleton.getStation() returnValue = station.mc.get("podcast") if returnValue: return returnValue title = "Journal of Journal Performance Studies Podcast" link = "http://journalofjournalperformancestudies.org/radio/feed/rss" description = "Podcast for JJPS Radio; http://journalofjournalperformancestudies.org/radio" items = [] podcastItems = station.getPodcastItemsList() for podcastItem in podcastItems: url = "http://journalofjournalperformancestudies.org" + podcastItem["playlist"] datetime = podcastItem['date'] enclosure = PyRSS2Gen.Enclosure("http://journalofjournalperformancestudies.org" + podcastItem["url"], podcastItem["size"], "audio/mpeg") item = PyRSS2Gen.RSSItem(title = podcastItem["title"], link = url, description = "<![CDATA[" + textile.textile(podcastItem["description"]) + "]]>", guid = PyRSS2Gen.Guid(url), enclosure = enclosure, categories = ["journalofjournalperformancestudies.org"], author = "*****@*****.**", pubDate = datetime) items.append(item) rss = PyRSS2Gen.RSS2(title = title, link = link, description = description, lastBuildDate = items[0].pubDate, items = items) podcastXML = rss.to_xml() station.mc.set("podcast", podcastXML, time = 60 * 24) return podcastXML
def parse_directory(current_dir, files, output_dir): files = [f for f in files if ext(f) in options['extensions']] for f in files: inp = os.path.join(current_dir, f) outp = get_outp(os.path.join(output_dir, f)) headers, body = parse(inp) # Attempt to use the file specified template, if not fall back to default. blob = get_template(template) try: blob = get_template(headers['template']) except: pass format = options['format'] try: format = headers['content-type'] except: pass content = {u'text/plain': lambda s: u'<pre>%s</pre>' % s, u'text/x-markdown': lambda s: u'%s' % markdown(s), u'text/x-textile': lambda s: u'%s' % textile(s,head_offset=0, validate=0, sanitize=1, encoding='utf-8', output='utf-8'), u'text/html': lambda s: s}[format](body) values = headers values.update({'content':content}) values.update(options) output = blob.safe_substitute(**values) outf = open(outp, 'w') outf.write(output) outf.close()
def textile(value): try: import textile except ImportError: raise jinja2.TemplateError('textile is not installed!') return textile.textile(value)
def dofile(srcpath): if not issrcfile(srcpath): print("Skipping '%s'" % srcpath) return dstpath = outfilename(srcpath) if dstpath is None: print("Ignoring file '%s'" % srcpath) return tmppath = tmpfilename(srcpath) (txt, tokens, keys) = parse_textile(srcpath) title = "" if "Title" in keys: title = keys["Title"] hdr = header() hdr = hdr.replace("$title", title) ftr = footer() # write(tmppath, txt) html = textile.textile(txt) if g_do_tokens: # print tokens.keys() for token in tokens.keys(): codetxt = tokens[token][1] filename = os.path.basename(tokens[token][0]) c = code_for_filename(tokens[token][0]) srclinktxt = src_html_link(filename) codehtml = srclinktxt + "\n<pre>" + c + "\n" + htmlify(codetxt) + "</code></pre>\n" token = token.strip() html = html.replace(token, codehtml) write(dstpath, hdr + html + ftr)
def readfile(filename, request): entryData = {} d = open(filename).read() # Grab title and body. title = d.split('\n')[0] body = d[len(title):] # Grab textile configuration. config = request.getConfiguration() head_offset = config.get('txtl_head_offset', 0) validate = config.get('txtl_validate', 0) output = config.get('txtl_output', 'ascii') encoding = config.get('txtl_encoding', 'latin-1') body = textile(body, head_offset=head_offset, validate=validate, output=output, encoding=encoding) entryData = {'title': title, 'body': body} # Call the postformat callbacks tools.run_callback('postformat', {'request': request, 'entry_data': entryData}) return entryData
def parse_textile(text): """ :type text: basestring :rtype: basestring """ return textile(text=text, encoding='utf-8', output='utf-8')
def new_entry(request): main = get_renderer(BASE_TEMPLATE).implementation() bibitex_form = BibitexForm.get_form() if 'submit' in request.POST: controls = request.POST.items() try: appstruct = bibitex_form.validate(controls) except deform.ValidationFailure, e: return{'main':main, 'form': e.render(), 'user':get_user(request), } bibitex = appstruct.copy() del(bibitex['document']) appstruct['bibitex'] = create_bibitex(bibitex) if appstruct['wiki']: appstruct['wiki_as_html'] = textile(appstruct['wiki']) else: appstruct['wiki_as_html'] = '' appstruct['modified_at'] = str(datetime.now()) bibitex = Bibitex.from_python(appstruct) bibitex.save(request.couchdb) indexer.index(bibitex._id,appstruct) return HTTPFound(location='/biblio/%s' % bibitex._id)
def html(self): if self.format == 'md': return markdown(self.text, safe_mode='escape') if self.format == 'rst': return publish_parts(self.text, writer_name='html')['html_body'] if self.format == 'textile': return textile.textile(sanitizer.Filter(self.text))
def GET(self): title = "Journal of Journal Performance Studies" link = "http://journalofjournalperformancestudies.org/feed/rss" description = "RSS feed of posts for http://journalofjournalperformancestudies.org" results = webDB.select("posts", limit=10, order="datetime DESC") items = [] for result in results: url = "http://journalofjournalperformancestudies.org/post/" + str(result["pid"]) datetime = result['datetime'] timeTuple = time.localtime(datetime) timeFormatted = time.strftime("%a, %d %b %Y %H:%M:%S", timeTuple) item = PyRSS2Gen.RSSItem(title = result["title"], link = url, description = textile.textile(result["content"]), guid = PyRSS2Gen.Guid(url), categories = ["journalofjournalperformancestudies.org"], author = "*****@*****.**", pubDate = timeFormatted) items.append(item) rss = PyRSS2Gen.RSS2(title = title, link = link, description = description, lastBuildDate = items[0].pubDate, items = items) return rss.to_xml()
def textile(value): try: import textile except ImportError: return value else: return textile.textile(value, encoding='utf-8')
def text_content(self): if self.size <= MAX_TEXTFILE_SIZE and not self.is_image: possible_markdown = self.extension in (MARKDOWN_FILE_EXTENSIONS + TEXTILE_FILE_EXTENSIONS) fake_extension = self.extension if not possible_markdown else u'txt' fake_filename = u'.'.join((self.filename, fake_extension,)) style = styles.get_style_by_name('friendly') formatter = formatters.HtmlFormatter(style=style) style = formatter.get_style_defs() f = urlopen(self.file_obj.cdn_url) data = f.read() f.close() try: data = data.decode('utf-8') lexer = lexers.guess_lexer_for_filename(fake_filename, data) except (ClassNotFound, UnicodeDecodeError): return None if isinstance(lexer, lexers.TextLexer) and possible_markdown: format_string = u'<div class="%s">%s</div>' if self.extension in MARKDOWN_FILE_EXTENSIONS: data = format_string % ('markdown', markdown(data)) if self.extension in TEXTILE_FILE_EXTENSIONS: data = format_string % ('textile', textile(data)) else: data = u'<style>%s</style>\n%s' % (style, highlight(data, lexer, formatter)) return data
def parse(self, text): """Parses and renders a text as HTML regarding current format. """ if self.format == 'markdown': try: import markdown except ImportError: raise RuntimeError(u"Looks like markdown is not installed") return markdown.markdown(text, self.md_extensions) elif self.format == 'restructuredtext': try: from rst import html_body except ImportError: raise RuntimeError(u"Looks like docutils are not installed") html = html_body(text, input_encoding=self.encoding) # RST generates pretty much markup to be removed in our case for (pattern, replacement, mode) in self.RST_REPLACEMENTS: html = re.sub(pattern, replacement, html, mode) return html.strip() elif self.format == 'textile': try: import textile except ImportError: raise RuntimeError(u"Looks like textile is not installed") return textile.textile(text, encoding=self.encoding) else: raise NotImplementedError(u"Unsupported format %s, cannot parse" % self.format)
def test_github_issue_28(): test = """So here I am porting my ancient "newspipe":newspipe "front-end":blog/2006/09/30/0950 to "Snakelets":Snakelets and "Python":Python, and I've just trimmed down over 20 lines of "PHP":PHP down to essentially one line of "BeautifulSoup":BeautifulSoup retrieval: <pre> def parseWapProfile(self, url): result = fetch.fetchURL(url) soup = BeautifulStoneSoup(result['data'], convertEntities=BeautifulStoneSoup.HTML_ENTITIES) try: width, height = soup('prf:screensize')[0].contents[0].split('x') except: width = height = None return {"width": width, "height": height} </pre> Of course there's a lot more error handling to do (and useful data to glean off the "XML":XML), but being able to cut through all the usual parsing crap is immensely gratifying.""" result = textile.textile(test) expect = ("""\t<p>So here I am porting my ancient <a href="newspipe">newspipe</a> <a href="blog/2006/09/30/0950">front-end</a> to <a href="Snakelets">Snakelets</a> and <a href="Python">Python</a>, and I’ve just trimmed down over 20 lines of <a href="PHP"><span class="caps">PHP</span></a> down to essentially one line of <a href="BeautifulSoup">BeautifulSoup</a> retrieval:</p> <pre> def parseWapProfile(self, url): result = fetch.fetchURL(url) soup = BeautifulStoneSoup(result['data'], convertEntities=BeautifulStoneSoup.HTML_ENTITIES) try: width, height = soup('prf:screensize')[0].contents[0].split('x') except: width = height = None return {"width": width, "height": height} </pre> \t<p>Of course there’s a lot more error handling to do (and useful data to glean off the <a href="XML"><span class="caps">XML</span></a>), but being able to cut through all the usual parsing crap is immensely gratifying.</p>""") assert result == expect
def render(self, context): # pagelets can automagically use pagelets templatetags # in order to remove boilerplate loaded_cms = AUTO_LOAD_TEMPLATE_TAGS + self.content """ skip the first portions of render_to_string() ( finding the template ) and go directly to compiling the template/pagelet render_to_string abbreviated: def render_to_string(template_name, dictionary=None, context_instance=None): t = select/get_template(template_name) template = get_template_from_string(source, origin, template_name) return Template(source, origin, name) t.render(context_instance) """ #XXX is this what the origin should be? origin = StringOrigin('pagelet: %s' % self.slug) compiled = compile_string(loaded_cms, origin).render(context) try: if self.type in ('html', 'tinymce', 'wymeditor'): html = compiled elif self.type == "textile": from textile import textile html = textile(str(compiled)) elif self.type == "markdown": from markdown import markdown html = markdown(compiled) return html except TemplateSyntaxError, e: return 'Syntax error, %s' % e
def get_html(self, string): """Returns html string of a textile content. string -- string to process """ return textile.textile(string)
def convert(self, orig, data, **kwargs): if HAS_TEXTILE: html = textile_transformer.textile(orig, encoding='utf-8', output='utf-8') else: html = orig data.setData(html) return data
'*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**', '*****@*****.**' ] subj = 'Merry X-Mas and Happy Holidays ' subj = 'Test new SMTP ' + str(datetime.datetime.today()) text = "Hi , \n I'm reaching out to set up a quick call to discuss how XOR can help you automate your communications to go from “cold candidate outreach” to “interview scheduled” in 5 minutes.\n\nGiven your role, In assume that shortening time-to-hire and increasing hiring efficiency is a priority.\n XOR is helping employers like McDonald’s, IKEA, and Manpower Group hire faster by automating text messages to announce new job postings, screen candidates,\nand schedule interviews, so your recruiting team is only speaking with qualified candidates.\n\nWe also integrate with 30 different ATS’s and job boards and offer the best support and implementation in the industry.\n\nDo you have time for a quick call to discuss how XOR can help you automate your recruiting communications?\n\n\n\n\n\nWith best regards,\n" text = textile.textile(text) # text = textile.textile(text) # unsubscribe #text = text + "<p>If you would like to unsubscribe and stop receiving these emails click <a href="+"'mailto:[email protected]?subject=Unsubscribe me&body=Helo, Unsubscribe me'"+">here</a>.</p>" s = smtplib.SMTP(server, port) """#s.connect(server, port) #print(a)""" a = s.ehlo() print(a) """#a = s.helo() #print(a) a = s.ehlo_or_helo_if_needed()
def render(self, text, **kwargs): return textile.textile(text)
""" Pull slashdot feed """ #!/usr/bin/python __author__ = 'dev' import urllib.request as ur import datetime as dt import bs4 as beau import textile as newhtml STRLIST = '' SDFEED = 'http://rss.slashdot.org/Slashdot/slashdotMain' OPENURL = ur.urlopen(SDFEED) #print("Status: {0}\nURL: {1}\n{2}".format(OPENURL.getcode(), OPENURL.geturl(), OPENURL.info())) MYSOUP = beau.BeautifulSoup(OPENURL, 'lxml') #print(MYSOUP.title.string) #print("Total length is {0}\n".format(len(MYSOUP.text))) DTMVAR = dt.datetime.now().strftime("%Y-%m-%d %H:%M:%S") STRLIST = '[' + DTMVAR + ']From "' + MYSOUP.title.string + '":' + OPENURL.geturl() + '\n\n' for SENTRY in MYSOUP.find_all("title"): if SENTRY.text not in ('Slashdot', 'Search Slashdot'): STRLIST = STRLIST + '* ' + SENTRY.text + '\n' OUTHTML = newhtml.textile(STRLIST) print(OUTHTML)
def render_textile(text): # 2.2.0 and later return textile.textile(text)
def render_textile(text): text = text.encode('utf-8') rv = textile.textile(text) return rv.decode('utf-8')
def html(self): return textile.textile(self.content)