示例#1
0
def generate_ace_editor(generator):
    """Generate a snippet, call quickly on a Pelican template."""
    generator.ace_editor = "<script %s%s%s></script>" % (
        'src="%s/%s/ace.js" ' % (generator.settings.get("SITEURL"), ACE_PATH),
        'type="text/javascript" ',
        'charset="utf-8"',
    )
    generator.ace_editor += "<style>"
    static_path = path.join(path.dirname(__file__), "static", "style.css")
    try:
        with pelican_open(static_path) as text:
            generator.ace_editor += text + "</style>"
    except OSError:
        error("""file "%s" does not exist""" % static_path)
    generator.ace_editor += "<script>"

    js_var = JsVar(generator)
    js_var.add("ACE_EDITOR_SCROLL_TOP_MARGIN")
    js_var.add("ACE_EDITOR_THEME")
    js_var.add("ACE_EDITOR_MAXLINES")
    js_var.add("ACE_EDITOR_READONLY")
    js_var.add("ACE_EDITOR_AUTOSCROLL")
    js_var.add("ACE_EDITOR_SHOW_INVISIBLE")

    script_path = path.join(path.dirname(__file__), "static", "script.js")
    try:
        with pelican_open(script_path) as text:
            generator.ace_editor += text + "</script>"
    except OSError:
        error("""file "%s" does not exist""" % script_path)

    generator._update_context(["ace_editor"])
示例#2
0
def generate_ace_editor(generator):
    """Generate a snippet, call quickly on a Pelican template."""
    generator.ace_editor = '<script %s%s%s></script>' % (
        'src="%s/%s/ace.js" ' % (generator.settings.get('SITEURL'), ACE_PATH),
        'type="text/javascript" ', 'charset="utf-8"')
    generator.ace_editor += '<style>'
    static_path = path.join(path.dirname(__file__), "static", "style.css")
    try:
        with pelican_open(static_path) as text:
            generator.ace_editor += text + '</style>'
    except OSError:
        error('''file "%s" does not exist''' % static_path)
    generator.ace_editor += '<script>'

    js_var = JsVar(generator)
    js_var.add('ACE_EDITOR_SCROLL_TOP_MARGIN')
    js_var.add('ACE_EDITOR_THEME')
    js_var.add('ACE_EDITOR_MAXLINES')
    js_var.add('ACE_EDITOR_READONLY')
    js_var.add('ACE_EDITOR_AUTOSCROLL')
    js_var.add('ACE_EDITOR_SHOW_INVISIBLE')

    script_path = path.join(path.dirname(__file__), "static", "script.js")
    try:
        with pelican_open(script_path) as text:
            generator.ace_editor += text + '</script>'
    except OSError:
        error('''file "%s" does not exist''' % script_path)

    generator._update_context(['ace_editor'])
示例#3
0
def generate_ace_editor(generator):
    """Generate a snippet, call quickly on a Pelican template."""
    generator.ace_editor = '<script %s%s%s></script>' % (
        'src="%s/%s/ace.js" ' % (generator.settings.get('SITEURL'), ACE_PATH),
        'type="text/javascript" ',
        'charset="utf-8"'
    )
    generator.ace_editor += '<style>'
    static_path = path.join(path.dirname(__file__), "static", "style.css")
    try:
        with pelican_open(static_path) as text:
            generator.ace_editor += text + '</style>'
    except OSError:
        error('''file "%s" does not exist''' % static_path)
    generator.ace_editor += '<script>'

    js_var = JsVar(generator)
    js_var.add('ACE_EDITOR_SCROLL_TOP_MARGIN')
    js_var.add('ACE_EDITOR_THEME')
    js_var.add('ACE_EDITOR_MAXLINES')
    js_var.add('ACE_EDITOR_READONLY')
    js_var.add('ACE_EDITOR_AUTOSCROLL')
    js_var.add('ACE_EDITOR_SHOW_INVISIBLE')

    script_path = path.join(path.dirname(__file__), "static", "script.js")
    try:
        with pelican_open(script_path) as text:
            generator.ace_editor += text + '</script>'
    except OSError:
        error('''file "%s" does not exist''' % script_path)

    generator._update_context(['ace_editor'])
示例#4
0
文件: mdimport.py 项目: sh0sh1n/www
	def read(self, filename):
		"""Parse content and metadata of markdown files"""

		self._md = Markdown(extensions=self.extensions)

		with pelican_open(filename) as mdi:
			with pelican_open(re.search(r"Source: ([\w/\\\.-]*)", mdi).group(1)) as md:
				md = re.sub(r'\(([^/()]*).md((?:#[-a-z]*)?)\)', r'(\1.html\2)', md)
				content = self._md.convert(mdi+"Display: mdimport\n"+md)

		metadata = self._parse_metadata(self._md.Meta)
		return content, metadata
示例#5
0
    def read(self, filename):
        with pelican_open(filename) as fp:
            text = list(fp.splitlines())

        metadata = {}
        for i, line in enumerate(text):
            kv = line.split(':', 1)
            if len(kv) == 2:
                name, value = kv[0].lower(), kv[1].strip()
                metadata[name] = self.process_metadata(name, value)
            else:
                content = "\n".join(text[i:])
                break

        extra_args = self.settings.get('PANDOC_ARGS', [])
        extensions = self.settings.get('PANDOC_EXTENSIONS', '')
        if isinstance(extensions, list):
            extensions = ''.join(extensions)

        pandoc_cmd = ["pandoc", "--from=markdown" + extensions, "--to=html5"]
        pandoc_cmd.extend(extra_args)

        proc = subprocess.Popen(pandoc_cmd,
                                stdin = subprocess.PIPE,
                                stdout = subprocess.PIPE)

        output = proc.communicate(content.encode('utf-8'))[0].decode('utf-8')
        status = proc.wait()
        if status:
            raise subprocess.CalledProcessError(status, pandoc_cmd)

        return output, metadata
示例#6
0
    def read(self, filename):
        """Parse content and metadata of markdown files"""
        # parse Rmd file - generate md file
        md_filename = filename.replace(".Rmd", ".aux").replace(".rmd", ".aux")
        robjects.r(
            """
require(knitr);
opts_knit$set(base.dir='{2}/content');
knit('{0}', '{1}', quiet=TRUE, encoding='UTF-8');
""".format(
                filename, md_filename, settings.DEFAULT_CONFIG.get("PATH")
            )
        )
        # parse md file
        md = Markdown(extensions=["meta", "codehilite(css_class=highlight)", "extra"])
        with pelican_open(md_filename) as text:
            content = md.convert(text)
        os.remove(md_filename)
        # find metadata
        metadata = {}
        for name, value in md.Meta.items():
            name = name.lower()
            meta = self.process_metadata(name, value[0])
            metadata[name] = meta
        return content, metadata
示例#7
0
    def read(self, filename):
        with pelican_open(filename) as fp:
            text = list(fp.splitlines())

        metadata = {}
        for i, line in enumerate(text):
            kv = line.split(":", 1)
            if len(kv) == 2:
                name, value = kv[0].lower(), kv[1].strip()
                metadata[name] = self.process_metadata(name, value)
            else:
                content = "\n".join(text[i:])
                break

        mmd_cmd = ["multimarkdown"]

        proc = subprocess.Popen(mmd_cmd,
                                stdin=subprocess.PIPE,
                                stdout=subprocess.PIPE)

        output = proc.communicate(content.encode("utf-8"))[0].decode("utf-8")
        status = proc.wait()
        if status:
            raise subprocess.CalledProcessError(status, mmd_cmd)

        return output, metadata
示例#8
0
    def read(self, filename):
        with pelican_open(filename) as text:
            md_slides = text.split('\n---\n')

            slides = []
            # Process each slide separately.
            for md_slide in md_slides:
                slide = {}
                sections = md_slide.split('\n\n')
                # Extract metadata at the beginning of the slide (look for key: value)
                # pairs.
                metadata_section = sections[0]
                metadata = self.parse_metadata(metadata_section)
                slide.update(metadata)
                remainder_index = metadata and 1 or 0
                # Get the content from the rest of the slide.
                content_section = '\n\n'.join(sections[remainder_index:])
                html = markdown.markdown(content_section,
                                         extensions=self.extensions)
                slide['content'] = self.postprocess_html(html, metadata)
                slides.append(slide)
            metadata = {
                'slides': slides,
                'title': slides[0]['title'],
                'date': get_date(slides[0]['date']),
                'template': 'slide'
            }
            return "", metadata
示例#9
0
    def read(self, filename):
        with pelican_open(filename) as fp:
            text = list(fp.splitlines())

        metadata = {}
        for i, line in enumerate(text):
            kv = line.split(':', 1)
            if len(kv) == 2:
                name, value = kv[0].lower(), kv[1].strip()
                metadata[name] = self.process_metadata(name, value)
            else:
                content = "\n".join(text[i:])
                break

        extra_args = self.settings.get('PANDOC_ARGS', [])
        extensions = self.settings.get('PANDOC_EXTENSIONS', '')
        if isinstance(extensions, list):
            extensions = ''.join(extensions)

        pandoc_cmd = [
            "pandoc", "+RTS", "-K512m", "-RTS", "--from=markdown" + extensions,
            "--to=html5"
        ]
        pandoc_cmd.extend(extra_args)

        proc = subprocess.Popen(pandoc_cmd,
                                stdin=subprocess.PIPE,
                                stdout=subprocess.PIPE)

        output = proc.communicate(content.encode('utf-8'))[0].decode('utf-8')
        status = proc.wait()
        if status:
            raise subprocess.CalledProcessError(status, pandoc_cmd)

        return output, metadata
示例#10
0
    def test_turkish_locale(self):
        if platform == 'win32':
            locale_string = 'Turkish'
        else:
            locale_string = 'tr_TR.UTF-8'
        settings = read_settings(
            override={
                'LOCALE': locale_string,
                'TEMPLATE_PAGES': {
                    'template/source.html': 'generated/file.html'
                }
            })

        generator = TemplatePagesGenerator(
            {'date': self.date}, settings,
            self.temp_content, '', self.temp_output)
        generator.env.filters.update({'strftime': utils.DateFormatter()})

        writer = Writer(self.temp_output, settings=settings)
        generator.generate_output(writer)

        output_path = os.path.join(
            self.temp_output, 'generated', 'file.html')

        # output file has been generated
        self.assertTrue(os.path.exists(output_path))

        # output content is correct
        with utils.pelican_open(output_path) as output_file:
            self.assertEqual(output_file,
                             utils.strftime(self.date, 'date = %A, %d %B %Y'))
    def read(self, source_path):
        """Parse content and metadata of asciidoc files"""
        from cStringIO import StringIO
        with pelican_open(source_path) as source:
            text = StringIO(source.encode('utf8'))
        content = StringIO()
        ad = AsciiDocAPI()

        options = self.settings.get('ASCIIDOC_OPTIONS', [])
        options = self.default_options + options
        for o in options:
            ad.options(*o.split())

        backend = self.settings.get('ASCIIDOC_BACKEND', self.default_backend)
        ad.execute(text, content, backend=backend)
        content = content.getvalue().decode('utf8')

        metadata = {}
        for name, value in ad.asciidoc.document.attributes.items():
            if value is None:
                continue
            name = name.lower()
            metadata[name] = self.process_metadata(name, six.text_type(value))
        if 'doctitle' in metadata:
            metadata['title'] = metadata['doctitle']
        return content, metadata
    def read(self, source_path):
        """Parse content and metadata of creole files"""

        self._metadata = {}
        with pelican_open(source_path) as text:
            content = creole2html(text, macros={'header': self._parse_header_macro})
        return content, self._metadata
示例#13
0
 def read(self, filename):
     logger.debug("pandoc_reader: reading '{}'".format(filename))
     with pelican_open(filename) as fp:
         text = list(fp.splitlines())
     content,metadata = self._extract_metadata(text)
     output = self._convert_markdown(content)
     return output, metadata
示例#14
0
    def read(self, source_path):
        """
        Parse, and return (content, metadata)
        """
        parser = email.parser.Parser()
        with pelican_open(source_path) as source:
            message = parser.parsestr(source)
        location = message.get('location')
        if not location:
            raise ValueError(
                u"RedirectReader requires a 'location' header in the file")

        delay = float(message.get('delay', 0))

        metadata = {
            'title': message.get('title', u''),
            'location': location,
            'delay': delay,
            'status': message.get('status', 'hidden')
        }

        # Slug is important because it Pelican's slugification affects
        # the final URL, and we care about exact URLs here.
        # So for redirect files, we assume that you named them carefully.
        # And allow overriding by explicit slug.
        slug = message.get('slug')
        if not slug:
            slug = os.path.splitext(os.path.basename(source_path))[0]
        if slug:
            metadata['slug'] = slug

        content = message.get_payload().strip()
        return content, metadata
    def read(self, source_path):
        """Parse Pandoc Markdown and return HTML5 markup and metadata."""
        # Get the user-defined path to the Pandoc executable or fall back to default
        pandoc_executable = self.settings.get(
            "PANDOC_EXECUTABLE_PATH", DEFAULT_PANDOC_EXECUTABLE
        )

        # If user-defined path, expand and make it absolute in case the path is relative
        if pandoc_executable != DEFAULT_PANDOC_EXECUTABLE:
            pandoc_executable = os.path.abspath(os.path.expanduser(pandoc_executable))

        # Check if pandoc is installed and is executable
        if not shutil.which(pandoc_executable):
            raise Exception("Could not find Pandoc. Please install.")

        # Check if the version of pandoc installed is 2.11 or higher
        self._check_pandoc_version(pandoc_executable)

        # Open Markdown file and read content
        content = ""
        with pelican_open(source_path) as file_content:
            content = file_content

        # Retrieve HTML content and metadata
        output, metadata = self._create_html(source_path, content, pandoc_executable)

        return output, metadata
示例#16
0
    def read(self, source_path):
        """Parse content and metadata of asciidoc files"""
        from cStringIO import StringIO
        with pelican_open(source_path) as source:
            text = StringIO(source)
        content = StringIO()
        ad = AsciiDocAPI()

        options = self.settings.get('ASCIIDOC_OPTIONS', [])
        if isinstance(options, (str, unicode)):
            options = [m.strip() for m in options.split(',')]
        options = self.default_options + options
        for o in options:
            ad.options(*o.split())

        ad.execute(text, content, backend="html4")
        content = content.getvalue()

        metadata = {}
        for name, value in ad.asciidoc.document.attributes.items():
            name = name.lower()
            metadata[name] = self.process_metadata(name, value)
        if 'doctitle' in metadata:
            metadata['title'] = metadata['doctitle']
        return content, metadata
    def read(self, filename):
        with pelican_open(filename) as fp:
            text = list(fp.splitlines())

        metadata = {}
        for i, line in enumerate(text):
            meta_match = re.match(r'^#\+([a-zA-Z]+):(.*)', line)
            if meta_match:
                name = meta_match.group(1).lower()
                value = meta_match.group(2).strip()
                metadata[name] = self.process_metadata(name, value)
            else:
                content = "\n".join(text[i:])
                break

        extra_args = self.settings.get('ORG_PANDOC_ARGS', [])
        extensions = self.settings.get('ORG_PANDOC_EXTENSIONS', '')
        if isinstance(extensions, list):
            extensions = ''.join(extensions)

        pandoc_cmd = ["pandoc", "--from=org" + extensions, "--to=html5"]
        pandoc_cmd.extend(extra_args)

        proc = subprocess.Popen(pandoc_cmd,
                                stdin=subprocess.PIPE,
                                stdout=subprocess.PIPE)

        output = proc.communicate(content.encode('utf-8'))[0].decode('utf-8')
        status = proc.wait()
        if status:
            raise subprocess.CalledProcessError(status, pandoc_cmd)

        return output, metadata
示例#18
0
    def read(self, filename):
        with pelican_open(filename) as fp:
            text = list(fp.splitlines())

        metadata = {}
        for i, line in enumerate(text):
            kv = line.split(':', 1)
            if len(kv) == 2:
                name, value = kv[0].lower(), kv[1].strip()
                metadata[name] = self.process_metadata(name, value)
            else:
                content = "\n".join(text[i:])
                break

        mmd_cmd = ["multimarkdown"]

        proc = subprocess.Popen(mmd_cmd,
                                stdin = subprocess.PIPE,
                                stdout = subprocess.PIPE)

        output = proc.communicate(content.encode('utf-8'))[0].decode('utf-8')
        status = proc.wait()
        if status:
            raise subprocess.CalledProcessError(status, mmd_cmd)

        return output, metadata
示例#19
0
    def read(self, filename):
        with pelican_open(filename) as fp:
            text = list(fp.splitlines())

        metadata = {}
        for i, line in enumerate(text):
            meta_match = re.match(r'^#\+([a-zA-Z]+):(.*)', line)
            if meta_match:
                name = meta_match.group(1).lower()
                value = meta_match.group(2).strip()
                metadata[name] = self.process_metadata(name, value)
            else:
                content = "\n".join(text[i:])
                break

        extra_args = self.settings.get('ORG_PANDOC_ARGS', [])
        extensions = self.settings.get('ORG_PANDOC_EXTENSIONS', '')
        if isinstance(extensions, list):
            extensions = ''.join(extensions)

        pandoc_cmd = ["pandoc", "--from=org" + extensions, "--to=html5"]
        pandoc_cmd.extend(extra_args)

        proc = subprocess.Popen(pandoc_cmd,
                                stdin = subprocess.PIPE,
                                stdout = subprocess.PIPE)

        output = proc.communicate(content.encode('utf-8'))[0].decode('utf-8')
        status = proc.wait()
        if status:
            raise subprocess.CalledProcessError(status, pandoc_cmd)

        return output, metadata
示例#20
0
    def read(self, source_path):
        """Parse content and metadata of asciidoc files"""
        from cStringIO import StringIO
        with pelican_open(source_path) as source:
            text = StringIO(source)
        content = StringIO()
        ad = AsciiDocAPI()

        options = self.settings.get('ASCIIDOC_OPTIONS', [])
        if isinstance(options, (str, unicode)):
            options = [m.strip() for m in options.split(',')]
        options = self.default_options + options
        for o in options:
            ad.options(*o.split())

        ad.execute(text, content, backend="html4")
        content = content.getvalue()

        metadata = {}
        for name, value in ad.asciidoc.document.attributes.items():
            name = name.lower()
            metadata[name] = self.process_metadata(name, value)
        if 'doctitle' in metadata:
            metadata['title'] = metadata['doctitle']
        return content, metadata
示例#21
0
    def read(self, filename):
        with pelican_open(filename) as fp:
            text = list(fp.splitlines())

        metadata = {}
        for i, line in enumerate(text):
            kv = line.split(":", 1)
            if len(kv) == 2:
                name, value = kv[0].lower(), kv[1].strip()
                metadata[name] = self.process_metadata(name, value)
            else:
                content = "\n".join(text[i:])
                break

        t2t_cmd = [
            r"txt2tags",
            r"--encoding=utf-8",
            r"--target=html",
            r"--infile=-",
            r"--outfile=-",
            r"--no-headers",
        ]

        proc = subprocess.Popen(t2t_cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)

        output = proc.communicate(content.encode("utf-8"))[0].decode("utf-8")
        status = proc.wait()
        if status:
            raise subprocess.CalledProcessError(status, t2t_cmd)

        return output, metadata
示例#22
0
    def read(self, source_path):
        """Parse content and metadata of asciidoc files"""
        from cStringIO import StringIO
        with pelican_open(source_path) as source:
            text = StringIO(source.encode('utf8'))
        content = StringIO()
        ad = AsciiDocAPI()

        options = self.settings.get('ASCIIDOC_OPTIONS', [])
        options = self.default_options + options
        for o in options:
            ad.options(*o.split())

        backend = self.settings.get('ASCIIDOC_BACKEND', self.default_backend)
        ad.execute(text, content, backend=backend)
        content = content.getvalue().decode('utf8')

        metadata = {}
        for name, value in ad.asciidoc.document.attributes.items():
            if value is None:
                continue
            name = name.lower()
            metadata[name] = self.process_metadata(name, six.text_type(value))
        if 'doctitle' in metadata:
            metadata['title'] = metadata['doctitle']
        return content, metadata
    def read(self, filename):
        with pelican_open(filename) as fp:
            text = list(fp.splitlines())

        metadata = {}
        for i, line in enumerate(text):
            kv = line.split(':', 1)
            if len(kv) == 2:
                name, value = kv[0].lower(), kv[1].strip()
                metadata[name] = self.process_metadata(name, value)
            else:
                content = "\n".join(text[i:])
                break

        t2t_cmd = [r"txt2tags", r"--encoding=utf-8", r"--target=html", r"--infile=-", r"--outfile=-", r"--no-headers"]

        proc = subprocess.Popen(t2t_cmd,
                                stdin = subprocess.PIPE,
                                stdout = subprocess.PIPE)

        output = proc.communicate(content.encode('utf-8'))[0].decode('utf-8')
        status = proc.wait()
        if status:
            raise subprocess.CalledProcessError(status, t2t_cmd)

        return output, metadata
示例#24
0
	def read(self, source_path):
		with pelican_open(source_path) as text:
			data = {}
			pre_data = json.loads(text)
		for k,v in pre_data.items():
			data[k.lower()] = v
		return ("",data)
示例#25
0
    def test_turkish_locale(self):
        if platform == 'win32':
            locale_string = 'Turkish'
        else:
            locale_string = 'tr_TR.UTF-8'
        settings = read_settings(
            override={
                'LOCALE': locale_string,
                'TEMPLATE_PAGES': {
                    'template/source.html': 'generated/file.html'
                }
            })

        generator = TemplatePagesGenerator({'date': self.date}, settings,
                                           self.temp_content, '',
                                           self.temp_output)
        generator.env.filters.update({'strftime': utils.DateFormatter()})

        writer = Writer(self.temp_output, settings=settings)
        generator.generate_output(writer)

        output_path = os.path.join(self.temp_output, 'generated', 'file.html')

        # output file has been generated
        self.assertTrue(os.path.exists(output_path))

        # output content is correct
        with utils.pelican_open(output_path) as output_file:
            self.assertEqual(output_file,
                             utils.strftime(self.date, 'date = %A, %d %B %Y'))
    def read(self, source_path):
        _, metadata = super(JinjaMarkdownReader, self).read(source_path)

        with pelican_open(source_path) as text:
            content = self._md.convert(self.parse_jinja(text))

        return content, metadata
示例#27
0
    def read(self, filename):
        tab_width = self.settings.get('PANDOC_TAB_WIDTH', 8)
        with pelican_open(filename) as fp:
            text = [line.expandtabs(tab_width) for line in fp.splitlines()]

        if text[0] == '---':
            metadata = parse_yaml_metadata(text)
        else:
            metadata = parse_plain_metadata(text)

        metadata = { k: self.process_metadata(k, v)
                     for k, v in metadata.items() }
        content = "\n".join(text)

        extra_args = self.settings.get('PANDOC_ARGS', [])
        extensions = self.settings.get('PANDOC_EXTENSIONS', '')
        if isinstance(extensions, list):
            extensions = ''.join(extensions)

        pandoc_cmd = ["pandoc", "--from=markdown" + extensions, "--to=html5"]
        pandoc_cmd.extend(extra_args)

        proc = subprocess.Popen(pandoc_cmd,
                                stdin = subprocess.PIPE,
                                stdout = subprocess.PIPE)

        output = proc.communicate(content.encode('utf-8'))[0].decode('utf-8')
        status = proc.wait()
        if status:
            raise subprocess.CalledProcessError(status, pandoc_cmd)

        return output, metadata
示例#28
0
    def read(self, source_path):
        """Parse content and metadata of creole files"""

        self._metadata = {}
        with pelican_open(source_path) as text:
            content = creole2html(text,
                                  macros={'header': self._parse_header_macro})
        return content, self._metadata
示例#29
0
    def read(self, source_path):
        """Parse content and metadata of markdown files"""
        text = pelican_open(source_path)
        md = Markdown(extensions=set(self.extensions + ['meta']))
        content = md.convert(text)

        metadata = self._parse_metadata(md.Meta)
        return content, metadata
示例#30
0
    def read(self, filename):
        """Parse content and metadata of markdown files"""
        text = pelican_open(filename)
        md = Markdown(extensions=set(self.extensions + ['meta']))
        content = md.convert(text)

        metadata = self._parse_metadata(md.Meta)
        return content, metadata
示例#31
0
 def _create_pdf(self, obj, output_path):
     if obj.filename.endswith(".rst"):
         filename = obj.slug + ".pdf"
         output_pdf = os.path.join(output_path, filename)
         # print "Generating pdf for", obj.filename, " in ", output_pdf
         self.pdfcreator.createPdf(text=pelican_open(obj.filename),
                                   output=output_pdf)
         info(u' [ok] writing %s' % output_pdf)
示例#32
0
    def read(self, source_path):
        self._source_path = source_path

        with pelican_open(source_path) as text:
            metadata, content = self._parse(text)

        content = self._render(content)
        return content.strip(), self._parse_metadata(metadata)
示例#33
0
 def _create_pdf(self, obj, output_path):
     if obj.filename.endswith(".rst"):
         filename = obj.slug + ".pdf"
         output_pdf=os.path.join(output_path, filename)
         # print "Generating pdf for", obj.filename, " in ", output_pdf
         self.pdfcreator.createPdf(text=pelican_open(obj.filename),
                                   output=output_pdf)
         info(u' [ok] writing %s' % output_pdf)
示例#34
0
    def read(self, source_path):
        self._source_path = source_path

        with pelican_open(source_path) as text:
            metadata, content = self._parse(text)

        content = self._render(content)
        return content.strip(), self._parse_metadata(metadata)
示例#35
0
    def read(self, source_path):
        """Parse content and metadata of markdown files"""

        with pelican_open(source_path) as text:
            content = self._md.convert(text)

        metadata = self._parse_metadata(self._md.Meta)
        return content, metadata
示例#36
0
    def read(self, source_path):
        self._source_path = source_path
        self._md = Markdown(**self.settings['MARKDOWN'])

        with pelican_open(source_path) as text:
            content, metadata = self._process_content(text.strip())

        return self._md.convert(content), self._parse_metadata(metadata)
示例#37
0
    def read(self, source_path):
        self._source_path = source_path
        self._md = Markdown(**self.settings['MARKDOWN'])

        with pelican_open(source_path) as text:
            content, metadata = self._process_content(text.strip())

        return self._md.convert(content), self._parse_metadata(metadata)
示例#38
0
    def read(self, source_path):
        """Parse content and metadata of markdown files"""

        with pelican_open(source_path) as text:
            content = self._md.convert(text)

        metadata = self._parse_metadata(self._md.Meta)
        return content, metadata
示例#39
0
def _copy_from_to(from_file, to_file):
    """
    A very rough and ready copy from / to function.
    """
    with pelican_open(from_file) as text_in:
        encoding = "utf-8"
        with open(to_file, "w", encoding=encoding) as text_out:
            text_out.write(text_in)
            logger.info("show_source: Writing %s", to_file)
示例#40
0
def _copy_from_to(from_file, to_file):
    """
    A very rough and ready copy from / to function.
    """
    with pelican_open(from_file) as text_in:
        encoding = 'utf-8'
        with open(to_file, 'w', encoding=encoding) as text_out:
            text_out.write(text_in)
            logger.info('Writing %s', to_file)
示例#41
0
def _copy_from_to(from_file, to_file):
    """
    A very rough and ready copy from / to function.
    """
    with pelican_open(from_file) as text_in:
        encoding = 'utf-8'
        with open(to_file, 'w', encoding=encoding) as text_out:
            text_out.write(text_in)
            logger.info('Writing %s', to_file)
示例#42
0
文件: readers.py 项目: AN6U5/pelican
    def read(self, source_path):
        """Parse content and metadata of markdown files"""

        with pelican_open(source_path) as text:
            md = Markdown(extensions=set(self.extensions + ['meta']))
            content = md.convert(text)

        metadata = self._parse_metadata(md.Meta)
        return content, metadata
    def read(self, source_path):
        with pelican_open(source_path) as text:
            text = self.env.from_string(text).render()

        with NamedTemporaryFile(delete=False) as f:
            f.write(text.encode())
            f.close()
            content, metadata = super().read(f.name)
            os.unlink(f.name)
            return content, metadata
示例#44
0
    def read(self, source_path):
        with pelican_open(source_path) as text:
            text = self.env.from_string(text).render()

        with NamedTemporaryFile(delete=False) as f:
            f.write(text.encode())
            f.close()
            content, metadata = super().read(f.name)
            os.unlink(f.name)
            return content, metadata
示例#45
0
文件: vyu_releases.py 项目: Xubes/www
def version_replacement(instance):
	patterns = {
		'../datavyu/version.txt': r'%%datavyu-version%%',
		'../datavyu/pre_version.txt': r'%%datavyu-version-pre%%',
	}

	for filename, pattern in patterns.items():
		if 'download.md' in instance.source_path and re.search(pattern, instance._content):
			with pelican_open(filename) as txt:
				instance._content = re.sub(pattern, txt.split()[0], instance._content)
示例#46
0
    def read(self, filename):
        md = Markdown(extensions=self.extensions)

        with pelican_open(filename) as text:
            text = Template(text).render()
            content = md.convert(text)

        metadata = self._parse_metadata(md.Meta)

        return content, metadata
示例#47
0
    def read(self, filename):
        """Parse content and metadata of HTML files"""
        with pelican_open(filename) as content:
            parser = self._HTMLParser(self.settings, filename)
            parser.feed(content)
            parser.close()

        metadata = {}
        for k in parser.metadata:
            metadata[k] = self.process_metadata(k, parser.metadata[k])
        return parser.body, metadata
示例#48
0
    def read(self, filename):
        """Parse content and metadata of (x)HTML files"""
        with pelican_open(filename) as content:
            metadata = {'title': 'unnamed'}
            for i in self._re.findall(content):
                key = i.split(':')[0][5:].strip()
                value = i.split(':')[-1][:-3].strip()
                name = key.lower()
                metadata[name] = self.process_metadata(name, value)

            return content, metadata
示例#49
0
    def read(self, filename):
        """Parse content and metadata of markdown files"""
        text = pelican_open(filename)
        md = Markdown(extensions=set(self.extensions + ['meta']))
        content = md.convert(text)

        metadata = {}
        for name, value in md.Meta.items():
            name = name.lower()
            metadata[name] = self.process_metadata(name, value[0])
        return content, metadata
示例#50
0
    def read(self, filename):
        """Parse content and metadata of markdown files"""
        text = pelican_open(filename)
        md = Markdown(extensions=set(self.extensions + ['meta']))
        content = md.convert(text)

        metadata = {}
        for name, value in md.Meta.items():
            name = name.lower()
            metadata[name] = self.process_metadata(name, value[0])
        return content, metadata
示例#51
0
    def read(self, filename):
        """Parse content and metadata of (x)HTML files"""
        with pelican_open(filename) as content:
            metadata = {'title': 'unnamed'}
            for i in self._re.findall(content):
                key = i.split(':')[0][5:].strip()
                value = i.split(':')[-1][:-3].strip()
                name = key.lower()
                metadata[name] = self.process_metadata(name, value)

            return content, metadata
示例#52
0
    def read(self, filename):
        source_path = osp.relpath(filename, self.settings['PATH'])
        path = normalize_path(osp.splitext(source_path)[0])
        with pelican_open(filename) as content:
            if content[-1] == '\n':
                content = content[:-1]
            link = content

        # XX Hack: 'precursors' is injected into this module in __init__.py
        precursors.append(LinkNodePrecursor(path, link))
        return None, {}
示例#53
0
    def read(self, source_path):
        """Parse content and metadata of markdown files"""

        self._source_path = source_path
        self._md = Markdown(extensions=self.extensions.keys(),
                            extension_configs=self.extensions)
        with pelican_open(source_path) as text:
            content = self._md.convert(text)

        metadata = self._parse_metadata(self._md.Meta)
        return content, metadata
示例#54
0
    def read(self, filename):
        """Parse content and metadata of HTML files"""
        with pelican_open(filename) as content:
            parser = self._HTMLParser(self.settings, filename)
            parser.feed(content)
            parser.close()

        metadata = {}
        for k in parser.metadata:
            metadata[k] = self.process_metadata(k, parser.metadata[k])
        return parser.body, metadata
示例#55
0
def version_replacement(instance):
    patterns = {
        '../datavyu/version.txt': r'%%datavyu-version%%',
        '../datavyu/pre_version.txt': r'%%datavyu-version-pre%%',
    }

    for filename, pattern in patterns.items():
        if 'download.md' in instance.source_path and re.search(
                pattern, instance._content):
            with pelican_open(filename) as txt:
                instance._content = re.sub(pattern,
                                           txt.split()[0], instance._content)
示例#56
0
    def read(self, source_path):
        """Parse MyST Markdown and return HTML5 markup and metadata."""
        # Get the user-defined path to the MyST executable or fall back to default
        # Open Markdown file and read content
        content = ""
        with pelican_open(source_path) as file_content:
            content = file_content

        # Retrieve HTML content and metadata
        metadata = self._extract_metadata(content)
        output = self._create_html(source_path, content)

        return output, metadata
示例#57
0
    def read(self, source_path):
        """Parse content and metadata of markdown files"""

        self._source_path = source_path
        self._md = Markdown(**self.settings['MARKDOWN'])
        with pelican_open(source_path) as text:
            content = self._md.convert(text)

        if hasattr(self._md, 'Meta'):
            metadata = self._parse_metadata(self._md.Meta)
        else:
            metadata = {}
        return content, metadata
示例#58
0
    def read(self, source_path):
        """Parse content and metadata of markdown files"""

        self._source_path = source_path
        self._md = Markdown(**self.settings['MARKDOWN'])
        with pelican_open(source_path) as text:
            content = self._md.convert(text)

        if hasattr(self._md, 'Meta'):
            metadata = self._parse_metadata(self._md.Meta)
        else:
            metadata = {}
        return content, metadata