def test_script(): """Test markdown reader""" doc = pweave.Pweb("tests/publish/publish_test.txt", doctype="pandoc", informat="script") doc.tangle() assertSameContent("tests/publish/publish_test.py", "tests/publish/publish_test_REF.py")
def setUp(self): self.doc = pweave.Pweb("tests/formats/formatters_test.pmd") #self.doc.run() #pickle.dump(doc.executed, open("formats/formatters_test.pkl", "wb")) e = pickle.load(open("tests/formats/formatters_test.pkl", "rb")) self.doc.executed = e self.out_base = "tests/formats/formatters_test.%s" self.ref_base = "tests/formats/formatters_test_REF.%s"
def publish_to_markdown(python_file: str, output_file: str): doc = pweave.Pweb(python_file, kernel="python3", doctype="markdown", output=output_file) doc.theme = "skeleton" # The default option is skeleton , other options are pweave (the old theme), bootstrap , cerulean and journal. All look the same for me. doc.read() doc.run() doc.format() doc.formatted += f"\n---\nMarkdown generated automatically from [{python_file}]({python_file}) using [Pweave](http://mpastell.com/pweave) {pweave.__version__} on {datetime.date.today()}.\n" doc.write()
def weave(): r""" This provides a callable script that mimics the `Pweave` command but uses our specially purposed Pandoc formatter and cache retry wrapper. TODO: Much of this isn't needed anymore, so refactor. Especially since the retry stuff should just be in a `Pweave.Processor`. Could we use `os.execvp('Pweave', ['Pweave'] + opts)`? """ if len(sys.argv) == 1: print("Enter PynowebWeave -h for help") sys.exit() parser = OptionParser(usage="PynowebWeave [options] sourcefile") parser.add_option("-d", "--documentation-mode", dest="docmode", action="store_true", default=False, help=("Use documentation mode, chunk code and results" " will be loaded from cache and inline code will" " be hidden")) parser.add_option("-c", "--cache-results", dest="cache", action="store_true", default=False, help="Cache results to disk for documentation mode") parser.add_option("-F", "--figure-directory", dest="figdir", default='figures', help=("Directory path for matplolib graphics: " "Default 'figures'")) parser.add_option("-o", "--output-file", dest="output", default=None, help="Path and filename for output file") parser.add_option("-k", "--kernel", dest="kernel", default="python3", help="Jupyter kernel in which to process code") (options, args) = parser.parse_args() try: infile = args[0] except IndexError: infile = "" opts_dict = vars(options) # set some global options rcParams['figdir'] = opts_dict.pop('figdir', None) rcParams['storeresults'] = opts_dict.pop('cache', None) rcParams["chunk"]["defaultoptions"].update({'wrap': False}) weave_kernel = opts_dict.pop('kernel') # pweb_formatter = PwebMintedPandoc(infile, # format="tex", # shell=shell_opt, # figdir=rcParams['figdir'], # output=opts_dict.pop('output', None), # docmode=opts_dict.pop('docmode', None)) out_file = opts_dict.pop('output', None) out_dir, out_filename = os.path.split(out_file) _, out_filename_ext = os.path.splitext(out_filename) weaver = pweave.Pweb( infile, doctype=out_filename_ext[1:], kernel=weave_kernel, # XXX: Pydoc is super confusing; this # should be the output dir and filename. output=out_file, figdir=rcParams['figdir'], kernel_args={'embed_kernel': False}) weaver.documentationmode = opts_dict.pop('docmode', None) weaver.setformat(Formatter=PwebMintedPandocFormatter) # if weave_format_opts is not None: # weaver.updateformat(weave_format_opts) weave_retry_cache(weaver)
#!/usr/bin/python3 # Marek's output hooks hacks import sys import pweave if len(sys.argv) != 3: print("call: script infile outfile") sys.exit() doc = pweave.Pweb(sys.argv[1], informat=None, doctype="sphinx", kernel="python3", output=sys.argv[2], figdir="figures", mimetype=None) doc.documentationmode = False pweave.rcParams["usematplotlib"] = True pweave.rcParams["cachedir"] = "cache" pweave.rcParams["storeresults"] = False class PwebSphinxFormatter2(pweave.PwebSphinxFormatter): def initformat(self): pweave.PwebSphinxFormatter.initformat(self) self.formatdict["indent"] = ' ## '
def nvim_weave_file(self, *args, **kwargs): """ Weaves the current buffer with Pweave. The weaving process relies on a few vim variables: * `noweb_weave_language`: name of the Jupyter language kernel for the code in the document's code chunks (e.g. 'python3'). * `noweb_weave_backend`: name of the typesetting language in which the code is embedded. In other words, the file format of the weaving's output. * `noweb_format_opts`: Pweave formatter dictionary. See http://mpastell.com/pweave/customizing.html. * `noweb_weave_docmode`: Set Pweave's docmode option. * `noweb_backend_src_dir`: Location/destination for the resulting backend source file. * `noweb_figures_dir`: Destination for resulting figures. * `noweb_weave_formatter`: Name of the Pweave output format. See http://mpastell.com/pweave/formats.html. If you would like to add new Pweave formats or change default Pweave values, make these changes via the standard Pweave route (e.g. http://mpastell.com/pweave/defaults.html) using Vim's Python capabilities (e.g. `:python ...`) *after* this plugin has loaded. """ currbuf = self.nvim.current.buffer weave_format_opts = self._get_any_var('noweb_format_opts', {'width': r'\linewidth'}) weave_kernel = self._get_any_var('noweb_weave_language', None) if weave_kernel is None: weave_kernel = self._get_any_var('noweb_language', None) file_out_ext = self._get_any_var('noweb_weave_backend', None) if file_out_ext is None: file_out_ext = self._get_any_var('noweb_backend', None) weave_docmode = self._get_any_var('noweb_weave_docmode', True) backend_src_dir = self._get_any_var('noweb_backend_src_dir', './') figures_dir = self._get_any_var('noweb_figures_dir', './') # TODO: Could also use `g:vimtex_latexmk_build_dir`. # build_dir = self._get_any_var('latex_build_dir', './') project_dir, input_file = os.path.split(currbuf.name) input_file_base, input_file_ext = os.path.splitext(input_file) output_filename = input_file_base + os.path.extsep + file_out_ext output_file = os.path.join(backend_src_dir, output_filename) pweave.rcParams['figdir'] = figures_dir pweave.rcParams['storeresults'] = weave_docmode # E.g. 'texmintedpandoc' # TODO: Enable some means of importing formatters. weave_formatter = self._get_any_var('noweb_weave_formatter') formats_mod = pweave.formatters.PwebFormats formatter_cls = formats_mod.formats.get(weave_formatter, None) if formatter_cls is None: self.nvim.out_write( ("Couldn't find weave formatter {}; " "guessing from extension\n").format(weave_formatter)) weave_formatter = formats_mod.guessFromExtension(file_out_ext) formatter_cls = formats_mod.formats.get(weave_formatter) weaver = pweave.Pweb(input_file, doctype=file_out_ext, kernel=weave_kernel, output=output_file, figdir=figures_dir) weaver.documentationmode = weave_docmode weaver.setformat(Formatter=formatter_cls['class']) if weave_format_opts is not None: weaver.updateformat(weave_format_opts) try: # XXX: If we let Pweave output as it likes, apparently Neovim's RPC # gets too upset. with capture() as out: # weaver.weave() weaver.run(Processor=CustomIPythonProcessor) weaver.format() weaver.write() except Exception as e: for line in traceback.format_exc().splitlines(): self.nvim.err_write("{}\n".format(line)) # FYI: Gotta add those newlines; otherwise, Neovim won't flush the # message. self.nvim.out_write("{}\n".format(out[0])) self.nvim.err_write("{}\n".format(out[1]))