Pandoc-Elements-0.38000755001750001750 013347276615 13217 5ustar00vojvoj000000000000README100644001750001750 4704113347276615 14206 0ustar00vojvoj000000000000Pandoc-Elements-0.38NAME Pandoc::Elements - create and process Pandoc documents SYNOPSIS The output of this script hello.pl use Pandoc::Elements; use JSON; print Document( { title => MetaInlines [ Str "Greeting" ] }, [ Header( 1, attributes { id => 'top' }, [ Str 'Hello' ] ), Para [ Str 'Hello, world!' ], ], api_version => '1.17.0.4' )->to_json; can be converted for instance to HTML via ./hello.pl | pandoc -f json -t html5 --standalone an equivalent Pandoc Markdown document would be % Greeting # Gruß {.de} Hello, world! DESCRIPTION Pandoc::Elements provides utility functions to parse, serialize, and modify abstract syntax trees (AST) of Pandoc documents. Pandoc can convert this data structure to many other document formats, such as HTML, LaTeX, ODT, and ePUB. See also module Pandoc::Filter, command line script pod2pandoc, and the internal modules Pandoc::Walker and Pod::Simple::Pandoc. PANDOC VERSIONS The Pandoc document model is defined in file Text.Pandoc.Definition as part of Haskell package pandoc-types. Pandoc::Elements is compatible with pandoc-types 1.12.3 (released with pandoc 1.12.1) up to at least pandoc-types-1.17.0.4 (first releases with pandoc 1.18). JSON output of all pandoc releases since 1.12.1 can be parsed with function pandoc_json, the "Document" constructor or method parse of module Pandoc. The AST is always upgraded to pandoc-types 1.17 and downgraded to another api version on serialization with to_json. To determine the api version required by a version of pandoc executable since version 1.18 execute pandoc with the --version option and check which version of the pandoc-types library pandoc was compiled with. Beginning with version 1.18 pandoc will not decode a JSON AST representation unless the major and minor version numbers (Document method api_version) match those built into that version of pandoc. The following changes in pandoc document model have been implemented: * pandoc-types 1.17, released for pandoc 1.18, introduced the LineBlock element and modified representation of the root Document element. * pandoc-types 1.16, released with pandoc 1.16, introduced attributes to Link and Image elements * pandoc-types 1.12.3, released with pandoc 1.12.1, modified the representation of elements to objects with field t and c. This is also the internal representation of documents used in this module. FUNCTIONS The following functions and keywords are exported by default: * Constructors for all Pandoc document element (block elements such as Para and inline elements such as Emph, metadata elements and the Document). * Type keywords such as Decimal and LowerAlpha to be used as types in other document elements. * The following helper functions pandoc_json, pandoc_version, attributes, metadata, citation, and element. pandoc_json $json Parse a JSON string, as emitted by pandoc in JSON format. This is the reverse to method to_json but it can read both old (before Pandoc 1.16) and new format. attributes { key => $value, ... } Maps a hash reference or instance of Hash::MultiValue into the internal structure of Pandoc attributes. The special keys id (string), and class (string or array reference with space-separated class names) are recognized. See attribute methods for details. citation { ... } A citation as part of document element Cite must be a hash reference with fields citationId (string), citationPrefix (list of inline elements) citationSuffix (list of inline elements), citationMode (one of NormalCitation, AuthorInText, SuppressAuthor), citationNoteNum (integer), and citationHash (integer). The helper method citation can be used to construct such a hash by filling in default values and optionally using shorter field names (id, prefix, suffix, mode, note, and hash): citation { id => 'foo', prefix => [ Str "see" ], suffix => [ Str "p.", Space, Str "42" ] } # in Pandoc Markdown [see @foo p. 42] The values returned by this function, as well as any citations contained in document objects returned by pandoc_json, are blessed hashrefs with getter/setter accessors corresponding to both the full and short field names, so that e.g. $citation->citationId(...) and $citation->id(...) get or set the same value. pandoc_version( [ $document ] ) Return a Pandoc::Version object with expected version number of pandoc executable to be used for serializing documents with to_json. If a Document element is given as argument, the minimal pandoc release version compatible with its api version is returned. Without argument, package variable $PANDOC_VERSION is checked for a preferred pandoc release. By default this variable is set from an environment variable of same name. If no preferred pandoc release has been specified, the function returns version 1.18 because this is the first pandoc release compatible with most recent api version supported by this module. See also method version of module Pandoc to get the current version of pandoc executable on your system. element( $name => $content ) Create a Pandoc document element of arbitrary name. This function is only exported on request. ELEMENTS AND METHODS Document elements are encoded as Perl data structures equivalent to the JSON structure, emitted with pandoc output format json. This JSON structure is subject to minor changes between versions of pandoc. All elements are blessed objects that provide common element methods (all elements), attribute methods (elements with attributes), and additional element-specific methods. COMMON METHODS to_json Return the element as JSON encoded string. The following are equivalent: $element->to_json; JSON->new->utf8->canonical->convert_blessed->encode($element); The serialization format can be adjusted to different pandoc versions with module and environment variable PANDOC_VERSION or with Document element properties api_version and pandoc_version. When writing filters you can normally just rely on the api version value obtained from pandoc, since pandoc expects to receive the same JSON format as it emits. name Return the name of the element, e.g. "Para" for a paragraph element. content Return the element content. For most elements (Para, Emph, Str...) the content is an array reference with child elements. Other elements consist of multiple parts; for instance the Link element has attributes (attr, id, class, classes, keyvals) a link text (content) and a link target (target) with url and title. is_block True if the element is a Block element is_inline True if the element is an inline Inline element is_meta True if the element is a Metadata element is_document True if the element is a Document element as_block Return the element unmodified if it is a block element or wrapped in a Plain or Div otherwise. match( $selector ) Check whether the element matches a given Pandoc::Selector (given as instance or string). walk(...) Walk the element tree with Pandoc::Walker query(...) Query the element to extract results with Pandoc::Walker transform(...) Transform the element tree with Pandoc::Walker string Returns a concatenated string of element content, leaving out all formatting. ATTRIBUTE METHODS Some elements have attributes which can be an identifier, ordered class names and ordered key-value pairs. Elements with attributes provide the following methods: attr Get or set the attributes in Pandoc internal structure: [ $id, [ @classes ], [ [ key => $value ], ... ] ] See helper function attributes to create this structure. keyvals Get all attributes (id, class, and key-value pairs) as new Hash::MultiValue instance, or replace all key-value pairs plus id and/or class if these are included as field names. All class fields are split by whitespaces. $e->keyvals # return new Hash::MultiValue $e->keyvals( $HashMultiValue ) # update by instance of Hash::MultiValue $e->keyvals( key => $value, ... ) # update by list of key-value pairs $e->keyvals( \%hash ) # update by hash reference $e->keyvals( { } ) # remove all key-value pairs $e->keyvals( id => '', class => '' ) # remove all key-value pairs, id, class id Get or set the identifier. See also Pandoc::Filter::HeaderIdentifiers for utility functions to handle Header identifiers. class Get or set the list of classes, separated by whitespace. add_attribute( $name => $value ) Append an attribute. The special attribute names id and class set or append identifier or class, respectively. DOCUMENT ELEMENT Document Root element, consisting of metadata hash (meta), document element array (content=blocks) and optional api_version. The constructor accepts either two arguments and an optional named parameter api_version: Document { %meta }, [ @blocks ], api_version => $version_string or a hash with three fields for metadata, document content, and an optional pandoc API version: { meta => { %metadata }, blocks => [ @content ], pandoc-api-version => [ $major, $minor, $revision ] } The latter form is used as pandoc JSON format since pandoc release 1.18. If no api version is given, it will be set 1.17 which was also introduced with pandoc release 1.18. A third ("old") form is accepted for compatibility with pandoc JSON format before release 1.18 and since release 1.12.1: an array with two elements for metadata and document content respectively. [ { unMeta => { %meta } }, [ @blocks ] ] The api version is set to 1.16 in this case, but older versions down to 1.12.3 used the same format. Document elements provide the following special methods in addition to common element methods: api_version( [ $api_version ] ) Return the pandoc-types version (aka "pandoc-api-version") of this document as Pandoc::Version object or sets it to a new value. This version determines how method to_json serializes the document. See "PANDOC VERSIONS" for details. pandoc_version( [ $pandoc_version ] ) Return the minimum required version of pandoc executable compatible with the api_version of this document. The following are equivalent: $doc->pandoc_version; pandoc_version( $doc ); If used as setter, sets the api version of this document to be compatible with the given pandoc version. content or blocks Get or set the array of block elements of the document. meta( [ $metadata ] ) Get and/or set combined document metadata. Use method value to get selected metadata fields and values. value( [ $pointer ] [ %options ] ) Get selected document metadata field value(s). See Pandoc::Metadata for documentation. Can also be called as metavalue, so the following are equivalent: $doc->value( ... ); $doc->meta->value( ... ); $doc->metavalue( ... ); to_pandoc( [ [ $pandoc, ] @arguments ]) Process the document with Pandoc executable and return its output: $doc->to_pandoc( -o => 'doc.html' ); my $markdown = $doc->to_pandoc( -t => 'markdown' ); The first argument can optionally be an instance of Pandoc to use a specific executable. to_...( [ @arguments ] ) Process the document into markdown (pandoc's extended Markdown), latex (LaTeX), html (HTML), rst (reStructuredText), or plain (plain text). The following are equivalent: $doc->to_markdown( @args ); $doc->to_pandoc( @args, '-t' => 'markdown' ); outline( [ $depth ] ) Returns an outline of the document structure based on Header elements. The outline is a hierarchical hash reference with the following fields: header Header element (not included at the document root) blocks List of block elements before the next Header element (of given depth or less if a maximum depth was given) sections List of subsections, each having the same outline structure. BLOCK ELEMENTS BlockQuote Block quote, consisting of a list of blocks (content) BlockQuote [ @blocks ] BulletList Unnumbered list of items (content=items), each a list of blocks BulletList [ [ @blocks ] ] CodeBlock Code block (literal string content) with attributes (attr, id, class, classes, keyvals) CodeBlock $attributes, $content DefinitionList Definition list, consisting of a list of pairs (content=items), each a term (term, a list of inlines) and one or more definitions (definitions, a list of blocks). DefinitionList [ @definitions ] # each item in @definitions being a pair of the form [ [ @inlines ], [ @blocks ] ] Div Generic container of blocks (content) with attributes (attr, id, class, classes, keyvals). Div $attributes, [ @blocks ] Header Header with level (integer), attributes (attr, id, class, classes, keyvals), and text (content, a list of inlines). Header $level, $attributes, [ @inlines ] HorizontalRule Horizontal rule HorizontalRule LineBlock List of lines (content), each a list of inlines. LineBlock [ @lines ] This element was added in pandoc 1.18. Before it was represented Para elements with embedded LineBreak elements. This old serialization form can be enabled by setting $PANDOC_VERSION package variable to a lower version number. Null Nothing Null OrderedList Numbered list of items (content=items), each a list of blocks), preceded by list attributes (start number, numbering style, and delimiter). OrderedList [ $start, $style, $delim ], [ [ @blocks ] ] Supported styles are DefaultStyle, Example, Decimal, LowerRoman, UpperRoman, LowerAlpha, and UpperAlpha. Supported delimiters are DefaultDelim, Period, OneParen, and TwoParens. Para Paragraph, consisting of a list of Inline elements (content). Para [ $elements ] Plain Plain text, not a paragraph, consisting of a list of Inline elements (content). Plain [ @inlines ] RawBlock Raw block with format and content string. RawBlock $format, $content Table Table, with caption, column alignments, relative column widths (0 = default), column headers (each a list of blocks), and rows (each a list of lists of blocks). Table [ @inlines ], [ @alignments ], [ @width ], [ @headers ], [ @rows ] Possible alignments are AlignLeft, AlignRight, AlignCenter, and AlignDefault. An example: Table [Str "Example"], [AlignLeft,AlignRight], [0.0,0.0], [[Plain [Str "name"]] ,[Plain [Str "number"]]], [[[Plain [Str "Alice"]] ,[Plain [Str "42"]]] ,[[Plain [Str "Bob"]] ,[Plain [Str "23"]]]]; INLINE ELEMENTS Cite Citation, a list of citations and a list of inlines (content). See helper function citation to construct citations. Cite [ @citations ], [ @inlines ] Code Inline code, a literal string (content) with attributes (attr, id, class, classes, keyvals) Code attributes { %attr }, $content Emph Emphasized text, a list of inlines (content). Emph [ @inlines ] Image Image with alt text (content, a list of inlines) and target (list of url and title) with attributes (attr, id, class, classes, keyvals). Image attributes { %attr }, [ @inlines ], [ $url, $title ] Serializing the attributes is disabled in api version less then 1.16. LineBreak Hard line break LineBreak Link Hyperlink with link text (content, a list of inlines) and target (list of url and title) with attributes (attr, id, class, classes, keyvals). Link attributes { %attr }, [ @inlines ], [ $url, $title ] Serializing the attributes is disabled in api version less then 1.16. Math TeX math, given as literal string (content) with type (one of DisplayMath and InlineMath). Math $type, $content Note Footnote or Endnote, a list of blocks (content). Note [ @blocks ] Quoted Quoted text with quote type (one of SingleQuote and DoubleQuote) and a list of inlines (content). Quoted $type, [ @inlines ] RawInline Raw inline with format (a string) and content (a string). RawInline $format, $content SmallCaps Small caps text, a list of inlines (content). SmallCaps [ @inlines ] SoftBreak Soft line break SoftBreak This element was added in pandoc 1.16 as a matter of editing convenience to preserve line breaks (as opposed to paragraph breaks) from input source to output. If you are going to feed a document containing SoftBreak elements to Pandoc < 1.16 you will have to set the package variable or environment variable PANDOC_VERSION to 1.15 or below. Space Inter-word space Space Span Generic container of inlines (content) with attributes (attr, id, class, classes, keyvals). Span attributes { %attr }, [ @inlines ] Str Plain text, a string (content). Str $content Strikeout Strikeout text, a list of inlines (content). Strikeout [ @inlines ] Strong Strongly emphasized text, a list of inlines (content). Strong [ @inlines ] Subscript Subscripted text, a list of inlines (content). Supscript [ @inlines ] Superscript Superscripted text, a list of inlines (content). Superscript [ @inlines ] METADATA ELEMENTS See Pandoc::Metadata for documentation of metadata elements MetaBool, MetaString, MetaMap, MetaInlines, MetaList, and MetaBlocks. Helper function metadata can be used to convert scalars, hash references, array references, and Pandoc Inline/Block elements into metadata elements. TYPE KEYWORDS The following document elements are only as used as type keywords in other document elements: * SingleQuote, DoubleQuote * DisplayMath, InlineMath * AuthorInText, SuppressAuthor, NormalCitation * AlignLeft, AlignRight, AlignCenter, AlignDefault * DefaultStyle, Example, Decimal, LowerRoman, UpperRoman, LowerAlpha, UpperAlpha * DefaultDelim, Period, OneParen, TwoParens SEE ALSO Perl module Pandoc implements a wrapper around the pandoc executable. Similar libraries in other programming languages are listed at https://github.com/jgm/pandoc/wiki/Pandoc-wrappers-and-interfaces. AUTHOR Jakob Voß CONTRIBUTORS Benct Philip Jonsson TakeAsk COPYRIGHT AND LICENSE Copyright 2014- Jakob Voß GNU General Public License, Version 2 This module is heavily based on Pandoc by John MacFarlane. Changes100644001750001750 1316213347276615 14616 0ustar00vojvoj000000000000Pandoc-Elements-0.38Revision history for Pandoc-Elements 0.38 2018-09-15 23:45:46 CEST - Introduce Citation object with accessors 0.37 2018-05-12 22:42:29 CEST - Let multifilter find filter directory also on Windows - Support fully compliant JSON Pointers in metavalues 0.36 2018-04-24 22:08:31 CEST - Extend ImageFromCode filter (#83) - Introduce Pandoc::Selector by refactoring - Add select filter - Remove deprecated function stringify 0.35 2018-04-20 13:07:19 CEST - Fix test failures (#77, #78) - Fix, extend and document ImageFromCode filter (#79) 0.34 2018-04-18 09:46:41 CEST - Extend metadata value method with JSON Pointer and options (#73) - Change default stringification of MetaBlocks - Fixes provided by Benct Philip Jonsson and TakeAsh (thanks!) - Remove internal module Pandoc::Filter::Usage 0.33 2017-02-13 10:57:59 CET - Extend and document document metadata handling (#10) - Fix $document->to_pandoc and friends with first Pandoc argument 0.32 2017-02-01 16:15:21 CET - Deprecate Pandoc::Filter::Usage and remove circular dependency 0.31 2017-02-01 15:52:47 CET - Remove deprecated script pandocwalk - Remove module Pandoc::Filter::Lazy 0.30 2017-01-31 21:23:11 CET - Fix and extend method to_pandoc - Extend document method metavalues 0.29 2017-01-25 12:10:07 CET - Add document methods: to_pandoc, to_markdown, ... (#48) - Add document methods: outline - Make Link/Image methods url/title also setters (#54) - Let pod2pandoc include package name as title - Fix metavalue for MetaBlocks 0.28 2016-11-29 06:49:57 CET - Fix pod2pandoc - Extend selection of serialization format (pandoc_version/api_version) 0.27 2016-11-21 19:36:29 CET - Update internal Document structure and default to Pandoc 1.18 - Extend testing 0.26 2016-11-11 10:49:22 CET - Extend Pod::Simple::Pandoc - Add Pandoc::Filter::HeaderIdentifiers - Mark pandocwalk and Pandoc::Filter::Lazy as deprecated 0.25 2016-10-11 21:32:00 CEST - Improve pod2pandoc script - Rename Pandoc::Filter::Usage::frompod to ::pod2usage - Add example filter: section - use new CPAN module Pandoc 0.24 2016-10-06 14:17:31 CEST - Rewrite and rename pandoc-filters to multifilter 0.23 2016-09-30 22:35:22 CEST - Add Pandoc::Filter::Usage and option --about for filter documentation - Extend pandoc-filters to support future Pandoc filters directory - Make most getters also setters 0.22 2016-09-22 12:03:38 CEST - Add pandoc-filters script to run filters specified in document metadata - Let pandoc_walk/pandoc_filter not filter metadata fields - Add metavars example 0.21 2016-09-19 22:05:43 CEST - extend method 'keyvals' as setter - document and extend metadata elements by method 'metavalue' - make content method an optional setter (not documented yet) - let to_json return canonical JSON 0.20 2016-09-04 14:34:05 CEST - Revert extended class selector, implement setter for id/class/keyvals instead - Add graphviz example 0.19 2016-09-03 09:42:34 CEST - Extend class selector to test existence of given class - Extend attributes with Hash::MultiValue. - Drop support of special key 'classes' in attributes helper function 0.18 2016-04-06 13:23:35 CEST - Fix and extend attributes function (#29/#26/#14) - Document and test removal of SoftBreak element - fix json serialization to ensure right scalar types (#27) 0.17 2016-03-07 21:15:58 CET - Support stringification of meta elements - Add SoftBreak inline element, introduced in Pandoc 1.16 0.16 2016-02-23 20:16:52 CET - Support new (Pandoc 1.16) document model with Link and Image attributes (issue #11) - Fix blessing metadata top level values 0.15 2015-12-14 10:12:50 CET - fix Pod::Simple::Pandoc for old Pod::Simple - allow more lazy filter scripting - add example to remove unnumbered sections 0.14 2015-12-11 14:11:51 CET - refactor and introduce Pandoc::Filter::Lazy 0.13 2015-12-09 12:43:50 CET - fix passing of output format - add method match (experimental) - added examples myemph.pl and theorem.pl 0.12 2015-12-08 13:55:43 CET - added pod2pandoc script and Pod::Simple::Pandoc - added string as method to replace function stringify - fixed nasty bug in Pandoc::Element constructor reuse 0.11 2015-11-30 13:47:17 CET - UTF-8 output with pandoc_walk and pandoc_filter - include tests of pandoc-walk 0.10 2015-11-26 22:07:39 CET - added utility script pandoc-walk - new method: pandoc_walk - provide special variable $_ to action functions 0.09 2015-11-22 20:40:49 CET - support definition of filters as hash 0.08 2015-09-24 11:10:54 CEST - new helper function: citation 0.07 2015-09-22 15:39:49 CEST - extend documentation and examples 0.06 2015-01-19 12:58:09 CET - fix endless recursion bug (issue #7) - add walker methods to documente elements (issue #4) - simplify access to attributes (issue #8, not documented yet) - rename and document function pandoc_json - extend documentation 0.05 2014-12-27 15:45:38 CET - fixed filter bug (issue #5) - added examples - added more accessor methods - remove method value 0.04 2014-10-27 14:09:21 CET - added accessor methods (issue #1) - refactoring 0.03 2014-10-26 20:52:58 CET - use blessed objects - new methods to_json and from_json - added Pandoc::Filter - changed calling syntax of Pandoc::Walker 0.02 2014-10-26 10:34:37 CET - added Pandoc::Walker - new helper method: element 0.01 2014-10-23 21:34:25 CEST - initial release t000755001750001750 013347276615 13403 5ustar00vojvoj000000000000Pandoc-Elements-0.38ast.t100644001750001750 134113347276615 14516 0ustar00vojvoj000000000000Pandoc-Elements-0.38/tuse strict; use Test::More; use Pandoc::Elements; my $doc = Document { title => MetaInlines [ Str 'test' ] }, [ Para [ Str 'test' ] ]; ok $doc->is_document, 'is_document'; is $doc->name, 'Document', 'name'; is_deeply $doc->content, [ Para [ Str 'test' ] ]; ok !$doc->is_block, 'is_block'; ok !$doc->is_inline, 'is_inline'; ok !$doc->is_meta, 'is_meta'; my $meta=$doc->meta; ok $meta, '->meta'; ok $meta->{title}->is_meta, 'is_meta'; is $meta->{title}->name, 'MetaInlines', 'name'; my $para = $doc->{blocks}->[0]; is $para->name, 'Para', 'name'; is_deeply $para->content, [ Str 'test' ]; ok $para->is_block, 'is_block'; ok !$para->is_document, '!is_document'; $para->null; is $para->name, 'Null', 'null'; done_testing; LICENSE100644001750001750 4352513347276615 14336 0ustar00vojvoj000000000000Pandoc-Elements-0.38This software is Copyright (c) 2014- by Jakob Voß . This is free software, licensed under: The GNU General Public License, Version 2, June 1991 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. cpanfile100644001750001750 73313347276615 14767 0ustar00vojvoj000000000000Pandoc-Elements-0.38requires 'perl', '5.010001'; # core modules requires 'Pod::Simple', '3.08'; requires 'List::Util'; requires 'Scalar::Util'; requires 'Pod::Usage'; # additional modules requires 'JSON'; requires 'JSON::PP'; requires 'Hash::MultiValue', '0.06'; requires 'Pandoc', '0.8.3'; requires 'IPC::Run3'; # also implied by Pandoc module on test => sub { requires 'Test::More', '0.96'; requires 'Test::Output'; requires 'Test::Exception'; requires 'Test::Warnings'; }; dist.ini100644001750001750 13213347276615 14720 0ustar00vojvoj000000000000Pandoc-Elements-0.38author=Jakob Voß [@Milla] [PruneFiles] filename=examples/Makefile match=^examples/.*\.md Build.PL100644001750001750 26513347276615 14557 0ustar00vojvoj000000000000Pandoc-Elements-0.38# This Build.PL for Pandoc-Elements was generated by Dist::Zilla::Plugin::ModuleBuildTiny 0.010. use strict; use warnings; use 5.010001; use Module::Build::Tiny 0.039; Build_PL(); META.yml100644001750001750 213013347276615 14545 0ustar00vojvoj000000000000Pandoc-Elements-0.38--- abstract: 'create and process Pandoc documents' author: - 'Jakob Voß' build_requires: Test::Exception: '0' Test::More: '0.96' Test::Output: '0' Test::Warnings: '0' configure_requires: Module::Build::Tiny: '0.039' dynamic_config: 0 generated_by: 'Dist::Zilla version 5.036, Dist::Milla version v1.0.15, CPAN::Meta::Converter version 2.150001' license: gpl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: '1.4' name: Pandoc-Elements no_index: directory: - t - xt - inc - share - eg - examples requires: Hash::MultiValue: '0.06' IPC::Run3: '0' JSON: '0' JSON::PP: '0' List::Util: '0' Pandoc: v0.8.3 Pod::Simple: '3.08' Pod::Usage: '0' Scalar::Util: '0' perl: '5.010001' resources: bugtracker: https://github.com/nichtich/Pandoc-Elements/issues homepage: https://github.com/nichtich/Pandoc-Elements repository: https://github.com/nichtich/Pandoc-Elements.git version: '0.38' x_contributors: - 'Benct Philip Jonsson ' - 'Jakob Voß ' - 'TakeAsh ' MANIFEST100644001750001750 302513347276615 14431 0ustar00vojvoj000000000000Pandoc-Elements-0.38# This file was automatically generated by Dist::Zilla::Plugin::Manifest v5.036. Build.PL Changes LICENSE MANIFEST META.json META.yml README cpanfile dist.ini examples/caps.pl examples/comments.pl examples/deemph.pl examples/deflist.pl examples/ditaa.pl examples/graphviz.pl examples/metavars.pl examples/myemph.pl examples/qids.pl examples/remove-unnumbered-sections.pl examples/section.pl examples/select.pl examples/theorem.pl lib/Pandoc/Document/Element.pm lib/Pandoc/Elements.pm lib/Pandoc/Filter.pm lib/Pandoc/Filter/HeaderIdentifiers.pm lib/Pandoc/Filter/ImagesFromCode.pm lib/Pandoc/Filter/Multifilter.pm lib/Pandoc/Metadata.pm lib/Pandoc/Selector.pm lib/Pandoc/Walker.pm script/multifilter t/Filter-ImagesFromCode.t t/accessors.t t/ast.t t/attributes.t t/citation.t t/document-pandoc-version.t t/document.t t/documents/example.json t/documents/example.md t/documents/link-image-attributes.json t/documents/link-image-oldstyle.json t/documents/meta.json t/documents/outline.md t/elements.t t/example.md t/example.tex t/examples/deemph.in.md t/examples/deemph.out.md t/filter.t t/header-identifiers.t t/invalid-version-from-env.t t/lineblock.t t/lineblocks-empty-lines.t t/link-image-attributes.t t/linkage-setters.t t/meta-blessing.t t/meta-filter.t t/metadata.t t/multifilter.t t/outline t/outline.t t/pandoc-metadata.t t/pandoc-version.t t/pandoc/filters/caps t/pandoc/filters/empty.pl t/pandoc_filter.t t/pointer.t t/release-pod-syntax.t t/scalar-types.t t/selector.t t/softbreak.t t/stringify.t t/synopsis.t t/to_pandoc.t t/walker.t xt/Makefile outline100755001750001750 25113347276615 15126 0ustar00vojvoj000000000000Pandoc-Elements-0.38/t#!/usr/bin/env perl use strict; use 5.010; use lib 'lib'; use Pandoc::Elements; use Pandoc::Filter; pandoc_walk( Header => sub{ say " " x ($_->level-1), $_->string } ); META.json100644001750001750 375213347276615 14730 0ustar00vojvoj000000000000Pandoc-Elements-0.38{ "abstract" : "create and process Pandoc documents", "author" : [ "Jakob Voß" ], "dynamic_config" : 0, "generated_by" : "Dist::Zilla version 5.036, Dist::Milla version v1.0.15, CPAN::Meta::Converter version 2.150001", "license" : [ "gpl_2" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : 2 }, "name" : "Pandoc-Elements", "no_index" : { "directory" : [ "t", "xt", "inc", "share", "eg", "examples" ] }, "prereqs" : { "configure" : { "requires" : { "Module::Build::Tiny" : "0.039" } }, "develop" : { "requires" : { "Dist::Milla" : "v1.0.15", "Test::Pod" : "1.41" } }, "runtime" : { "requires" : { "Hash::MultiValue" : "0.06", "IPC::Run3" : "0", "JSON" : "0", "JSON::PP" : "0", "List::Util" : "0", "Pandoc" : "v0.8.3", "Pod::Simple" : "3.08", "Pod::Usage" : "0", "Scalar::Util" : "0", "perl" : "5.010001" } }, "test" : { "requires" : { "Test::Exception" : "0", "Test::More" : "0.96", "Test::Output" : "0", "Test::Warnings" : "0" } } }, "release_status" : "stable", "resources" : { "bugtracker" : { "web" : "https://github.com/nichtich/Pandoc-Elements/issues" }, "homepage" : "https://github.com/nichtich/Pandoc-Elements", "repository" : { "type" : "git", "url" : "https://github.com/nichtich/Pandoc-Elements.git", "web" : "https://github.com/nichtich/Pandoc-Elements" } }, "version" : "0.38", "x_contributors" : [ "Benct Philip Jonsson ", "Jakob Voß ", "TakeAsh " ] } filter.t100644001750001750 250413347276615 15216 0ustar00vojvoj000000000000Pandoc-Elements-0.38/tuse strict; use 5.010; use Test::More; use Pandoc::Filter; use Pandoc::Elements; # action function my $action = sub { return unless $_[0]->name eq 'Header' and $_[0]->level >= 2; Para [ Emph $_[0]->content ]; }; my $h1 = Header(1, attributes {}, [ Str 'hello']); my $h2 = Header(2, attributes {}, [ Str 'hello']); is $action->($h1), undef, 'action'; is_deeply $action->($h2), Para [ Emph [ Str 'hello' ] ], 'action'; { my $doc = Document {}, [ $h1, $h2 ]; Pandoc::Filter->new($action)->apply($doc); is_deeply $doc->content->[1], Para [ Emph [ Str 'hello' ] ], 'apply'; } { my $doc = Document { title => MetaInlines [ Str 'test' ] }, [ $h1, $h2 ]; Pandoc::Filter->new( Header => sub { Para [ Str $_[1] . ':' . $_[2]->{title}->string ] } )->apply($doc, 'html'); is_deeply $doc->content->[1], Para [ Str 'html:test' ], 'format and metadata'; } # TODO: should croak because 1 is no selector ( 1 => sub { } ) # eval { Pandoc::Filter->new( 1 ) }; ok $@, 'invalid filter'; my $doc = Document {}, [ Str "hello" ]; my $filter = Pandoc::Filter->new(sub { return if $_->name ne 'Str'; $_->{c} = uc $_->{c}; return [ $_, Str " world!" ]; }); $filter->apply($doc); is_deeply $doc->content, [ Str('HELLO'), Str(' world!') ], "don't filter injected elements"; done_testing; walker.t100644001750001750 414413347276615 15220 0ustar00vojvoj000000000000Pandoc-Elements-0.38/tuse strict; use Test::More; use Pandoc::Walker; use Pandoc::Filter; use Pandoc::Elements qw(Str Space pandoc_json); sub load { local (@ARGV, $/) = ('t/documents/example.json'); pandoc_json(<>); } my $doc = load(); my $LINKS = [qw( http://example.org/ image.png http://example.com/ )]; sub urls { return unless ($_->name eq 'Link' or $_->name eq 'Image'); return $_->target->[0]; }; my $links = query $doc, \&urls; is_deeply $links, $LINKS, 'query( action )'; is_deeply $doc->query(\&urls), $LINKS, '->query'; $links = query $doc, 'Link|Image' => sub { $_->target->[0] }; is_deeply $links, $LINKS, 'query( name => action )'; sub links { return unless ($_->name eq 'Link' or $_->name eq 'Image'); push @$links, $_->url; } { $links = [ ]; walk $doc, \&links; is_deeply $links, $LINKS, 'walk(sub)'; } { $links = [ ]; $doc->walk(\&links); is_deeply $links, $LINKS, '->walk'; } { $links = [ ]; walk $doc, Pandoc::Filter->new(\&links); is_deeply $links, $LINKS, 'walk(Filter)'; } transform $doc, sub { return ($_->name eq 'Link' ? [] : ()); }; is_deeply query($doc,\&urls), ['image.png'], 'transform, remove elements'; sub escape_links { my ($e) = @_; return unless $e->name eq 'Link'; my $a = [ Str "<", @{$e->content}, Str ">" ]; return $a; } $doc = load(); transform $doc, \&escape_links; is scalar @{ query($doc, \&urls) }, 1, 'transform, escaped links'; $doc = load(); $doc->transform(\&escape_links); is scalar @{ query($doc, \&urls) }, 1, '->transform, escaped links'; my $header = $doc->content->[0]->content; is_deeply $header, [ Str 'Example', Space, Str '<', Str 'http://example.org/', Str '>', Str '!' ], 'transform, multiple elements'; $doc = load(); transform $doc, sub { my $e = shift; return unless $e->name eq 'Header'; $e->transform(\&escape_links); }; is scalar @{ query($doc, \&urls) }, 2, 'nested transformation'; #SKIP: { # $header = $doc->content->[0]; # $header->transform(sub { # return unless $_[0]->name eq 'Header'; # return Para $_[0]->[0]->content; # }); #} done_testing; outline.t100644001750001750 305713347276615 15414 0ustar00vojvoj000000000000Pandoc-Elements-0.38/tuse strict; use 5.010; use Test::More; use Pandoc::Elements; use Pandoc; plan skip_all => 'pandoc >= 1.12.1 not available' unless (pandoc and pandoc->version > '1.12.1'); my $doc = pandoc->file('t/documents/outline.md'); my $outline = $doc->outline; sub simplify { my $o = shift; $o->{header} //= Header 0, {}, [ Str '' ]; [ ('#' x $o->{header}->level . ' ' . $o->{header}->string), join(' / ', map { $_->string } @{$o->{blocks}}), [ map { simplify($_) } @{$o->{sections}} ] ] } is_deeply simplify($doc->outline), [ ' ', 'test document', [ [ '## section 0.1', '', [ [ '### section 0.1.1', '', [] ] ] ], [ '# chapter 1', 'with / content', [] ], [ '# chapter 2', '', [ [ '## section 2.1', '', [] ], [ '## section 2.2', 'text', [ [ '#### subsubsection 2.2.1.1.1', '', [] ], [ '### subsubsection 2.2.2', '', [] ] ] ] ] ], [ '# chapter 3', 'header in table', [] ], [ '# chapter 4', '', [] ] ] ], 'outline()'; is_deeply simplify($doc->outline(2)), [ ' ', 'test document', [ [ '## section 0.1', 'section 0.1.1', [] ], [ '# chapter 1', 'with / content', [] ], [ '# chapter 2', '', [ [ '## section 2.1', '', [] ], [ '## section 2.2', 'text / subsubsection 2.2.1.1.1 / subsubsection 2.2.2', [] ] ] ], [ '# chapter 3', 'header in table', [] ], [ '# chapter 4', '', [] ] ] ], 'outline(2)'; done_testing; pointer.t100644001750001750 1060413347276615 15431 0ustar00vojvoj000000000000Pandoc-Elements-0.38/tuse 5.010001; use strict; use warnings; use Test::More 0.96; use Test::Exception; use Pandoc::Elements; # Make sure examples from RFC 6901 sec 5 work as metadata my $doc = pandoc_json(<<'JSON'); [ { "unMeta": { "":{"c":"0","t":"MetaString"}, " ":{"c":"7","t":"MetaString"}, "a/b":{"c":"1","t":"MetaString"}, "c%d":{"c":"2","t":"MetaString"}, "e^f":{"c":"3","t":"MetaString"}, "foo":{"c":[ {"c":[{"c":"bar","t":"Str"}],"t":"MetaInlines"}, {"c":[{"c":"baz","t":"Str"}],"t":"MetaInlines"} ],"t":"MetaList"}, "g|h":{"c":"4","t":"MetaString"}, "i\\j":{"c":"5","t":"MetaString"}, "k\"l":{"c":"6","t":"MetaString"}, "m~n":{"c":"8","t":"MetaString"} } }, [] ] JSON my @tests = ( [ 'RFC 6901' => [ [ "" => $doc->value ], [ "/foo" => [ "bar", "baz" ] ], [ "/foo/0" => "bar" ], [ "/" => 0 ], [ "/a~1b" => 1 ], [ "/c%d" => 2 ], [ "/e^f" => 3 ], [ "/g|h" => 4 ], [ "/i\\j" => 5 ], [ "/k\"l" => 6 ], [ "/ " => 7 ], [ "/m~0n" => 8 ], ], ], # If the 'pointer' string does not start with a forward # slash or is empty the whole string is a plain key. [ 'plain-key' => [ [ "foo" => [ "bar", "baz" ] ], [ "foo/0" => undef ], [ "a/b" => 1 ], [ "c%d" => 2 ], [ "e^f" => 3 ], [ "g|h" => 4 ], [ "i\\j" => 5 ], [ "k\"l" => 6 ], [ " " => 7 ], [ "m~n" => 8 ], ], ], ); for my $test ( @tests ) { my($name, $subtests) = @$test; subtest $name => sub { for my $subtest ( @$subtests ) { my ( $pointer, $expected ) = @$subtest; my $value = $doc->value( $pointer ); is_deeply $value, $expected, "'$pointer'" or note explain { got => $value, expected => $expected }; next unless defined $expected; lives_ok { $doc->value( $pointer, strict => 1 ) } "'$pointer' strict"; } }; } subtest strict => sub { my @tests = ( [ '/foo/2' => qr{\QList index 2 out of range in (sub)pointer "/2" in pointer "/foo/2"\E} ], [ '/foo/bar' => qr{\QNode "/bar" not a valid list index in (sub)pointer "/bar" in pointer "/foo/bar"\E} ], [ '/quux' => qr{\QNode "/quux" doesn't correspond to any key in (sub)pointer "/quux" in pointer "/quux"\E} ], [ 'quux' => qr{\QNode "quux" doesn't correspond to any key in (sub)pointer "quux" in pointer "quux"\E} ], [ '/e^f/g/h' => qr{\QNo list or mapping "/g" in (sub)pointer "/g/h" in pointer "/e^f/g/h"\E} ], ); for my $test ( @tests ) { my ( $pointer, $regex ) = @$test; throws_ok { $doc->value( $pointer, strict => 1 ) } $regex, "'$pointer' throws"; # # For Pandoc::Metadata::Error # my $exception = $@; # isa_ok $exception, 'Pandoc::Metadata::Error', "'$pointer' exception"; # is $exception->{pointer}, $pointer, "'$pointer' pointer"; # note explain $exception->data; } }; subtest indices => sub { my @list = map {; MetaString $_ } 0 .. 122; my %meta = ( long_list => MetaList \@list ); my $doc = Document [ { unMeta => \%meta }, [] ]; my @range = 90 .. 112; my @returns = map {; $doc->value("/long_list/$_") } @range; is scalar(@returns), 23, 'return list length' or note scalar @returns; is_deeply [ @returns ], [ @range ], 'correct return values'; }; done_testing; __END__ --- { "foo": ["bar", "baz"], "": 0, "a/b": 1, "c%d": 2, "e^f": 3, "g|h": 4, "i\\j": 5, "k\"l": 6, " ": 7, "m~n": 8 } The following JSON strings evaluate to the accompanying values: "" // the whole document "/foo" ["bar", "baz"] "/foo/0" "bar" "/" 0 "/a~1b" 1 "/c%d" 2 "/e^f" 3 "/g|h" 4 "/i\\j" 5 "/k\"l" 6 "/ " 7 "/m~0n" 8 my $doc = pandoc->parse( markdown => <<'END_OF_MD', '--standalone' ); --- foo: - bar - baz '': 0 a/b: 1 c%d: 2 e^f: 3 g|h: 4 i\j: 5 k"l: 6 ' ': 7 m~n: 8 ... END_OF_MD say $doc->meta->to_json; xt000755001750001750 013347276615 13573 5ustar00vojvoj000000000000Pandoc-Elements-0.38Makefile100644001750001750 35213347276615 15353 0ustar00vojvoj000000000000Pandoc-Elements-0.38/xt# Usage: # $ make -f xt/Makefile PANDOC_BINDIR=~/.pandoc/bin test: for P in ${PANDOC_BINDIR}/pandoc-*; do\ RELEASE_TESTING=1 prove -lv -Pandoc=$$P t;\ done index.html: ../lib/Pandoc/Elements.pm pod2pandoc $< -s -S --toc -o $@ citation.t100644001750001750 430613347276615 15545 0ustar00vojvoj000000000000Pandoc-Elements-0.38/tuse strict; use Test::More 0.96; # 0.96 for subtests use Pandoc::Elements; use constant STRINGLIKE => 'Pandoc::Document::Citation::Test::Stringlike'; { package # no index Pandoc::Document::Citation::Test::Stringlike; use overload q[""] => sub { ${$_[0]} }, fallback => 1; sub new { my($class, $value) = @_; return bless \$value => $class; } } my @accessors = ( [ hash => "citationHash" ], [ id => "citationId" ], [ mode => "citationMode" ], [ num => "citationNoteNum" ], [ prefix => "citationPrefix" ], [ suffix => "citationSuffix" ], ); my @methods = qw[ new TO_JSON ], map {; @$_ } @accessors; my $c = citation { id => 'foo', prefix => [ Str "see" ], suffix => [ Str "p.", Space, Str "42" ] }; isa_ok $c, 'Pandoc::Document::Citation'; can_ok $c, @methods; is_deeply $c, { citationId => 'foo', citationHash => 1, citationMode => NormalCitation, citationNoteNum => 0, citationPrefix => [ Str "see" ], citationSuffix => [ Str "p.", Space, Str "42" ], }, 'structure'; subtest accessors => sub { for my $aliases ( @accessors ) { my($name, $key) = @$aliases; is_deeply $c->$name, $c->{$key}, $name; is_deeply $c->$key, $c->{$key}, $key; is_deeply $c->$key, $c->$name, "$key/$name"; } }; subtest id => sub { my $bar = STRINGLIKE->new('bar'); my $baz = STRINGLIKE->new('baz'); isa_ok $bar, STRINGLIKE, 'test object'; my $c = citation { id => $bar }; is $c->id, 'bar', 'initial value'; ok !ref($c->id), 'coercion through constructor'; $c->id($baz); is $c->id, 'baz', 'changed value'; ok !ref($c->id), 'coercion through setter'; }; my $doc = pandoc_json(<<'END_OF_JSON'); {"blocks":[{"t":"Para","c":[{"t":"Cite","c":[[{"citationSuffix":[],"citationNoteNum":0,"citationMode":{"t":"NormalCitation"},"citationPrefix":[],"citationId":"foo","citationHash":0}],[{"t":"Str","c":"[@foo]"}]]}]}],"pandoc-api-version":[1,17,5,1],"meta":{}} END_OF_JSON subtest 'blessed by document constructor' => sub { my $cites = $doc->query( Cite => sub { $_ } ); isa_ok eval { $cites->[0]->citations->[0] }, 'Pandoc::Document::Citation'; }; done_testing; document.t100644001750001750 1052213347276615 15566 0ustar00vojvoj000000000000Pandoc-Elements-0.38/tuse strict; use Test::More 0.96; # subtests use Test::Exception; use Pandoc::Elements; use JSON qw( decode_json ); use utf8; sub list2content { my @content = map { Str( $_ ), Space } @_; pop @content; # remove trailing space return \@content; } sub doc_meta() { { title => MetaInlines( [Plain [ Str 'A', SoftBreak, Str 'message' ] ] ) } } sub doc_blocks() { [ Header( 1, attributes {}, list2content qw[Hej Världen!] ), Para list2content qw[Hur mår du idag?] ] } my %data = ( 1.16 => [ 'meta, blocks, api_version' => [ doc_meta, doc_blocks, api_version => '1.16' ], '[ { unMeta => meta }, blocks' => [ [ { unMeta => doc_meta }, doc_blocks ] ], '{ meta =>, blocks =>, pandoc-api-version }' => [ { meta => doc_meta, blocks => doc_blocks, 'pandoc-api-version' => [ 1, 16 ], } ], ], 1.17 => [ 'meta, blocks' => [ doc_meta, doc_blocks, ], 'meta, blocks, api_version =>' => [ doc_meta, doc_blocks, api_version => '1.17', ], '{ meta =>, blocks => }' => [ { meta => doc_meta, blocks => doc_blocks } ], '{ meta =>, blocks =>, pandoc-api-version => }' => [ { meta => doc_meta, blocks => doc_blocks, 'pandoc-api-version' => [ 1, 17 ], } ], ], ); my %json = ( '1.17' => '{"blocks":[{"c":[1,["",[],[]],[{"c":"Hej","t":"Str"},{"c":[],"t":"Space"},{"c":"V\u00e4rlden!","t":"Str"}]],"t":"Header"},{"c":[{"c":"Hur","t":"Str"},{"c":[],"t":"Space"},{"c":"m\u00e5r","t":"Str"},{"c":[],"t":"Space"},{"c":"du","t":"Str"},{"c":[],"t":"Space"},{"c":"idag?","t":"Str"}],"t":"Para"}],"meta":{"title":{"c":[{"c":[{"c":"A","t":"Str"},{"c":[],"t":"SoftBreak"},{"c":"message","t":"Str"}],"t":"Plain"}],"t":"MetaInlines"}},"pandoc-api-version":[1,17]}', '1.16' => '[{"unMeta":{"title":{"c":[{"c":[{"c":"A","t":"Str"},{"c":[],"t":"SoftBreak"},{"c":"message","t":"Str"}],"t":"Plain"}],"t":"MetaInlines"}}},[{"c":[1,["",[],[]],[{"c":"Hej","t":"Str"},{"c":[],"t":"Space"},{"c":"V\u00e4rlden!","t":"Str"}]],"t":"Header"},{"c":[{"c":"Hur","t":"Str"},{"c":[],"t":"Space"},{"c":"m\u00e5r","t":"Str"},{"c":[],"t":"Space"},{"c":"du","t":"Str"},{"c":[],"t":"Space"},{"c":"idag?","t":"Str"}],"t":"Para"}]]', '1.12.3' => '[{"unMeta":{"title":{"c":[{"c":[{"c":"A","t":"Str"},{"c":[],"t":"Space"},{"c":"message","t":"Str"}],"t":"Plain"}],"t":"MetaInlines"}}},[{"c":[1,["",[],[]],[{"c":"Hej","t":"Str"},{"c":[],"t":"Space"},{"c":"V\u00e4rlden!","t":"Str"}]],"t":"Header"},{"c":[{"c":"Hur","t":"Str"},{"c":[],"t":"Space"},{"c":"m\u00e5r","t":"Str"},{"c":[],"t":"Space"},{"c":"du","t":"Str"},{"c":[],"t":"Space"},{"c":"idag?","t":"Str"}],"t":"Para"}]]', ); foreach (keys %json) { $json{$_} = JSON->new->utf8->canonical->convert_blessed->encode( decode_json $json{$_} ); } # create a document and check whether it equals to expected result sub test_document(@) { my ($args, $expect, $json, $message) = @_; subtest $message => sub { my $doc = Document @$args; isa_ok $doc, 'Pandoc::Document', '$doc'; is_deeply $doc, $expect, 'expected'; is $doc->to_json, $json, 'to_json'; }; } foreach my $api_version ( qw[ 1.16 1.17 ] ) { subtest $api_version => sub { my $expect = pandoc_json $json{$api_version}; is $expect->api_version, $api_version, 'api_version'; my @variants = @{ $data{$api_version} }; while (@variants) { my ($name, $args) = splice @variants, 0, 2; test_document $args, $expect, $json{$api_version}, $name; } }; } subtest '1.12.3' => sub { my $expect = Document pandoc_json($json{1.16}); $expect->api_version('1.12.3'); my $args = [ doc_meta, doc_blocks, api_version => '1.12.3' ]; test_document $args, $expect, $json{'1.12.3'}, 'api_version = 1.12.3'; }; throws_ok { Document doc_meta, doc_blocks, api_version => '1.12.1' } qr{^api_version must be >= 1\.12\.3}, 'minimum api_version'; throws_ok { Document doc_meta, doc_blocks, '1.17.0.4' } qr{Document: too many or ambiguous arguments}, 'invalid arguments'; throws_ok { Document 'hello' } qr{expect array or hash reference}, 'invalid arguments'; done_testing; elements.t100644001750001750 216013347276615 15543 0ustar00vojvoj000000000000Pandoc-Elements-0.38/tuse strict; use Test::More; use Pandoc::Elements qw(Plain Emph Str attributes element); use JSON; is_deeply [ Str 'hello' ], [ { t => 'Str', c => 'hello' } ], 'Emph'; is_deeply [ Str 'hello', 'world' ], [ { t => 'Str', c => 'hello' }, 'world' ], 'Emph'; is_deeply [ Emph Str 'hello' ], [ { t => 'Emph', c => { t => 'Str', c => 'hello' } } ], 'Emph'; my $code = element( Code => attributes {}, 'x' ); is_deeply $code, { t => 'Code', c => [["",[],[]],"x"] }, 'element'; ok $code->is_inline, 'is_inline'; is_deeply $code->content, 'x', 'content'; eval { element ( Foo => 'bar' ) }; ok $@, 'unknown element'; eval { element ( Code => 'x' ) }; ok $@, 'wrong number of arguments'; is_deeply decode_json(Str('今日は')->to_json), { t => 'Str', c => '今日は' }, 'method to_json'; my $ast = element ( Header => 6, attributes { foo => 6 }, Str 6 ); is_deeply [ $ast->to_json =~ /(.6.)/g ], [ '[6,', '"6"', '"6"',], 'stringify numbers'; # as_block { is_deeply $ast->as_block, $ast, ':block->as_block'; is_deeply Str('x')->as_block, Plain([ Str 'x' ]), ':inline->as_block'; } done_testing; example.md100644001750001750 12713347276615 15500 0ustar00vojvoj000000000000Pandoc-Elements-0.38/t# Section with *ÄÖÜ* and [link](http://example.org/) ## Subsection with **äöü** metadata.t100644001750001750 712613347276615 15516 0ustar00vojvoj000000000000Pandoc-Elements-0.38/tuse strict; use Test::More 0.96; use Pandoc::Elements; use Scalar::Util qw[ blessed reftype ]; use JSON::PP; my $doc = pandoc_json(<meta->{true}->content, 'true'; ok !$doc->meta->{false}->content, 'false'; foreach (1, '1', 'true', 'TRUE', 42, 'wtf') { my $m = MetaBool($_); ok $m->content; is '{"c":true,"t":"MetaBool"}', $m->to_json, "true: $_"; } foreach (0, '', 'false', 'FALSE', undef) { my $m = MetaBool($_); ok !$m->content; is '{"c":false,"t":"MetaBool"}', $m->to_json, "false: $_"; } is_deeply $doc->value('/true', boolean => 'JSON::PP'), JSON::PP::true, 'JSON::PP::true'; is_deeply $doc->value('/false', boolean => 'JSON::PP'), JSON::PP::false, 'JSON::PP::false'; # MetaString is $doc->meta->{string}->content, "hello\nworld"; is $doc->meta->{string}->value, "hello\nworld"; # MetaInlines { my $m = MetaInlines [ Str "foo" ]; is '{"c":[{"c":"foo","t":"Str"}],"t":"MetaInlines"}', $m->to_json, 'MetaInlines'; is $m->string, 'foo', 'MetaInlines->string'; } # MetaBlocks { my $m = MetaBlocks [ Para [ Str "x" ], Para [ Str "y" ] ]; is $m->string, "x\n\ny", 'MetaBlocks->string'; } # [meta]value is_deeply $doc->value, { false => 0, true => 1, string => "hello\nworld", blocks => "x\n\ny", map => { string => "0", list => ["a", "b", 0], '/~' => 1 } }, 'value'; is $doc->value('false'), 0, 'value("false")'; is $doc->value('/false'), 0, 'value("/false")'; is $doc->value('true'), 1, 'value("true")'; is $doc->value('/true'), 1, 'value("/true")'; is $doc->value('/map/string'), "0", 'value("/map/string")'; is $doc->value('/map/list/0'), "a", 'value("/map/list/0")'; is $doc->value('/map/list/2'), "0", 'value("/map/list/2")'; is $doc->value('string'), "hello\nworld", 'value("string")'; is $doc->value('/string'), "hello\nworld", 'value("/string")'; is_deeply $doc->value('/map/~1~0', boolean => 'JSON::PP'), JSON::PP::true, 'value("/map/~1~0")'; is_deeply $doc->value('string', element => 'keep'), $doc->meta->{string}->content, 'value("string", elements => keep)'; is_deeply $doc->value('/string', element => 'keep'), $doc->meta->{string}->content, 'value("/string", elements => keep)'; is $doc->value('blocks'), "x\n\ny", 'value("blocks")'; is $doc->value('/blocks'), "x\n\ny", 'value("/blocks")'; is_deeply $doc->value('blocks', element => 'keep'), $doc->meta->{blocks}->content, 'value("blocks", elements => keep)'; is_deeply $doc->value('/blocks', element => 'keep'), $doc->meta->{blocks}->content, 'value("/blocks", elements => keep)'; foreach (qw(x map/x true/x blocks/x map/list/x map/list/3)) { is $doc->value($_), undef, "value('$_')"; is $doc->value($_), undef, "value('/$_')"; } my $doc = do { local (@ARGV, $/) = ('t/documents/meta.json'); pandoc_json(<>); }; is_deeply { map { $_ => $doc->metavalue($_) } keys %{$doc->meta} }, $doc->metavalue, 'Document->metavalue'; done_testing; selector.t100644001750001750 225013347276615 15547 0ustar00vojvoj000000000000Pandoc-Elements-0.38/tuse strict; use Test::More; use Pandoc::Elements; use Pandoc::Selector; # test matching on elements ok Str('')->match('Str'), 'match name'; ok !Str('')->match('Para'), 'no match'; ok Str('')->match('str'), 'case-insensitive'; ok Str('')->match(':inline'), 'type match'; ok !Str('')->match(':block'), 'type not match'; ok Str('')->match('str:inline'), 'multiple match'; ok Str('')->match('Foo|Str'), '| match'; ok !Str('')->match(Pandoc::Selector->new('#id')), 'no id match'; my $e = Code attributes { id => 'abc', class => ['f0_0','bar']} , ''; # test matching with selector ok(Pandoc::Selector->new('#abc')->match($e), 'id match'); ok(!Pandoc::Selector->new('#xyz')->match($e), 'id no match'); ok(!Pandoc::Selector->new('#1')->match($e), 'id no match'); ok(Pandoc::Selector->new('.f0_0')->match($e), 'class match'); ok(Pandoc::Selector->new('.bar .f0_0')->match($e), 'classes match'); ok(!Pandoc::Selector->new('.xyz')->match($e), 'class no match'); ok $e->match("code\t:inline .bar#abc .f0_0"), 'multiple match'; { my $plain = Plain [ Math InlineMath, 'x' ]; is_deeply $plain->query(':inline'), $plain->content, ':inline match without keywords'; } done_testing; synopsis.t100644001750001750 263113347276615 15621 0ustar00vojvoj000000000000Pandoc-Elements-0.38/tuse strict; use Test::More; use Pandoc::Elements; use JSON; # Use Test::Deep because it handles blessed structures # with overloaded stringification correctly. BEGIN { plan skip_all => 'Test::Deep not available' unless eval 'require Test::Deep; 1;'; Test::Deep->import( qw[cmp_deeply noclass] ); } my $ast = Document { title => MetaInlines [ Str 'Greeting' ] }, [ Header( 1, attributes { id => 'de' }, [ Str 'Gruß' ] ), Para [ Str 'hello, world!' ], ], api_version => '1.17.0.4'; # note explain $ast->TO_JSON; cmp_deeply $ast, noclass { 'blocks' => [ { 'c' => [ 1, [ 'de', [], [] ], [ { 'c' => 'Gruß', 't' => 'Str' } ] ], 't' => 'Header' }, { 'c' => [ { 'c' => 'hello, world!', 't' => 'Str' } ], 't' => 'Para' } ], 'meta' => { 'title' => { 'c' => [ { 'c' => 'Greeting', 't' => 'Str' } ], 't' => 'MetaInlines' } }, 'pandoc-api-version' => [ 1, 17, 0, 4 ] }; my $json = JSON->new->utf8->convert_blessed->encode($ast); cmp_deeply decode_json($json), noclass($ast), 'encode/decode JSON'; cmp_deeply Pandoc::Elements::pandoc_json($json), noclass($ast), 'pandoc_json'; $json = $ast->to_json; cmp_deeply decode_json($json), noclass($ast), 'to_json'; eval { Pandoc::Elements->pandoc_json(".") }; like $@, qr{.+at.+synopsis.*\.t}, 'error in pandoc_json'; done_testing; __DATA__ % Greeting # Gruß {.de} hello, world! accessors.t100644001750001750 346213347276615 15722 0ustar00vojvoj000000000000Pandoc-Elements-0.38/tuse strict; use Test::More; use Pandoc::Elements; my $e = CodeBlock attributes { class => ['perl'], id => 2 }, 'say "Hi";'; is_deeply $e->attr, $e->{c}->[0], 'CodeBlock->attr'; is $e->id, '2', 'AttributeRole->id'; is $e->class, 'perl', 'AttributeRole->class'; is $e->content, 'say "Hi";', 'CodeBlock->content'; is $e->content('foo'), 'foo', 'setter'; is $e->content, 'foo', 'setter'; $e = Quoted SingleQuote, 'x'; is $e->type->name, 'SingleQuote', 'Quoted'; { my $e = BulletList []; is_deeply $e->items, [], 'BulletList: items'; my $items = [ [ Plain Str 'foo' ] ]; is_deeply $e->content($items), $items, 'BulletList: content(...)'; is_deeply $e->items, $items, 'BulletList: items set'; } { my $content = 'a'; my $attr = attributes {}; my $e = Span $attr, $content; is_deeply $e->attr, $attr, 'Span: attr'; $attr = attributes { a => 1 }; is_deeply $e->attr($attr), $attr, 'Span: attr(...)'; is_deeply $e->attr, $attr, 'Span: attr set'; is_deeply $e->content, 'a', 'Span: content'; is_deeply $e->content('b'), 'b', 'Span: content(...)'; is_deeply $e->content, 'b', 'Span: content set'; } { my $e = DefinitionList [ [ [ Str 'term 1' ], [ [ Para Str 'definition 1' ] ] ], [ [ Str 'term 2' ], [ [ Para Str 'definition 2' ], [ Para Str 'definition 3' ] ] ], ]; is_deeply $e->items, $e->content, 'DefinitionList: items=content'; is scalar @{$e->items}, 2, 'DefinitionList->items'; is_deeply $e->items->[0]->term, [ Str 'term 1' ], '...->term'; is_deeply $e->items->[1]->definitions->[1], [ Para Str 'definition 3' ], '...->definitions'; } { my $doc = Document { foo => 1 }, []; note explain $doc->to_json; is_deeply $doc->meta->value, { foo => 1 }, 'Document: meta'; $doc->meta({ bar => 0 }); is_deeply $doc->meta->value, { bar => 0 }, 'Document: meta(...)'; } done_testing; example.tex100644001750001750 16713347276615 15704 0ustar00vojvoj000000000000Pandoc-Elements-0.38/t\section{Section with \emph{ÄÖÜ} and \href{http://example.org/}{link}} \subsection{Subsection with \textbf{äöü}} lineblock.t100644001750001750 213513347276615 15673 0ustar00vojvoj000000000000Pandoc-Elements-0.38/tuse strict; use Test::More; use Pandoc::Elements; use JSON; # internal representation my $lineblock = LineBlock [ [ Str " foo"], [ Str "bar"], [ Str " baz"], ]; ok $lineblock->is_block, 'is_block'; { local $Pandoc::Elements::PANDOC_VERSION = '1.16'; my $expect = { t => 'Para', c => [ { 'c' => "\x{a0}\x{a0}foo", 't' => 'Str' }, { 'c' => [], 't' => 'LineBreak' }, { 'c' => "bar", 't' => 'Str' }, { 'c' => [], 't' => 'LineBreak' }, { 'c' => "\x{a0}baz", 't' => 'Str' } ] }; is_deeply $expect, decode_json($lineblock->to_json), 'PANDOC_VERSION < 1.18'; } { local $Pandoc::Elements::PANDOC_VERSION = '1.18'; my $expect = { t => 'LineBlock', c => [ [ { 'c' => "\x{a0}\x{a0}foo", 't' => 'Str' } ], [ { 'c' => "bar", 't' => 'Str' } ], [ { 'c' => "\x{a0}baz", 't' => 'Str' } ] ] }; is_deeply $expect, decode_json($lineblock->to_json), 'PANDOC_VERSION >= 1.18'; } done_testing; softbreak.t100644001750001750 235213347276615 15712 0ustar00vojvoj000000000000Pandoc-Elements-0.38/tuse strict; use Test::More; use Pandoc::Elements qw(pandoc_json Space); my $json_in = ; my $ast = pandoc_json( $json_in ); is $ast->string, 'Dolorem sapiente ducimus quia beatae sapiente perspiciatis quia. Praesentium est cupiditate architecto temporibus eos.', 'replaced SoftBreak with spaces'; $Pandoc::Elements::PANDOC_VERSION = '1.16'; like $ast->to_json, qr/"SoftBreak"/, 'keep SoftBreak by default'; $Pandoc::Elements::PANDOC_VERSION = '1.15'; unlike $ast->to_json, qr/"SoftBreak"/, 'no SoftBreak in modified ast'; done_testing; __DATA__ [{"unMeta":{}},[{"t":"Para","c":[{"t":"Str","c":"Dolorem"},{"t":"Space","c":[]},{"t":"Str","c":"sapiente"},{"t":"Space","c":[]},{"t":"Str","c":"ducimus"},{"t":"Space","c":[]},{"t":"Str","c":"quia"},{"t":"SoftBreak","c":[]},{"t":"Str","c":"beatae"},{"t":"Space","c":[]},{"t":"Str","c":"sapiente"},{"t":"Space","c":[]},{"t":"Str","c":"perspiciatis"},{"t":"Space","c":[]},{"t":"Str","c":"quia."},{"t":"SoftBreak","c":[]},{"t":"Str","c":"Praesentium"},{"t":"Space","c":[]},{"t":"Str","c":"est"},{"t":"Space","c":[]},{"t":"Str","c":"cupiditate"},{"t":"SoftBreak","c":[]},{"t":"Str","c":"architecto"},{"t":"Space","c":[]},{"t":"Str","c":"temporibus"},{"t":"Space","c":[]},{"t":"Str","c":"eos."}]}]] stringify.t100644001750001750 201113347276615 15740 0ustar00vojvoj000000000000Pandoc-Elements-0.38/tuse strict; use Test::More; use Pandoc::Elements; my $doc = Document { }, [ Header(1,attributes {},[ Str 'hello', Code attributes {}, ', ' ]), BulletList [ [ Plain [ Str 'world', Space, Str '!' ] ] ], ]; $doc->meta->{foo} = MetaInlines [ Emph [ Str "FOO" ] ]; $doc->meta->{bar} = MetaString "BAR"; $doc->meta->{doz} = MetaMap { x => MetaList [ MetaInlines [ Str "DOZ" ] ] }; is $doc->meta->{foo}->string, 'FOO', 'stringify MetaInlines'; is $doc->meta->{bar}->string, 'BAR', 'stringify MetaString'; is $doc->meta->{doz}->string, 'DOZ', 'stringify MetaMap>MetaList>MetaInlines'; is $doc->string, 'hello, world !', 'stringify Document with metadata'; is LineBreak->string, ' ', 'LineBreak to space'; is RawBlock('html','hi')->string, '', 'RawBlock has no string'; is RawInline('html','hi')->string, '', 'RawInline has no string'; is Code(attributes {},'#!$')->string, '#!$', 'Code has string'; is CodeBlock({}, 'Hi')->string, 'Hi', 'CodeBlock has string'; done_testing; __DATA__ # hello`,` * world ! to_pandoc.t100644001750001750 135313347276615 15700 0ustar00vojvoj000000000000Pandoc-Elements-0.38/tuse strict; use 5.010; use Test::More; use Pandoc::Elements; use Pandoc; use File::Temp; plan skip_all => 'pandoc >= 1.12.1 not available' unless (pandoc and pandoc->version > '1.12.1'); my $doc = pandoc->file('t/documents/outline.md'); { my $html = $doc->to_pandoc( '-t' => 'html' ); ok $html =~ qr{^

test document

}, 'to_pandoc'; } { my $html = $doc->to_pandoc( '-t' => 'html', '--standalone' ); ok $html =~ qr{^to_markdown, $doc->to_pandoc( '-t' => 'markdown' ), 'to_markdown'; } { my $to_latex = new_ok Pandoc => [ '-t' => 'latex' ], 'to-latex-object'; is $doc->to_pandoc( $to_latex ), $doc->to_latex,'to latex with custom Pandoc'; } done_testing; attributes.t100644001750001750 374313347276615 16125 0ustar00vojvoj000000000000Pandoc-Elements-0.38/tuse strict; use v5.10; use Test::More; use Pandoc::Elements; use Hash::MultiValue; my $attr_hash = { class => [qw(x x y)], answer => 42, id => 0 }; is_deeply attributes {}, [ '', [], [] ], 'empty attributes'; is_deeply attributes(undef), [ '', [], [] ], 'empty attributes (undef)'; is_deeply attributes $attr_hash, [ '0', [qw(x x y)], [ [ answer => '42' ] ] ], 'classes and id'; my $e = Code attributes {}, ''; is_deeply [], [ $e->keyvals->flatten ], 'empty attributes'; $e = Code attributes $attr_hash, ''; is_deeply [ id => '0', class => 'x x y', answer => '42', ], [ $e->keyvals->flatten ], 'keyvals'; $e = Code [ '', [], [ [ foo => '1' ], [ bar => '2' ], [ foo => '3' ] ] ], ''; is_deeply [ $e->keyvals->flatten ], [ foo => 1, bar => 2, foo => 3 ], 'keyvals'; $e->keyvals( Hash::MultiValue->new( foo => 9, id => 0, bar => 8, foo => 7, class => 'a', class => 'b c', ) ); is_deeply [ '0', [qw(a b c)], [ [ foo => 9 ], [ bar => 8 ], [ foo => 7 ] ] ], $e->attr, 'attributes via Hash::MultiValue'; $e->keyvals({ foo => 3, class => 'x y' }); is_deeply [ '0', [qw(x y)], [ [ foo => 3 ] ] ], $e->attr, 'keyvals as setter'; $e->keyvals({ }); is_deeply [ '0', [qw(x y)], [ ] ], $e->attr, 'keyvals as setter (no class)'; $e->keyvals( id => undef, class => undef ); is_deeply [ '', [], [ ] ], $e->attr, 'keyvals to remove id and classes'; $e->id(2); is '2', $e->id, 'id setter'; $e->class('q r', 's ', [qw(x y)]); is_deeply 'q r s x y', $e->class, 'class setter'; $e->keyvals( a => 1, class => ['s'], a => 2 ); is_deeply [ '2', ['s'], [ [ a => 1 ], [ a => 2 ] ] ], $e->attr, 'keyvals as setter'; my @class_hashes = ( { class => [qw(foo bar doz)] }, { class => 'foo bar doz ' }, { class => " foo\t bar\n doz " }, ); foreach (@class_hashes) { $e = CodeBlock attributes $_, ''; is_deeply $e->class, 'foo bar doz', 'class(es) attributes'; } foreach (qw(foo bar doz)) { ok $e->match(".$_"), 'class match'; } ok !$e->match('.baz'), 'class selector'; done_testing; meta-filter.t100644001750001750 175213347276615 16146 0ustar00vojvoj000000000000Pandoc-Elements-0.38/tuse strict; use 5.010; use Test::More; use Pandoc::Filter; use Pandoc::Elements; my $json = '[{"unMeta":{"foo":{"c":[{"c":"bar","t":"Str"}],"t":"MetaInlines"}}},[{"c":[{"c":"doz","t":"Str"}],"t":"Para"}]]'; my $allcaps = '[{"unMeta":{"foo":{"c":[{"c":"BAR","t":"Str"}],"t":"MetaInlines"}}},[{"c":[{"c":"DOZ","t":"Str"}],"t":"Para"}]]'; my $contentcaps = '[{"unMeta":{"foo":{"c":[{"c":"bar","t":"Str"}],"t":"MetaInlines"}}},[{"c":[{"c":"DOZ","t":"Str"}],"t":"Para"}]]'; my $filter = Pandoc::Filter->new( Str => sub { Str(uc $_->content) } ); my $doc = pandoc_json($json); $doc->transform($filter), is $doc->to_json, $allcaps, 'transform with metadata element'; $doc = pandoc_json($json); $filter->apply($doc->content); is $doc->to_json, $contentcaps, 'apply document content only'; { open my $stdin, '<', \$json; local *STDIN = $stdin; my $doc = pandoc_walk Str => sub { Str(uc $_->content) }; is $doc->to_json, $contentcaps, 'pandoc_walk document content only'; } done_testing; multifilter.t100644001750001750 503313347276615 16271 0ustar00vojvoj000000000000Pandoc-Elements-0.38/tuse strict; use Test::More; use Test::Exception; use Pandoc::Elements; use Pandoc::Filter::Multifilter qw(find_filter apply_filter); use IPC::Cmd 'can_run'; use Pandoc; # used to test ~/.pandoc/filters as default filter location # this does not work on Windows because of symlinks my ($PANDOC_SYMLINK) = grep { -d $_ } ('t/.pandoc'); # find_filter( ... ) { my @tests = ( { input => ['script/multifilter'], expected => ['script/multifilter'], name => 'absolute path', skip => 'MSWin32', }, { input => ['t/pandoc/filters/empty.pl'], expected => [ 'perl', 't/pandoc/filters/empty.pl' ], name => 'known extension', }, { input => ['perl'], expected => [ can_run('perl') ], name => 'executable in $PATH', }, ); local $ENV{HOME} = 't'; if ( $PANDOC_SYMLINK ) { push @tests, ( { input => ['empty.pl'], expected => [ 'perl', 't/.pandoc/filters/empty.pl' ], name => 'known extension in DATADIR', }, { input => ['caps'], expected => ['t/.pandoc/filters/caps'], name => 'executable in DATADIR', skip => 'MSWin32', }, ); } while ( my $test = shift @tests ) { SKIP: { skip 'find_filter: ' . $test->{name} . ' on ' . $^O, 1 if $^O eq ($test->{skip} || '-'); my @filter = find_filter( @{ $test->{input} } ); is_deeply \@filter, $test->{expected}, join ' ', 'find_filter: ' . $test->{name}; } } my $notfound = '0c9703d020ded30c97682e812636c9ef'; throws_ok { find_filter($notfound) } qr/^filter not found: $notfound/; } if ( $ENV{RELEASE_TESTING} and pandoc and pandoc->version('1.12') ) { my $in = Document {}, [ Para [ Str 'hi' ] ]; my $out = apply_filter( $in, 'html', find_filter( 'caps', 't/pandoc' ) ); is $out->string, 'HI', 'apply_filter'; throws_ok { apply_filter( $in, 'html', find_filter( 'empty.pl', 't/pandoc' ) ); } qr{^filter emitted no valid JSON}; if ( $PANDOC_SYMLINK ) { $in->meta( { multifilter => MetaList [ MetaInlines [ Str 'caps' ] ] } ); local $ENV{HOME} = 't'; Pandoc::Filter::Multifilter->new->apply($in)->to_json; is $in->string, 'HI', 'apply_filter'; } } else { note "Skipping detailed testing of Pandoc::Filter::Multifilter"; } done_testing; examples000755001750001750 013347276615 14756 5ustar00vojvoj000000000000Pandoc-Elements-0.38caps.pl100755001750001750 121013347276615 16376 0ustar00vojvoj000000000000Pandoc-Elements-0.38/examples#!/usr/bin/env perl use strict; =head1 DESCRIPTION Pandoc filter to convert all regular text to uppercase. Code, link URLs, etc. are not affected. =cut use Pandoc::Filter; use Pandoc::Elements qw(Str); pandoc_filter Str => sub { return Str(uc $_->content); # alternatively to modify in-place (comment out previous line to enable) $_->content(uc($_->content)); return }; =head1 SYNOPSIS pandoc --filter caps.pl -o output.html < input.md =head1 SEE ALSO This is a port of L from Python to Perl with L and L. =cut qids.pl100644001750001750 111213347276615 16406 0ustar00vojvoj000000000000Pandoc-Elements-0.38/examples#!/usr/bin/env perl use strict; =head1 DESCRIPTION Pandoc filter to link all Wikidata ids such as C<[Q123]> =cut use Pandoc::Filter; use Pandoc::Elements; pandoc_filter Str => sub { my @split = split /\[([QP][0-9]+)\]/, $_->content; return if @split < 2; my @inlines; while (@split) { my $str = shift @split; push @inlines, Str($str) if $str ne ''; my $id = shift @split or last; my $url = "http://www.wikidata.org/entity/$id"; push @inlines, Link attributes {}, [ Str $id ], [ $url, '' ]; } return \@inlines; }; scalar-types.t100644001750001750 630113347276615 16337 0ustar00vojvoj000000000000Pandoc-Elements-0.38/tuse strict; use Test::More; use Pandoc::Elements qw(pandoc_json); use JSON qw(decode_json); # deliberately erroneous, # i.e. pandoc should choke on it unless the appropriate # TO_JSON methods have done their magic on it! my $bad_json = <<'JSON'; [{"unMeta":{"MetaBool":{"t":"MetaBool","c":true}}},[{"t":"Header","c":["1",["heading",[],[]],[{"t":"Str","c":"Heading"},{"c":[],"t":"Space"}]]},{"t":"Para","c":[{"c":[[{"citationMode":{"t":"NormalCitation","c":[]},"citationPrefix":[{"c":"citation","t":"Str"}],"citationSuffix":[{"c":[],"t":"Space"},{"c":"p.","t":"Str"},{"c":[],"t":"Space"},{"c":13,"t":"Str"}],"citationId":"author2015","citationNoteNum":"0","citationHash":"0"}],[{"t":"Str","c":"[citation"},{"t":"Space","c":[]},{"c":"@author2015","t":"Str"},{"t":"Space","c":[]},{"c":"p.","t":"Str"},{"c":[],"t":"Space"},{"c":"13]","t":"Str"}]],"t":"Cite"},{"c":",","t":"Str"},{"c":[],"t":"Space"}]},{"t":"OrderedList","c":[["2",{"t":"Decimal","c":[]},{"t":"OneParen","c":[]}],[[{"t":"Plain","c":[{"c":"#1=2","t":"Str"},{"t":"Space","c":[]}]}],[{"c":[{"t":"Str","c":"#2=3"}],"t":"Plain"}]]]},{"t":"Table","c":[[{"t":"Str","c":"Table"},{"t":"Space","c":[]}],[{"t":"AlignLeft","c":[]},{"t":"AlignLeft","c":[]},{"t":"AlignLeft","c":[]}],["0","0","0"],[[{"t":"Plain","c":[{"t":"Str","c":"M."}]}],[{"t":"Plain","c":[{"t":"Str","c":"F."}]}],[{"c":[{"t":"Str","c":"N."}],"t":"Plain"}]],[[[{"c":[{"t":"Str","c":"hic"}],"t":"Plain"}],[{"c":[{"c":"haec","t":"Str"}],"t":"Plain"}],[{"c":[{"c":"hoc","t":"Str"}],"t":"Plain"}]]]]}]] JSON my $good_json = <<'JSON'; [{"unMeta":{"MetaBool":{"c":true,"t":"MetaBool"}}},[{"t":"Header","c":[1,["heading",[],[]],[{"c":"Heading","t":"Str"},{"t":"Space","c":[]}]]},{"t":"Para","c":[{"t":"Cite","c":[[{"citationHash":0,"citationSuffix":[{"c":[],"t":"Space"},{"c":"p.","t":"Str"},{"c":[],"t":"Space"},{"c":"13","t":"Str"}],"citationId":"author2015","citationPrefix":[{"t":"Str","c":"citation"}],"citationNoteNum":0,"citationMode":{"c":[],"t":"NormalCitation"}}],[{"t":"Str","c":"[citation"},{"c":[],"t":"Space"},{"c":"@author2015","t":"Str"},{"c":[],"t":"Space"},{"t":"Str","c":"p."},{"c":[],"t":"Space"},{"t":"Str","c":"13]"}]]},{"c":",","t":"Str"},{"t":"Space","c":[]}]},{"t":"OrderedList","c":[[2,{"c":[],"t":"Decimal"},{"t":"OneParen","c":[]}],[[{"t":"Plain","c":[{"t":"Str","c":"#1=2"},{"c":[],"t":"Space"}]}],[{"c":[{"t":"Str","c":"#2=3"}],"t":"Plain"}]]]},{"t":"Table","c":[[{"t":"Str","c":"Table"},{"c":[],"t":"Space"}],[{"c":[],"t":"AlignLeft"},{"c":[],"t":"AlignLeft"},{"t":"AlignLeft","c":[]}],[0,0,0],[[{"c":[{"t":"Str","c":"M."}],"t":"Plain"}],[{"c":[{"c":"F.","t":"Str"}],"t":"Plain"}],[{"t":"Plain","c":[{"c":"N.","t":"Str"}]}]],[[[{"t":"Plain","c":[{"c":"hic","t":"Str"}]}],[{"c":[{"t":"Str","c":"haec"}],"t":"Plain"}],[{"c":[{"c":"hoc","t":"Str"}],"t":"Plain"}]]]]}]] JSON my $document = eval { pandoc_json( $bad_json ) }; my $error = $@; is $error, "", 'no error reading "bad" JSON'; isa_ok $document, 'Pandoc::Document'; is_deeply decode_json($good_json), $document->TO_JSON, 'fixed JSON'; # IPC::Run3::run3( [pandoc => -f => 'json', -t => 'markdown'], \$json, \my $stdout, \my $stderr ); # is $stderr, "", 'no errors feeding JSON to pandoc' or note $stderr; # note $document->to_json; # note $stdout; done_testing; ditaa.pl100644001750001750 114213347276615 16533 0ustar00vojvoj000000000000Pandoc-Elements-0.38/examples#!/usr/bin/env perl use strict; use Pandoc::Filter; use Pandoc::Filter::ImagesFromCode; pandoc_filter 'CodeBlock.ditaa' => Pandoc::Filter::ImagesFromCode->new( from => 'ditaa', to => 'png', # TODO: support use of dita-eps for vector images run => ['ditaa', '-o', '$infile$', '$outfile$'], ); __END__ =head1 NAME ditaa - process code blocks with C<.ditaa> into images =head1 SYNOPSIS pandoc --filter ditaa.pl -o output.html < input.md =head1 SEE ALSO This is a rewrite of the standalone-script C originally published at L. =cut meta-blessing.t100644001750001750 327213347276615 16466 0ustar00vojvoj000000000000Pandoc-Elements-0.38/tuse strict; use Test::More 0.96; use Pandoc::Elements; use Scalar::Util qw[ blessed reftype ]; my $document = do { local (@ARGV, $/) = ('t/documents/meta.json'); pandoc_json(<>); }; isa_ok $document, 'Pandoc::Document', "it's a document" or note ref $document; my $unblessed_counts = bless_check_loop($document->meta); ok !keys(%$unblessed_counts), 'no unblessed metadata objects' or note "There were some unblessed metadata objects:\n", explain $unblessed_counts; my $undef_count = undef_check_loop( $document->meta ); ok !$undef_count, 'no undef values' or note "There were $undef_count undefined values"; sub bless_check_loop { my @data = @_; my %counts; LOOP: for ( my $i = 0; $i <= @data; $i++ ) { my $item = $data[$i]; next LOOP unless reftype $item; if ( 'ARRAY' eq reftype $item ) { push @data, grep { reftype $_ } @$item; } elsif ( 'HASH' eq reftype $item ) { if ( $item->{t} ) { ++$counts{$item->{t}} unless blessed $item; } push @data, grep { reftype $_ } values %$item; } } return \%counts; } sub undef_check_loop { my @data = @_; my $count; LOOP: for ( my $i = 0; $i <= @data; $i++ ) { my $item = $data[$i]; next LOOP unless reftype $item; if ( 'ARRAY' eq reftype $item ) { $count += grep { !defined($_) } @$item; push @data, grep { reftype $_ } @$item; } elsif ( 'HASH' eq reftype $item ) { $count += grep { !defined($_) } values %$item; push @data, grep { reftype $_ } values %$item; } } return $count; } done_testing; __DATA__ pandoc_filter.t100644001750001750 221013347276615 16534 0ustar00vojvoj000000000000Pandoc-Elements-0.38/tuse Test::More; use Pandoc::Filter; use Pandoc::Elements; use JSON; use Encode; use Test::Output; # FIXME: don't require decode_utf8 (?) my $ast = Pandoc::Elements::pandoc_json( '{"blocks":[{"t":"Para","c":[{"t":"Str","c":"☃"}]}]}' )->blocks->[0]->content->[0]; is_deeply $ast, { t => 'Str', c => decode_utf8("☃") }, 'JSON with Unicode'; Pandoc::Filter->new()->apply($ast); is_deeply $ast, { t => 'Str', c => decode_utf8("☃") }, 'identity filter'; sub shout { return unless $_[0]->name eq 'Str'; return Str($_[0]->content.'!'); } # FIXME: cannot directly filter root element $ast = [$ast]; Pandoc::Filter->new(\&shout)->apply($ast); is_deeply $ast, [{ t => 'Str', c => "\x{2603}!" }], 'applied filter'; { local *STDIN = *DATA; my $data_start = tell DATA; stdout_like(sub { pandoc_filter( \&shout ) }, qr/"c":"☃!"/, 'pandoc_filter (sub)'); seek DATA, $data_start, 0; stdout_like(sub { pandoc_filter( Str => sub { Str($_[0]->content.'!') } ) }, qr/"c":"☃!"/, 'pandoc_filter (hash)'); } done_testing; __DATA__ [{"unMeta":{}},[{"t":"Para","c":[{"t":"Str","c":"☃"}]}]] deemph.pl100755001750001750 102613347276615 16717 0ustar00vojvoj000000000000Pandoc-Elements-0.38/examples#!/usr/bin/env perl use strict; =head1 DESCRIPTION Pandoc filter that causes emphasized text to be displayed in ALL CAPS. =cut use Pandoc::Filter; use Pandoc::Elements qw(Str); pandoc_filter Emph => sub { $_->transform( Str => sub { Str(uc($_->content)) }); }; =head1 SYNOPSIS pandoc --filter deemph.pl -o output.html < input.md =head1 SEE ALSO This is a port of L from Python to Perl with L and L. =cut myemph.pl100644001750001750 141113347276615 16747 0ustar00vojvoj000000000000Pandoc-Elements-0.38/examples#!/usr/bin/env perl use strict; =head1 NAME myemph - use C<\myemp{...}> instead of C<\emph{...}> in LaTeX =head1 DESCRIPTION Pandoc filter that causes emphasized text to be rendered using the custom macro C<\myemph{...}> rather than C<\emph{...}> in LaTeX. Other output formats are unaffected. =cut use Pandoc::Filter; use Pandoc::Elements; pandoc_filter Emph => sub { my ($e, $f, $m) = @_; return if $f ne 'latex'; [ RawInline(latex => '\myemph{'), @{$e->content}, RawInline(latex => '}') ] }; =head1 SYNOPSIS pandoc --filter myemph.pl -o output.html < input.md =head1 SEE ALSO This is a port of L from Python to Perl with L and L. =cut select.pl100755001750001750 132513347276615 16736 0ustar00vojvoj000000000000Pandoc-Elements-0.38/examples#!/usr/bin/env perl use strict; require 5.010; use Pandoc::Elements; my $select = $ENV{PANDOC_SELECT} // die "filter requires environment variable PANDOC_SELECT\n"; my $doc = pandoc_json(); my $blocks = $doc->query( $select => sub { $_->as_block } ); say STDOUT Document({}, $blocks, api_version => $doc->api_version)->to_json; =head1 NAME pandoc-select - select parts of a document with Pandoc =head1 SYNOPSIS PANDOC_SELECT=Link pandoc --filter select -o out.html < in.md PANDOC_SELECT=Header pandoc --filter select -o out.html < in.md =head1 DESCRIPTION This filter expects a L in environment variable C. Selected elements are converted to block elements. =cut script000755001750001750 013347276615 14444 5ustar00vojvoj000000000000Pandoc-Elements-0.38multifilter100755001750001750 156313347276615 17077 0ustar00vojvoj000000000000Pandoc-Elements-0.38/script#!/usr/bin/env perl use strict; use v5.10; =head1 NAME multifilter - Pandoc filter to apply filters listed in field C =head1 DESCRIPTION This Pandoc filter applies other filters listed in document metadata field C. The filters can be specified like with pandoc option C<-F> or C<--filter>. For instance C: --- filters: - filter1 # in $PATH or ~/.pandoc/filters - ./filter2.pl # relative path - /path/filter3 # absolute path ... converted via pandoc --filter multifilter input.md will be filtered like pandoc -F filter1 -F ./filter2.pl -F /path/filter3 input.md In addition, filters are searched in C<~/.pandoc/filters>. =head1 OPTIONS =over =item --help|-h Print this help =back =cut use Pandoc::Filter; use Pandoc::Filter::Multifilter; pandoc_filter_document( Pandoc::Filter::Multifilter->new ); pandoc-version.t100644001750001750 102113347276615 16651 0ustar00vojvoj000000000000Pandoc-Elements-0.38/tuse strict; use Test::More; use Test::Exception; local $ENV{PANDOC_VERSION} = '1.2.3'; require Pandoc::Elements; is Pandoc::Elements::pandoc_version(), '1.2.3', 'pandoc_version from ENV'; Pandoc::Elements->import('pandoc_version'); $Pandoc::Elements::PANDOC_VERSION = 1.3; is pandoc_version(), '1.3', 'set pandoc_version via variable'; { local $Pandoc::Elements::PANDOC_VERSION = undef; is pandoc_version(), '1.19', 'maximum supported version'; } is pandoc_version(), '1.3', 'localize PANDOC_VERSION'; done_testing; deflist.pl100755001750001750 150413347276615 17110 0ustar00vojvoj000000000000Pandoc-Elements-0.38/examples#!/usr/bin/env perl use strict; =head1 NAME deflist - convert definiton lists to bullet lists =head1 DESCRIPTION Pandoc filter to convert definition lists to bullet lists with the defined terms in strong emphasis (for compatibility with standard markdown). =cut use Pandoc::Filter qw(pandoc_filter); use Pandoc::Elements qw(BulletList Para Strong Str); pandoc_filter DefinitionList => sub { BulletList [ map { to_bullet($_) } @{ $_->items } ] }; sub to_bullet { my $item = shift; [ Para [ Strong $item->term ], map { @$_} @{$item->definitions} ] } =head1 SYNOPSIS pandoc --filter deflist.pl -o output.html < input.md =head1 SEE ALSO This is a port of L from Python to Perl with L and L. =cut section.pl100644001750001750 176213347276615 17125 0ustar00vojvoj000000000000Pandoc-Elements-0.38/examples#!/usr/bin/env perl use strict; =head1 NAME section - select document sections =head1 SYNOPSIS section --select-id foo --select-class bar --select-name "the title" section --select '#foo' --select .bar --select '"the title"' =cut use Pandoc::Filter; =head1 DESCRIPTION --- multifilter: - filter: section - options: - select: .keep ... =cut # TODO: get options my @select = ('.keep'); # TODO: use Pandoc::Element::Selector; my $level = 0; # process all elements pandoc_filter sub { my $e = shift; if ($level > 0) { if ($_->name eq 'Header' and $e->level <= $level) { $level = 0; # end of currently selected section } else { return; # keep element in selected section } } if ($e->name eq 'Header' and grep { $e->match($_) } @select ) { $level = $e->level; # new selected section return; # keep Header } else { return []; # skip } }; theorem.pl100644001750001750 231413347276615 17116 0ustar00vojvoj000000000000Pandoc-Elements-0.38/examples#!/usr/bin/env perl use strict; =head1 NAME theorem - handle divs with C<.theorem> as theorems =head1 DESCRIPTION Pandoc filter to convert divs with C to LaTeX theorem environments in LaTeX output, and to numbered theorems in HTML output. =cut use Pandoc::Filter; use Pandoc::Elements; my $theoremcount = 0; sub latex { RawBlock latex => shift } sub html { RawBlock html => shift } pandoc_filter 'Div.theorem' => sub { my ($e, $f, $m) = @_; if ($f eq 'latex') { my $label = $e->id ? '\label{'.$e->id.'}' : ''; return [ latex("\\begin{theorem}$label"), @{$e->content}, latex('\end{theorem}') ]; } elsif ($f eq 'html' or $f eq 'html5') { $theoremcount++; return Div [@{$e->attr}], [ html("
Theorem $theoremcount
\n
"), @{$e->content}, html("
\n") ]; } return; }; =head1 SYNOPSIS pandoc --filter theorem.pl -o output.html < input.md =head1 SEE ALSO This is a port of L from Python to Perl with L and L. =cut linkage-setters.t100644001750001750 124313347276615 17031 0ustar00vojvoj000000000000Pandoc-Elements-0.38/tuse strict; use warnings; use Test::More 0.96; # for subtests use Pandoc::Elements qw[ attributes Str Link Image ]; my @tests = ( [ Link => \&Link ], [Image => \&Image], ); for my $test ( @tests ) { my ( $type, $constr ) = @$test; subtest $type => sub { my $e = $constr->( attributes {}, [ Str $type], [] ); ok( ( can_ok( $e, 'name' ) and $e->name eq $type ), 'name' ); for my $method ( qw[ url title ] ) { can_ok $e, $method; is $e->$method, "", "$method unset"; is $e->$method( $method ), $method, "set $method"; is $e->$method, $method, "$method set"; } }; } done_testing; pandoc-metadata.t100644001750001750 131313347276615 16750 0ustar00vojvoj000000000000Pandoc-Elements-0.38/tuse strict; use Test::More; use Pandoc::Elements; use JSON; is_deeply metadata 'foo', MetaString 'foo'; is_deeply metadata undef, MetaString ''; is_deeply metadata JSON::true(), MetaBool 1; is_deeply metadata JSON::false(), MetaBool 0; is_deeply metadata ['foo'], MetaList [ MetaString 'foo' ]; is_deeply metadata { x => [1] }, MetaMap { x => MetaList [ MetaString '1' ] }; is_deeply metadata MetaString 'foo', MetaString 'foo'; is_deeply metadata Str 'ä', MetaInlines [ Str 'ä' ]; is_deeply metadata Para [ Str 'ä' ], MetaBlocks [ Para [ Str 'ä' ] ]; my $ref = \''; is_deeply metadata $ref, MetaString "$ref"; $ref = bless {}, 'Pandoc::Elements'; is_deeply metadata $ref, MetaString "$ref"; done_testing; comments.pl100755001750001750 165713347276615 17314 0ustar00vojvoj000000000000Pandoc-Elements-0.38/examples#!/usr/bin/env perl use strict; =head1 NAME comments - remove everyting between C<< >> =head1 DESCRIPTION Pandoc filter to ignore everything between C<< >> and C<< >> The comment lines must appear on lines by themselves, with blank lines surrounding them. =cut use Pandoc::Filter; my $incomment = 0; pandoc_filter sub { my $e = shift; if ( $e->name eq 'RawBlock' and $e->format eq 'html' ) { if ( $e->content =~ /^\s*\s*$/ ) { $incomment = $1 eq 'BEGIN'; return []; } } return $incomment ? [] : undef; }; =head1 SYNOPSIS pandoc --filter comments.pl -o output.html < input.md =head1 SEE ALSO This is a port of L from Python to Perl with L and L. =cut graphviz.pl100755001750001750 152113347276615 17307 0ustar00vojvoj000000000000Pandoc-Elements-0.38/examples#!/usr/bin/env perl use strict; use Pandoc::Filter; use Pandoc::Filter::ImagesFromCode; pandoc_filter 'CodeBlock.graphviz' => Pandoc::Filter::ImagesFromCode->new( from => 'dot', to => sub { $_[0] eq 'latex' ? 'pdf' : 'png' }, run => ['dot', '-T$to$', '-o$outfile$', '$infile$'], ); =head1 NAME graphviz - process code blocks with C<.graphviz> into images =head1 DESCRIPTION Pandoc filter to process code blocks with class C into graphviz-generated images. Attribute C can be used to select layout engine (C by default). =head1 SYNOPSIS pandoc --filter graphviz.pl -o output.html < input.md =head1 SEE ALSO This is an extended port of L from Python to Perl with L and L. =cut metavars.pl100755001750001750 475713347276615 17315 0ustar00vojvoj000000000000Pandoc-Elements-0.38/examples#!/usr/bin/env perl use strict; =head1 NAME metavars - interpolate metadata C<{{field}} references =head1 DESCRIPTION Pandoc filter to allow interpolation of metadata fields into a document. Field references such as C<{{field}}> will be replaced by the field's value or by an empty string. Spaces in, before, and after field names are not allowed. Metadata fields of type L and L are always replaced in inline elements (L). Metadata fields of type L are also replaced in block elements if the reference is the only content of the block. To literally include a field reference, define and include another field with content C<'{{field}}'>. =cut use Pandoc::Filter; use Pandoc::Elements qw(element Str); pandoc_filter 'Plain|Para' => sub { my ($e, $f, $m) = @_; return if @{$e->content} != 1 or $e->content->[0]->name ne 'Str'; return if $e->content->[0]->content !~ /^{{(.+?)}}$/; my $var = $m->{$1}; if ($var) { if ($var->name eq 'MetaInlines') { return element($e->name, $var->content); } elsif ($var->name eq 'MetaString') { return element($e->name, [ Str $var->content ]); } elsif ($var->name eq 'MetaBlocks') { return $var->content; } } return element($e->name, []); # keep element but empty }, Str => sub { my ($e, $f, $m) = @_; return unless $e->content =~ /{{(.+?)}}/; my @parts = split /{{(.+?)}}/, $e->content; return if @parts < 2; my @inlines; while (@parts) { my $str = shift @parts; my $field = shift @parts; push @inlines, Str($str) if $str ne ''; next unless defined $field and $field ne ''; my $var = $m->{$field} or next; if ($var->name eq 'MetaInlines') { push @inlines, @{$var->content}; } elsif ($var->name eq 'MetaString') { push @inlines, Str $var->content; } } return \@inlines; }, ; =head1 SYNOPSIS pandoc --filter metavars.pl -o output.html < input.md =head1 SEE ALSO This is an improved port of L from Python to Perl with L and L. =cut Pandoc000755001750001750 013347276615 15112 5ustar00vojvoj000000000000Pandoc-Elements-0.38/libFilter.pm100644001750001750 1264013347276615 17060 0ustar00vojvoj000000000000Pandoc-Elements-0.38/lib/Pandocpackage Pandoc::Filter; use strict; use warnings; use 5.010; our $VERSION = '0.34'; use JSON; use Carp; use Scalar::Util 'reftype'; use List::Util; use Pandoc::Walker; use Pandoc::Elements qw(Image Str); use parent 'Exporter'; our @EXPORT = qw(pandoc_filter pandoc_filter_document pandoc_walk); # FUNCTIONS sub pandoc_walk(@) { ## no critic my $filter = Pandoc::Filter->new(@_); my $ast = Pandoc::Elements::pandoc_json(); binmode STDOUT, ':encoding(UTF-8)'; $filter->apply( $ast->content, @ARGV ? $ARGV[0] : '', $ast->meta ); return $ast; } sub _pod2usage_if_help { require Getopt::Long; my %opt; Getopt::Long::GetOptions(\%opt, 'help|?'); return unless $opt{help}; ## no critic my $module = -t STDOUT ? 'Pod::Text::Termcap' : 'Pod::Text'; eval "require $module" or die "Can't locate $module in \@INC\n"; $module->new( indent => 2, nourls => 1 )->parse_file($0); exit; } sub pandoc_filter(@) { ## no critic _pod2usage_if_help(); my $ast = pandoc_walk(@_); # implies binmode STDOUT UTF-8 my $json = JSON->new->allow_blessed->convert_blessed->encode($ast); #my $json = $ast->to_json; # does not want binmode STDOUT UTF-8 say STDOUT $json; } sub pandoc_filter_document($) { ## no critic _pod2usage_if_help(); my $filter = shift; my $doc = Pandoc::Elements::pandoc_json(); $filter->apply( $doc, $ARGV[0] ); say $doc->to_json; } # METHODS sub new { my $class = shift; my $action = (@_ < 2 or @_ % 2 or ref $_[0]) ? Pandoc::Walker::action(@_) # @actions : Pandoc::Walker::action({ @_ }); # %actions bless { action => $action, error => '', }, $class; } sub action { $_[0]->{action}; } sub apply { my ( $self, $ast, $format, $meta ) = @_; $format ||= ''; $meta ||= eval { $ast->meta } || {}; Pandoc::Walker::transform( $ast, $self->action, $format, $meta ); $ast; } 1; __END__ =encoding utf-8 =head1 NAME Pandoc::Filter - process Pandoc abstract syntax tree =head1 SYNOPSIS Filter C, adopted from L, converts level 2+ headers to regular paragraphs: use Pandoc::Filter; use Pandoc::Elements; pandoc_filter Header => sub { return unless $_->level >= 2; # keep return Para [ Emph $_->content ]; # replace }; Apply this filter on a Markdown file like this: pandoc --filter flatten.pl -t markdown < input.md See L for more examples of filters. =head1 DESCRIPTION Pandoc::Filter provides tools to modify the abstract syntax tree (AST) of L documents. See L for AST elements that can be modified by filters. The function interface (see L) directly reads AST and format from STDIN and ARGV and prints the transformed AST to STDOUT. The object oriented interface (see L) requires to: my $filter = Pandoc::Filter->new( ... ); # create a filter object $filter->apply( $ast, $format ); # pass it an AST for processing If you don't need the C parameter, consider using the interface provided by module L instead. It can be used both: transform $ast, ...; # as function $ast->transform( ... ); # or as method =head1 ACTIONS An action is a code reference that is executed on matching document elements of an AST. The action is passed a reference to the current element, the output format (the empty string by default), and the document metadata (an empty hash by default). The current element is also given in the special variable C<$_> for convenience. The action is expected to return an element, an empty array reference, or C to modify, remove, or keep a traversed element in the AST. =head1 METHODS =head2 new( @actions | %actions ) Create a new filter object with one or more actions (see L). If actions are given as hash, key values are used to check which elements to apply for, e.g. Pandoc::Filter->new( Header => sub { ... }, 'Suscript|Superscript' => sub { ... } ) =head2 apply( $ast [, $format [, $metadata ] ] ) Apply all actions to a given abstract syntax tree (AST). The AST is modified in place and also returned for convenience. Additional argument format and metadata are also passed to the action function. Metadata is taken from the Document by default (if the AST is a Document root). =head2 action Return a code reference to call all actions. =head1 FUNCTIONS The following functions are exported by default. =head2 pandoc_filter( @actions | %actions ) Read a single line of JSON from STDIN, apply actions on the document content and print the resulting AST as single line of JSON. Filter documentation is printed if filter called with command line argument C<--help>, C<-h>, or C<-?>. See L for extended ways to process filter documentation. =head1 FILTER MODULES =over =item L =item L =item L =back =head1 SEE ALSO This module is a port of L from Python to modern Perl. =head1 COPYRIGHT AND LICENSE Copyright 2014- Jakob Voß GNU General Public License, Version 2 This module is heavily based on Pandoc by John MacFarlane. =cut Walker.pm100644001750001750 1532613347276615 17064 0ustar00vojvoj000000000000Pandoc-Elements-0.38/lib/Pandocpackage Pandoc::Walker; use strict; use warnings; use 5.010; our $VERSION = '0.34'; use Scalar::Util qw(reftype blessed); use Carp; use parent 'Exporter'; our @EXPORT = qw(walk query transform); our @EXPORT_OK = ( @EXPORT, 'action' ); sub _simple_action { my $action = shift // return sub { }; if ( blessed $action and $action->isa('Pandoc::Filter') ) { $action = $action->action; } elsif ( !ref $action or ref $action ne 'CODE' ) { croak "expected code reference, got: " . ( $action // 'undef' ); } if (@_) { my @args = @_; return sub { local $_ = $_[0]; $action->( $_[0], @args ) }; } else { return $action; } } sub action { my @actions; my @args; # $selector => $action [, @arguments ] if ( !ref $_[0] ) { @actions = ( shift, shift // sub { $_ } ); @args = @_; } # { $selector => $code, ... } [, @arguments ] elsif ( ref $_[0] eq 'HASH' ) { @actions = %{ shift @_ }; @args = @_; # code [, @arguments ] } else { return _simple_action(@_); } my $n = ( scalar @actions ) / 2 - 1; # check action functions and add arguments $actions[ $_ * 2 + 1 ] = _simple_action( $actions[ $_ * 2 + 1 ], @args ) for 0 .. $n; # TODO: compile selectors for performance sub { my $element = $_[0]; # get all matching actions my @matching = map { $actions[ $_ * 2 + 1 ] } grep { $element->match( $actions[ $_ * 2 ] ) } 0 .. $n; my @return = (); foreach my $action (@matching) { local $_ = $_[0]; # FIXME: $doc->walk( Section => sub { $_->id } ) @return = ( $action->(@_) ); } wantarray ? @return : $return[0]; } } sub transform { my $ast = shift; my $action = action(@_); my $reftype = reftype($ast) || ''; if ( $reftype eq 'ARRAY' ) { for ( my $i = 0 ; $i < @$ast ; ) { my $item = $ast->[$i]; if ( ( reftype $item || '' ) eq 'HASH' and $item->{t} ) { my $res = $action->($item); if ( defined $res ) { # stop traversal if ( $res eq \undef ) { $i++; # replace current item with result element(s) } else { my @elements = #map { transform($_, $action, @_) } ( reftype $res || '' ) eq 'ARRAY' ? @$res : $res; splice @$ast, $i, 1, @elements; $i += scalar @elements; } next; } } transform( $item, $action ); $i++; } } elsif ( $reftype eq 'HASH' ) { # TODO: directly transform an element. # if (blessed $ast and $ast->isa('Pandoc::Elements::Element')) { # } else { foreach ( keys %$ast ) { transform( $ast->{$_}, $action, @_ ); } # } } $ast; } sub walk(@) { ## no critic my $ast = shift; my $action = action(@_); transform( $ast, sub { local $_ = $_[0]; my $q = $action->(@_); return (defined $q and $q eq \undef) ? \undef : undef } ); } sub query(@) { ## no critic my $ast = shift; my $action = action(@_); my $list = []; transform( $ast, sub { local $_ = $_[0]; my $q = $action->(@_); return $q if !defined $q or $q eq \undef; push @$list, $q; return } ); return $list; } 1; __END__ =encoding utf-8 =head1 NAME Pandoc::Walker - utility functions to process Pandoc documents =head1 SYNOPSIS use Pandoc::Walker; use Pandoc::Elements qw(pandoc_json); my $ast = pandoc_json(<>); # extract all links and image URLs my $links = query $ast, 'Link|Image' => sub { $_->url }; # print all links and image URLs walk $ast, 'Link|Image' => sub { say $_->url }; # remove all links transform $ast, sub { return ($_->name eq 'Link' ? [] : ()); }; # replace all links by their link text angle brackets use Pandoc::Elements 'Str'; transform $ast, Link => sub { return (Str " < ", $_->content->[0], Str " > "); }; =head1 DESCRIPTION This module provides utility functions to traverse the abstract syntax tree (AST) of a pandoc document (see L for documentation of AST elements). Document elements are passed to action functions by reference, so I by trying to directly modify the element. Traversing a single element is not reliable neither, so put the element in an array reference if needed. For instance to replace links in headers only by their link text content: transform $ast, Header => sub { transform [ $_[0] ], Link => sub { # make an array return $_[0]->content; # is an array }; }; See also L for an object oriented interface to transformations. =head1 FUNCTIONS =head2 action ( [ $selector => ] $code [, @arguments ] ) =head2 action ( { $selector => $code, ... } [, @arguments ] ) Return an an action function to process document elements. =head2 walk( $ast, ... ) Walks an abstract syntax tree and calls an action on every element or every element of given name(s). Additional arguments are also passed to the action. If and only if the action function returns C<\undef> the current element is not traversed further. See also function C exported by L. =head2 query( $ast, ... ) Walks an abstract syntax tree and applies one or multiple query functions to extract results. The query function is expected to return a list or C<\undef>. The combined query result is returned as array reference. For instance the C method of L is implemented as following: join '', @{ query( $ast, { 'Str|Code|Math' => sub { $_->content }, 'LineBreak|Space' => sub { ' ' } } ); =head2 transform( $ast, ... ) Walks an abstract syntax tree and applies an action on every element, or every element of given name(s), to either keep it (if the action returns C or C<\undef>), remove it (if it returns an empty array reference), or replace it with one or more elements (returned by array reference or as single value). See also function C exported by L. =head1 COPYRIGHT AND LICENSE Copyright 2014- Jakob Voß GNU General Public License, Version 2 This module is heavily based on Pandoc by John MacFarlane. =head1 SEE ALSO Haskell module L for the original. =cut documents000755001750001750 013347276615 15404 5ustar00vojvoj000000000000Pandoc-Elements-0.38/tmeta.json100644001750001750 411013347276615 17361 0ustar00vojvoj000000000000Pandoc-Elements-0.38/t/documents[ { "unMeta": { "officia": { "t": "MetaInlines", "c": [ { "t": "Str", "c": "molestias" } ] }, "error": { "t": "MetaMap", "c": { "magni": { "t": "MetaInlines", "c": [ { "t": "Str", "c": "repellendus" } ] }, "minima": { "t": "MetaList", "c": [ { "t": "MetaInlines", "c": [ { "t": "Str", "c": "nihil" } ] }, { "t": "MetaMap", "c": { "aliquam": { "t": "MetaInlines", "c": [ { "t": "Str", "c": "voluptas" } ] }, "eos": { "t": "MetaInlines", "c": [ { "t": "Str", "c": "odit" } ] }, "true": { "t": "MetaBool", "c": true } } } ] }, "perferendis": { "t": "MetaInlines", "c": [ { "t": "Str", "c": "aut" } ] } } }, "illo": { "t": "MetaList", "c": [ { "t": "MetaInlines", "c": [ { "t": "Str", "c": "nesciunt" } ] } ] }, "tempora": { "t": "MetaInlines", "c": [ { "t": "Str", "c": "nisi" } ] } } }, [] ] filters000755001750001750 013347276615 16317 5ustar00vojvoj000000000000Pandoc-Elements-0.38/t/pandoccaps100755001750001750 16513347276615 17315 0ustar00vojvoj000000000000Pandoc-Elements-0.38/t/pandoc/filters#!/usr/bin/env perl use Pandoc::Filter; pandoc_filter Str => sub { $_->content(uc($_->content)); return }; Elements.pm100644001750001750 13341513347276615 17433 0ustar00vojvoj000000000000Pandoc-Elements-0.38/lib/Pandocpackage Pandoc::Elements; use strict; ## no critic (ProhibitNoStrict, ProhibitSubroutinePrototypes) use warnings; use 5.010001; our $VERSION = '0.38'; use Carp; use JSON qw(decode_json); use Scalar::Util qw(blessed reftype); use Pandoc::Walker qw(walk); use Pandoc::Version; our $PANDOC_VERSION; # a string like '1.16' $PANDOC_VERSION ||= eval { Pandoc::Version->new($ENV{PANDOC_VERSION}) }; # internal variables my $PANDOC_API_MIN = Pandoc::Version->new('1.12.3'); # since pandoc 1.12.1 my $PANDOC_BIN_MIN = Pandoc::Version->new('1.12.1'); # release version => minimal required api version my @REQUIRED_API = map { Pandoc::Version->new($_) } '1.19' => '1.17', # pandoc 1.19 has api 1.17.0.4, compatible with api 1.17 '1.18' => '1.17', # pandoc 1.18 has api 1.17.0.4, compatible with api 1.17 '1.16' => '1.16', # pandoc 1.16 has api 1.16 '1.17' => '1.16', # pandoc 1.17 has api 1.16 ; sub _as_pandoc_version { (blessed $_[0] and $_[0]->isa('Pandoc::Version')) ? $_[0] : Pandoc::Version->new($_[0]) } sub pandoc_version { if (@_) { my $doc = shift; if (@_) { $doc->api_version( _minimum_pandoc_api_for(@_) // croak "pandoc version not supported" ); } _minimum_pandoc_version_for_api($doc->api_version); } elsif (defined $PANDOC_VERSION) { _as_pandoc_version($PANDOC_VERSION) } else { $REQUIRED_API[0] } } sub _minimum_pandoc_version_for_api { my $api = shift; my $version; foreach (grep { $_ % 2} 0 .. @REQUIRED_API) { # 1,3,... if ($api->match($REQUIRED_API[$_]) ) { if (!$version or $version > $REQUIRED_API[$_-1]) { $version = $REQUIRED_API[$_-1] } } } if (!$version and $api >= $PANDOC_API_MIN) { $PANDOC_BIN_MIN; } else { return $version; } } sub _minimum_pandoc_api_for { my $version = _as_pandoc_version(shift); return if @$version <= 1; # require major.minor foreach (grep { $_ % 2} 0 .. @REQUIRED_API) { # 1,3,... if ($version->match($REQUIRED_API[$_-1]) ) { return $REQUIRED_API[$_]; } } # required version is newer than any known version # return the latest known api version and hope it has not changed if ($version > $REQUIRED_API[0]) { return $REQUIRED_API[1]; } return $version >= $PANDOC_BIN_MIN ? $PANDOC_API_MIN : undef; } our %ELEMENTS = ( # BLOCK ELEMENTS Plain => [ Block => 'content' ], Para => [ Block => 'content' ], CodeBlock => [ Block => qw(attr content) ], RawBlock => [ Block => qw(format content) ], BlockQuote => [ Block => 'content' ], OrderedList => [ Block => qw(attr content/items) ], BulletList => [ Block => 'content/items' ], DefinitionList => [ Block => 'content/items:[DefinitionPair]' ], Header => [ Block => qw(level attr content) ], HorizontalRule => ['Block'], Table => [ Block => qw(caption alignment widths headers rows) ], Div => [ Block => qw(attr content) ], Null => ['Block'], LineBlock => [ Block => qw(content) ], # INLINE ELEMENTS Str => [ Inline => 'content' ], Emph => [ Inline => 'content' ], Strong => [ Inline => 'content' ], Strikeout => [ Inline => 'content' ], Superscript => [ Inline => 'content' ], Subscript => [ Inline => 'content' ], SmallCaps => [ Inline => 'content' ], Quoted => [ Inline => qw(type content) ], Cite => [ Inline => qw(citations:[Citation] content) ], Code => [ Inline => qw(attr content) ], Space => ['Inline'], SoftBreak => ['Inline'], LineBreak => ['Inline'], Math => [ Inline => qw(type content) ], RawInline => [ Inline => qw(format content) ], Link => [ Inline => qw(attr content target) ], Image => [ Inline => qw(attr content target) ], Note => [ Inline => 'content' ], Span => [ Inline => qw(attr content) ], # METADATA ELEMENTS MetaBool => [ Meta => 'content' ], MetaString => [ Meta => 'content' ], MetaMap => [ Meta => 'content' ], MetaInlines => [ Meta => 'content' ], MetaList => [ Meta => 'content' ], MetaBlocks => [ Meta => 'content' ], # TYPE KEYWORDS map { $_ => ['Keyword'] } qw(DefaultDelim Period OneParen TwoParens SingleQuote DoubleQuote DisplayMath InlineMath AuthorInText SuppressAuthor NormalCitation AlignLeft AlignRight AlignCenter AlignDefault DefaultStyle Example Decimal LowerRoman UpperRoman LowerAlpha UpperAlpha) ); use parent 'Exporter'; our @EXPORT = ( keys %ELEMENTS, qw(Document attributes metadata citation pandoc_version pandoc_json pandoc_query) ); our @EXPORT_OK = ( @EXPORT, 'element' ); # create constructor functions foreach my $name ( keys %ELEMENTS ) { no strict 'refs'; ## no critic my ( $parent, @accessors ) = @{ $ELEMENTS{$name} }; my $numargs = scalar @accessors; my @parents = map { "Pandoc::Document::$_" } ($parent); $parent = join ' ', map { "Pandoc::Document::$_" } $parent, map { 'AttributesRole' } grep { $_ eq 'attr' } @accessors; ## no critic (ProhibitStringyEval) eval "package Pandoc::Document::$name; our \@ISA = qw($parent);"; *{ __PACKAGE__ . "::$name" } = Scalar::Util::set_prototype( sub { croak "$name expects $numargs arguments, but given " . scalar @_ if @_ != $numargs; my $self = bless { t => $name, c => ( @_ == 1 ? $_[0] : [@_] ) }, "Pandoc::Document::$name"; $self->set_content(@_); $self; }, '$' x $numargs ); for ( my $i = 0 ; $i < @accessors ; $i++ ) { my $member = @accessors == 1 ? "\$e->{c}" : "\$e->{c}->[$i]"; my $code = "my \$e = shift; $member = ( 1 == \@_ ? \$_[0] : [\@_] ) if \@_; return"; # auto-bless on access via accessor (TODO: move to constructor?) $code .= $accessors[$i] =~ s/:\[(.+)\]$// ? " [ map { bless \$_, 'Pandoc::Document::$1' } \@{$member} ];" : " $member;"; for ( split '/', $accessors[$i] ) { ## no critic *{"Pandoc::Document::${name}::$_"} = eval "sub { $code }"; } } } sub element { my $name = shift; no strict 'refs'; # croak "undefined element" unless defined $name; croak "unknown element $name" unless $ELEMENTS{$name}; &$name(@_); } sub Document { my $from_json; my $arg = do { if ( @_ == 1 ) { $from_json = 1; my $reftype = reftype $_[0] // ''; if ( $reftype eq 'ARRAY') { # old JSON format { meta => $_[0]->[0]->{unMeta}, blocks => $_[0]->[1], api_version => 1.16, } } elsif ( $reftype eq 'HASH' ) { $_[0] } else { croak 'Document: expect array or hash reference' } } elsif ( @_ == 2 ) { # \%meta, \@blocks { meta => $_[0], blocks => $_[1] } } elsif ( @_ % 2 ) { # odd number of args croak "Document: too many or ambiguous arguments"; } else { # even number of args: api_version as named parameter { meta => shift, blocks => shift, @_ } } }; # prefer haskell-style key but accept perl-style and abbreviated key my $api_version = $arg->{'pandoc-api-version'} // $arg->{pandoc_api_version} // $arg->{api_version}; # We copy values here because $arg may not be a pure AST representation my $doc = bless { blocks => ( $arg->{blocks} // [] ) }, 'Pandoc::Document'; # unblessed metadata in internal format can only come from JSON my $meta = $arg->{meta} // {}; if ($from_json) { croak "Document metadata must be a hash" unless 'HASH' eq reftype $meta; $doc->{meta} = bless { map { $_ => _bless_pandoc_element( $meta->{$_} ) } keys %$meta }, 'Pandoc::Document::Metadata'; } else { # otherwise allow user-friendly upgrade via 'metadata' function $doc->meta($meta) } if (!defined $api_version and defined $arg->{pandoc_version}) { $doc->pandoc_version($arg->{pandoc_version}); } else { $doc->api_version($api_version // $REQUIRED_API[1]); } walk $doc, \&_bless_pandoc_element; return $doc; } # internal helper method sub _bless_pandoc_element { my $e = shift; return $e unless ref $e; return $e if blessed $e and $e->isa('Pandoc::Document::Element'); # TODO: run recursively via set_content (don't require 'walk') if ( 'MetaMap' eq $e->{t} ) { for my $v ( values %{ $e->{c} } ) { _bless_pandoc_element( $v ); } } bless $e, 'Pandoc::Document::' . $e->{t}; $e->upgrade($e) if $e->can('upgrade'); return $e; } # specific accessors sub Pandoc::Document::DefinitionPair::term { $_[0]->[0] } sub Pandoc::Document::DefinitionPair::definitions { $_[0]->[1] } # additional functions sub attributes($) { my $e = Span(['',[],[]],[]); # to make use of AttributesRole $e->keyvals(@_); return $e->attr; } sub citation($) { Pandoc::Document::Citation->new( @_ ) } # XXX: must require rather than use Pandoc::Metadata # or its attempt to use Pandoc::Elements will result in a broken state. require Pandoc::Metadata; sub metadata($); ## no critic sub metadata($) { ## no critic my $value = shift; if ( !ref $value ) { MetaString($value // '') } elsif ( JSON::is_bool($value) ) { MetaBool($value) } elsif ( blessed($value) ) { if ( $value->can('is_meta') and $value->is_meta ) { $value } elsif ( $value->can('is_inline') and $value->is_inline ) { MetaInlines([ $value ]) } elsif ( $value->can('is_block') and $value->is_block ) { MetaBlocks([ $value ]) } elsif ( $value->isa('Pandoc::Document::Metadata') ) { MetaMap( { map { $_ => $value->{$_} } keys %$value } ) } else { MetaString("$value") } } elsif ( reftype $value eq 'ARRAY' ) { MetaList( [ map { metadata $_ } @$value ] ) } elsif ( reftype $value eq 'HASH' ) { MetaMap( { map { $_ => metadata $value->{$_} } keys %$value } ) } else { MetaString("$value") } } sub pandoc_json($) { shift if $_[0] =~ /^Pandoc::/; my $ast = eval { decode_json( $_[0] ) }; if ($@) { $@ =~ s/ at [^ ]+Elements\.pm line \d+//; chomp $@; croak $@; } return Document $ast; } *pandoc_query = *Pandoc::Walker::query; # document element packages { package Pandoc::Document; use strict; use Carp 'croak'; use Scalar::Util qw(blessed reftype); use Pandoc; our $VERSION = '0.04'; our @ISA = ('Pandoc::Document::Element'); sub blocks; sub name { 'Document' } sub meta { if (@_ > 1) { croak "document metadata must be a hash" unless 'HASH' eq reftype $_[1]; my $map = Pandoc::Elements::metadata($_[1])->content; $_[0]->{meta} = bless $map, 'Pandoc::Document::Metadata'; } $_[0]->{meta}; } sub content { $_[0]->{blocks} = $_[1] if @_ > 1; $_[0]->{blocks}; } *blocks = \&content; sub is_document { 1 } sub as_block { bless { t => 'Div', c => [ {}, $_[0]->{blocks} ] }, 'Pandoc::Document::Div'; } sub value { shift->meta->value(@_); } *metavalue = \&value; sub string { join '', map { $_->string } @{$_[0]->content} } sub api_version { my $self = shift; if ( @_ ) { my $version = Pandoc::Version->new(shift); croak "api_version must be >= $PANDOC_API_MIN" if $version < $PANDOC_API_MIN; croak "api_version must have major and minor part" if @$version < 2; $self->{'pandoc-api-version'} = $version; } return $self->{'pandoc-api-version'}; } *pandoc_version = \&Pandoc::Elements::pandoc_version; sub outline { my ($self, $depth) = @_; _sections( [@{$self->blocks}], $depth ); } sub _sections { my ($list, $depth) = @_; my (@blocks, @sections); # everything up to the first Header while (@$list) { if ($list->[0]->name eq 'Header') { last if !$depth or $depth >= $list->[0]->level; } push @blocks, shift @$list; } # divide into sections while (@$list) { my $header = shift @$list; my $level = $header->level; my @content; while (@$list) { if ($list->[0]->name eq 'Header') { last if $list->[0]->level <= $level; } push @content, shift @$list; } my $s = ($depth and $depth < $level) ? { blocks => \@content } : _sections(\@content,$depth); push @sections, { header => $header, %$s }; } return { blocks => \@blocks, sections => \@sections }; } sub to_pandoc { my ($self, @args) = @_; my $pandoc = (@args and blessed($args[0]) and $args[0]->isa('Pandoc')) ? shift(@args) : pandoc; my $api_version = $self->api_version; # save $self->pandoc_version( $pandoc->version ); my $in = $self->to_json; $self->api_version($api_version); # restore $pandoc->run( [ -f => 'json', @args ], { in => \$in, out => \my $out } ); return $out; } foreach my $format (qw(markdown latex html rst plain)) { no strict 'refs'; *{ __PACKAGE__ . "::to_$format" } = sub { shift()->to_pandoc( @_, '-t' => $format ); } } } { package Pandoc::Document::Keyword; our @ISA = ('Pandoc::Document::Element'); } { package Pandoc::Document::Element; use strict; use warnings; our $VERSION = $Pandoc::Document::VERSION; use JSON (); use Scalar::Util qw(reftype blessed); use Pandoc::Walker (); use Pandoc::Selector; use subs qw(walk query transform); # Silence syntax warnings sub to_json { JSON->new->utf8->canonical->convert_blessed->encode( $_[0] ); } sub TO_JSON { # Run everything thru this method so arrays/hashes are cloned # and objects without TO_JSON methods are stringified. # Required to ensure correct scalar types for Pandoc. # There is no easy way in Perl to tell if a scalar value is already a string or number, # so we stringify all scalar values and numify/boolify as needed afterwards. my ( $ast, $maybe_blessed ) = @_; if ( $maybe_blessed && blessed $ast ) { return $ast if $ast->can('TO_JSON'); # JSON.pm will convert # may have overloaded stringification! Should we check? # require overload; # return "$ast" if overload::Method($ast, q/""/) or overload::Method($ast, q/0+/); # carp "Non-stringifiable object $ast"; return "$ast"; } elsif ( 'ARRAY' eq reftype $ast ) { return [ map { ref($_) ? TO_JSON( $_, 1 ) : "$_"; } @$ast ]; } elsif ( 'HASH' eq reftype $ast ) { my %ret = %$ast; while ( my ( $k, $v ) = each %ret ) { $ret{$k} = ref($v) ? TO_JSON( $v, 1 ) : "$v"; } return \%ret; } else { return "$ast" } } sub name { $_[0]->{t} } sub content { my $e = shift; $e->set_content(@_) if @_; $e->{c} } sub set_content { # TODO: document this my $e = shift; $e->{c} = @_ == 1 ? $_[0] : [@_] } sub is_document { 0 } sub is_block { 0 } sub is_inline { 0 } sub is_meta { 0 } sub as_block { bless { t => 'Null', c => [] }, 'Pandoc::Document::Null'; } *walk = *Pandoc::Walker::walk; *query = *Pandoc::Walker::query; *transform = *Pandoc::Walker::transform; sub string { # TODO: fix issue #4 to avoid this duplication if ( $_[0]->name =~ /^(Str|Code|CodeBlock|Math|MetaString)$/ ) { return $_[0]->content; } elsif ( $_[0]->name =~ /^(LineBreak|SoftBreak|Space)$/ ) { return ' '; } join '', @{ $_[0]->query( { 'Str|Code|CodeBlock|Math|MetaString' => sub { $_->content }, 'LineBreak|Space|SoftBreak' => sub { ' ' }, } ); }; } sub match { my $self = shift; my $selector = blessed $_[0] ? shift : Pandoc::Selector->new(shift); $selector->match($self); } } { package Pandoc::Document::AttributesRole; use Hash::MultiValue; use Scalar::Util qw(reftype blessed); use Carp qw(croak); sub id { $_[0]->attr->[0] = defined $_[1] ? "$_[1]" : "" if @_ > 1; $_[0]->attr->[0] } sub classes { my $e = shift; croak 'Method classes() is not a setter' if @_; warn "->classes is deprecated. Use [ split ' ', \$e->class ] instead\n"; $e->attr->[1] } sub class { my $e = shift; if (@_) { $e->attr->[1] = [ grep { $_ ne '' } map { split qr/\s+/, $_ } map { (ref $_ and reftype $_ eq 'ARRAY') ? @$_ : $_ } @_ ]; } join ' ', @{$e->attr->[1]} } sub add_attribute { my ($e, $key, $value) = @_; if ($key eq 'id') { $e->id($value); } elsif ($key eq 'class') { $value //= ''; $value = ["$value"] unless (reftype $value // '') eq 'ARRAY'; push @{$e->attr->[1]}, grep { $_ ne '' } map { split qr/\s+/, $_ } @$value; } else { push @{$e->attr->[2]}, [ $key, "$value" ]; } } sub keyvals { my $e = shift; if (@_) { my $attrs = @_ == 1 ? shift : Hash::MultiValue->new(@_); unless (blessed $attrs and $attrs->isa('Hash::MultiValue')) { $attrs = Hash::MultiValue->new(%$attrs); } $e->attr->[1] = [] if exists $attrs->{class}; $e->attr->[2] = []; $attrs->each(sub { $e->add_attribute(@_) }); } my @h; push @h, id => $e->id if $e->id ne ''; push @h, class => $e->class if @{$e->attr->[1]}; Hash::MultiValue->new( @h, map { @$_ } @{$e->attr->[2]} ); } } { package Pandoc::Document::Block; our $VERSION = $PANDOC::Document::VERSION; our @ISA = ('Pandoc::Document::Element'); sub is_block { 1 } sub as_block { $_[0] } sub null { # TODO: document this (?) %{$_[0]} = (t => 'Null', c => []); bless $_[0], 'Pandoc::Document::Null'; } } { package Pandoc::Document::Inline; our $VERSION = $PANDOC::Document::VERSION; our @ISA = ('Pandoc::Document::Element'); sub is_inline { 1 } sub as_block { bless { t => 'Plain', c => [ $_[0] ] }, 'Pandoc::Document::Plain'; } } { package Pandoc::Document::LinkageRole; our $VERSION = $PANDOC::Document::VERSION; for my $Element (qw[ Link Image ]) { no strict 'refs'; #no critic unshift @{"Pandoc::Document::${Element}::ISA"}, __PACKAGE__; # no critic } sub url { my $e = shift; $e->{c}->[-1][0] = shift if @_; return $e->{c}->[-1][0] //= ""; } sub title { my $e = shift; $e->{c}->[-1][1] = shift if @_; return $e->{c}->[-1][1] //= ""; } sub upgrade { # prepend attributes to old-style ast unshift @{ $_[0]->{c} }, [ "", [], [] ] if 2 == @{ $_[0]->{c} }; } } { package Pandoc::Document::Citation; our $VERSION = $PANDOC::Document::VERSION; use Carp qw[ carp croak ]; my %props = ( id => { key => 'citationId', default => '"missing"' }, prefix => { key => 'citationPrefix', default => '[]' }, suffix => { key => 'citationSuffix', default => '[]' }, num => { key => 'citationNoteNum', default => '0' }, hash => { key => 'citationHash', default => '1' }, mode => { key => 'citationMode', default => q{ bless( { t => 'NormalCitation', c => [] }, 'Pandoc::Document::NormalCitation' ) }, }, ); { my $template = <<'END_OF_TEMPLATE'; #line 1 "method [[[method]]]()" package Pandoc::Document::Citation; sub [[[method]]] { my $self = shift; if ( @_ ) { $self->{[[[key]]]} = [[[coerce]]] ( shift // [[[default]]] ); } return [[[coerce]]] ( $self->{[[[key]]]} //= [[[default]]] ); } no warnings 'once'; *[[[alias]]] = \&[[[method]]]; 1; END_OF_TEMPLATE while ( my ( $name, $prop ) = each %props ) { $prop->{name} = $name; $prop->{method} = "Pandoc::Document::Citation::$name"; $prop->{alias} = "Pandoc::Document::Citation::$prop->{key}"; $prop->{coerce} = $prop->{default} =~ /^\d$/ ? '0 +' : $prop->{default} =~ /^"/ ? '"" .' : ""; { ( my $source = $template ) =~ s/\Q[[[\E(\w+)\Q]]]\E/$prop->{$1}/g; local $@; ## no critic eval $source || croak $@ . $source; } } } my %accessors = map { ; $_->{name} => $_->{key} } values %props; sub new { my ( $class, $arg ) = @_; my $self = bless {}, $class; while ( my ( $name, $key ) = each %accessors ) { # coerce on access $self->$name( $arg->{$key} // $arg->{$name} ); } return $self; } no warnings 'once'; *TO_JSON = \&Pandoc::Document::Element::TO_JSON; } # Special TO_JSON methods to coerce data to int/number/Boolean as appropriate # and to downgrade document model depending on pandoc_version sub Pandoc::Document::to_json { my ($self) = @_; local $Pandoc::Elements::PANDOC_VERSION = $Pandoc::Elements::PANDOC_VERSION // $self->pandoc_version; return Pandoc::Document::Element::to_json( $self->TO_JSON ); } sub Pandoc::Document::TO_JSON { my ( $self ) = @_; return $self->api_version >= 1.17 ? { %$self } : [ { unMeta => $self->{meta} }, $self->{blocks} ] } sub Pandoc::Document::SoftBreak::TO_JSON { if ( pandoc_version() < '1.16' ) { return { t => 'Space', c => [] }; } else { return { t => 'SoftBreak', c => [] }; } } sub Pandoc::Document::LinkageRole::TO_JSON { my $ast = Pandoc::Document::Element::TO_JSON( $_[0] ); if ( pandoc_version() < 1.16 ) { # remove attributes $ast->{c} = [ @{ $ast->{c} }[ 1, 2 ] ]; } return $ast; } sub Pandoc::Document::Header::TO_JSON { my $ast = Pandoc::Document::Element::TO_JSON( $_[0] ); # coerce heading level to int $ast->{c}[0] = int( $ast->{c}[0] ); return $ast; } sub Pandoc::Document::OrderedList::TO_JSON { my $ast = Pandoc::Document::Element::TO_JSON( $_[0] ); # coerce first item number to int $ast->{c}[0][0] = int( $ast->{c}[0][0] ); return $ast; } sub Pandoc::Document::Table::TO_JSON { my $ast = Pandoc::Document::Element::TO_JSON( $_[0] ); # coerce column widths to numbers (floats) $_ += 0 for @{ $ast->{c}[2] }; # faster than map return $ast; } sub Pandoc::Document::Cite::TO_JSON { my $ast = Pandoc::Document::Element::TO_JSON( $_[0] ); for my $citation ( @{ $ast->{c}[0] } ) { for my $key (qw[ citationHash citationNoteNum ]) { # coerce to int $citation->{$key} = int( $citation->{$key} ); } } return $ast; } sub Pandoc::Document::LineBlock::TO_JSON { my $ast = Pandoc::Document::Element::TO_JSON( $_[0] ); my $content = $ast->{c}; for my $line ( @$content ) { # Convert spaces at the beginning of each line # to Unicode non-breaking spaces, because pandoc does. next unless @$line and $line->[0]->{t} eq 'Str'; $line->[0]->{c} =~ s{^(\x{20}+)}{ "\x{a0}" x length($1) }e; } return $ast if pandoc_version() >= 1.18; my $c = [ map { ; @$_, LineBreak() } @{$content} ]; pop @$c; # remove trailing line break return Para( $c )->TO_JSON; } 1; __END__ =encoding utf-8 =head1 NAME Pandoc::Elements - create and process Pandoc documents =begin markdown # STATUS [![Unix Build Status](https://travis-ci.org/nichtich/Pandoc-Elements.svg)](https://travis-ci.org/nichtich/Pandoc-Elements) [![Windows Build status](https://ci.appveyor.com/api/projects/status/pb7vdd14xml9ho43?svg=true)](https://ci.appveyor.com/project/nichtich/pandoc-elements) [![Coverage Status](https://coveralls.io/repos/nichtich/Pandoc-Elements/badge.svg)](https://coveralls.io/r/nichtich/Pandoc-Elements) [![Kwalitee Score](http://cpants.cpanauthors.org/dist/Pandoc-Elements.png)](http://cpants.cpanauthors.org/dist/Pandoc-Elements) [![Code Climate Issue Count](https://codeclimate.com/github/nichtich/Pandoc-Elements/badges/issue_count.svg)](https://codeclimate.com/github/nichtich/Pandoc-Elements) =end markdown =head1 SYNOPSIS The output of this script C use Pandoc::Elements; use JSON; print Document( { title => MetaInlines [ Str "Greeting" ] }, [ Header( 1, attributes { id => 'top' }, [ Str 'Hello' ] ), Para [ Str 'Hello, world!' ], ], api_version => '1.17.0.4' )->to_json; can be converted for instance to HTML via ./hello.pl | pandoc -f json -t html5 --standalone an equivalent Pandoc Markdown document would be % Greeting # Gruß {.de} Hello, world! =head1 DESCRIPTION Pandoc::Elements provides utility functions to parse, serialize, and modify abstract syntax trees (AST) of L documents. Pandoc can convert this data structure to many other document formats, such as HTML, LaTeX, ODT, and ePUB. See also module L, command line script L, and the internal modules L and L. =head1 PANDOC VERSIONS The Pandoc document model is defined in file L as part of Haskell package L. Pandoc::Elements is compatible with pandoc-types 1.12.3 (released with pandoc 1.12.1) up to I pandoc-types-1.17.0.4 (first releases with pandoc 1.18). JSON output of all pandoc releases since 1.12.1 can be parsed with function C, the L constructor or method C of module L. The AST is always upgraded to pandoc-types 1.17 and downgraded to another api version on serialization with C. To determine the api version required by a version of pandoc executable since version 1.18 execute pandoc with the C<--version> option and check which version of the C library pandoc was compiled with. Beginning with version 1.18 pandoc will not decode a JSON AST representation unless the major and minor version numbers (Document method C) match those built into that version of pandoc. The following changes in pandoc document model have been implemented: =over =item pandoc-types 1.17, released for pandoc 1.18, introduced the L element and modified representation of the root L element. =item pandoc-types 1.16, released with pandoc 1.16, introduced attributes to L and L elements =item pandoc-types 1.12.3, released with pandoc 1.12.1, modified the representation of elements to objects with field C and C. This is also the internal representation of documents used in this module. =back =head1 FUNCTIONS The following functions and keywords are exported by default: =over =item Constructors for all Pandoc document element (L such as C and L such as C, L and the L). =item L such as C and C to be used as types in other document elements. =item The following helper functions C, C, C, C, C, and C. =back =head2 pandoc_json $json Parse a JSON string, as emitted by pandoc in JSON format. This is the reverse to method C but it can read both old (before Pandoc 1.16) and new format. =head2 attributes { key => $value, ... } Maps a hash reference or instance of L into the internal structure of Pandoc attributes. The special keys C (string), and C (string or array reference with space-separated class names) are recognized. See L for details. =head2 citation { ... } A citation as part of document element L must be a hash reference with fields C (string), C (list of L) C (list of L), C (one of C, C, C), C (integer), and C (integer). The helper method C can be used to construct such a hash by filling in default values and optionally using shorter field names (C, C, C, C, C, and C): citation { id => 'foo', prefix => [ Str "see" ], suffix => [ Str "p.", Space, Str "42" ] } # in Pandoc Markdown [see @foo p. 42] The values returned by this function, as well as any citations contained in document objects returned by C, are blessed hashrefs with getter/setter accessors corresponding to both the full and short field names, so that e.g. C<< $citation->citationId(...) >> and C<< $citation->id(...) >> get or set the same value. =head2 pandoc_version( [ $document ] ) Return a L object with expected version number of pandoc executable to be used for serializing documents with L. If a L is given as argument, the minimal pandoc release version compatible with its api version is returned. Without argument, package variable C<$PANDOC_VERSION> is checked for a preferred pandoc release. By default this variable is set from an environment variable of same name. If no preferred pandoc release has been specified, the function returns version 1.18 because this is the first pandoc release compatible with most recent api version supported by this module. See also method C of module L to get the current version of pandoc executable on your system. =head2 element( $name => $content ) Create a Pandoc document element of arbitrary name. This function is only exported on request. =head1 ELEMENTS AND METHODS Document elements are encoded as Perl data structures equivalent to the JSON structure, emitted with pandoc output format C. This JSON structure is subject to minor changes between L. All elements are blessed objects that provide L (all elements), L (elements with attributes), and additional element-specific methods. =head2 COMMON METHODS =head3 to_json Return the element as JSON encoded string. The following are equivalent: $element->to_json; JSON->new->utf8->canonical->convert_blessed->encode($element); The serialization format can be adjusted to different L with module and environment variable C or with Document element properties C and C. When writing filters you can normally just rely on the api version value obtained from pandoc, since pandoc expects to receive the same JSON format as it emits. =head3 name Return the name of the element, e.g. "Para" for a L. =head3 content Return the element content. For most elements (L, L, L...) the content is an array reference with child elements. Other elements consist of multiple parts; for instance the L element has attributes (C, C, C, C, C) a link text (C) and a link target (C) with C and C. =head3 is_block True if the element is a L<Block element|/BLOCK ELEMENTS> =head3 is_inline True if the element is an inline L<Inline element|/INLINE ELEMENTS> =head3 is_meta True if the element is a L<Metadata element|/METADATA ELEMENTS> =head3 is_document True if the element is a L<Document element|/DOCUMENT ELEMENT> =head3 as_block Return the element unmodified if it is a block element or wrapped in a L<Plain|/Plain> or L<Div|/Div> otherwise. =head3 match( $selector ) Check whether the element matches a given L<Pandoc::Selector> (given as instance or string). =head3 walk(...) Walk the element tree with L<Pandoc::Walker> =head3 query(...) Query the element to extract results with L<Pandoc::Walker> =head3 transform(...) Transform the element tree with L<Pandoc::Walker> =head3 string Returns a concatenated string of element content, leaving out all formatting. =head2 ATTRIBUTE METHODS Some elements have attributes which can be an identifier, ordered class names and ordered key-value pairs. Elements with attributes provide the following methods: =head3 attr Get or set the attributes in Pandoc internal structure: [ $id, [ @classes ], [ [ key => $value ], ... ] ] See helper function L<attributes|/attributes-key-value> to create this structure. =head3 keyvals Get all attributes (id, class, and key-value pairs) as new L<Hash::MultiValue> instance, or replace I<all> key-value pairs plus id and/or class if these are included as field names. All class fields are split by whitespaces. $e->keyvals # return new Hash::MultiValue $e->keyvals( $HashMultiValue ) # update by instance of Hash::MultiValue $e->keyvals( key => $value, ... ) # update by list of key-value pairs $e->keyvals( \%hash ) # update by hash reference $e->keyvals( { } ) # remove all key-value pairs $e->keyvals( id => '', class => '' ) # remove all key-value pairs, id, class =head3 id Get or set the identifier. See also L<Pandoc::Filter::HeaderIdentifiers> for utility functions to handle L<Header|/Header> identifiers. =head3 class Get or set the list of classes, separated by whitespace. =head3 add_attribute( $name => $value ) Append an attribute. The special attribute names C<id> and C<class> set or append identifier or class, respectively. =head2 DOCUMENT ELEMENT =head3 Document Root element, consisting of metadata hash (C<meta>), document element array (C<content>=C<blocks>) and optional C<api_version>. The constructor accepts either two arguments and an optional named parameter C<api_version>: Document { %meta }, [ @blocks ], api_version => $version_string or a hash with three fields for metadata, document content, and an optional pandoc API version: { meta => { %metadata }, blocks => [ @content ], pandoc-api-version => [ $major, $minor, $revision ] } The latter form is used as pandoc JSON format since pandoc release 1.18. If no api version is given, it will be set 1.17 which was also introduced with pandoc release 1.18. A third ("old") form is accepted for compatibility with pandoc JSON format before release 1.18 and since release 1.12.1: an array with two elements for metadata and document content respectively. [ { unMeta => { %meta } }, [ @blocks ] ] The api version is set to 1.16 in this case, but older versions down to 1.12.3 used the same format. Document elements provide the following special methods in addition to L<common element methods|/COMMON METHODS>: =over =item B<api_version( [ $api_version ] )> Return the pandoc-types version (aka "pandoc-api-version") of this document as L<Pandoc::Version|Pandoc::Version> object or sets it to a new value. This version determines how method L<to_json|/to_json> serializes the document. See L</PANDOC VERSIONS> for details. =item B<pandoc_version( [ $pandoc_version ] )> Return the minimum required version of pandoc executable compatible with the api_version of this document. The following are equivalent: $doc->pandoc_version; pandoc_version( $doc ); If used as setter, sets the api version of this document to be compatible with the given pandoc version. =item B<content> or B<blocks> Get or set the array of L<block elements|/BLOCK ELEMENTS> of the document. =item B<meta( [ $metadata ] )> Get and/or set combined L<document metadata|Pandoc::Metadata>. Use method C<value> to get selected metadata fields and values. =item B<value( [ $pointer ] [ %options ] )> Get selected document metadata field value(s). See L<Pandoc::Metadata> for documentation. Can also be called as C<metavalue>, so the following are equivalent: $doc->value( ... ); $doc->meta->value( ... ); $doc->metavalue( ... ); =item B<to_pandoc( [ [ $pandoc, ] @arguments ])> Process the document with L<Pandoc> executable and return its output: $doc->to_pandoc( -o => 'doc.html' ); my $markdown = $doc->to_pandoc( -t => 'markdown' ); The first argument can optionally be an instance of L<Pandoc> to use a specific executable. =item B<to_...( [ @arguments ] )> Process the document into C<markdown> (pandoc's extended Markdown), C<latex> (LaTeX), C<html> (HTML), C<rst> (reStructuredText), or C<plain> (plain text). The following are equivalent: $doc->to_markdown( @args ); $doc->to_pandoc( @args, '-t' => 'markdown' ); =item B<outline( [ $depth ] )> Returns an outline of the document structure based on L<Header|/Header> elements. The outline is a hierarchical hash reference with the following fields: =over =item header L<Header|/Header> element (not included at the document root) =item blocks List of L<block elements|/Block elements> before the next L<Header|/Header> element (of given depth or less if a maximum depth was given) =item sections List of subsections, each having the same outline structure. =back =back =head2 BLOCK ELEMENTS =head3 BlockQuote Block quote, consisting of a list of L<blocks|/BLOCK ELEMENTS> (C<content>) BlockQuote [ @blocks ] =head3 BulletList Unnumbered list of items (C<content>=C<items>), each a list of L<blocks|/BLOCK ELEMENTS> BulletList [ [ @blocks ] ] =head3 CodeBlock Code block (literal string C<content>) with attributes (C<attr>, C<id>, C<class>, C<classes>, C<keyvals>) CodeBlock $attributes, $content =head3 DefinitionList Definition list, consisting of a list of pairs (C<content>=C<items>), each a term (C<term>, a list of L<inlines|/INLINE ELEMENTS>) and one or more definitions (C<definitions>, a list of L<blocks|/BLOCK ELEMENTS>). DefinitionList [ @definitions ] # each item in @definitions being a pair of the form [ [ @inlines ], [ @blocks ] ] =head3 Div Generic container of L<blocks|/BLOCK ELEMENTS> (C<content>) with attributes (C<attr>, C<id>, C<class>, C<classes>, C<keyvals>). Div $attributes, [ @blocks ] =head3 Header Header with C<level> (integer), attributes (C<attr>, C<id>, C<class>, C<classes>, C<keyvals>), and text (C<content>, a list of L<inlines|/INLINE ELEMENTS>). Header $level, $attributes, [ @inlines ] =head3 HorizontalRule Horizontal rule HorizontalRule =head3 LineBlock List of lines (C<content>), each a list of L<inlines|/INLINE ELEMENTS>. LineBlock [ @lines ] This element was added in pandoc 1.18. Before it was represented L<Para|/Para> elements with embedded L<LineBreak|/LineBreak> elements. This old serialization form can be enabled by setting C<$PANDOC_VERSION> package variable to a lower version number. =head3 Null Nothing Null =head3 OrderedList Numbered list of items (C<content>=C<items>), each a list of L<blocks|/BLOCK ELEMENTS>), preceded by list attributes (start number, numbering style, and delimiter). OrderedList [ $start, $style, $delim ], [ [ @blocks ] ] Supported styles are C<DefaultStyle>, C<Example>, C<Decimal>, C<LowerRoman>, C<UpperRoman>, C<LowerAlpha>, and C<UpperAlpha>. Supported delimiters are C<DefaultDelim>, C<Period>, C<OneParen>, and C<TwoParens>. =head3 Para Paragraph, consisting of a list of L<Inline elements|/INLINE ELEMENTS> (C<content>). Para [ $elements ] =head3 Plain Plain text, not a paragraph, consisting of a list of L<Inline elements|/INLINE ELEMENTS> (C<content>). Plain [ @inlines ] =head3 RawBlock Raw block with C<format> and C<content> string. RawBlock $format, $content =head3 Table Table, with C<caption>, column C<alignments>, relative column C<widths> (0 = default), column C<headers> (each a list of L<blocks|/BLOCK ELEMENTS>), and C<rows> (each a list of lists of L<blocks|/BLOCK ELEMENTS>). Table [ @inlines ], [ @alignments ], [ @width ], [ @headers ], [ @rows ] Possible alignments are C<AlignLeft>, C<AlignRight>, C<AlignCenter>, and C<AlignDefault>. An example: Table [Str "Example"], [AlignLeft,AlignRight], [0.0,0.0], [[Plain [Str "name"]] ,[Plain [Str "number"]]], [[[Plain [Str "Alice"]] ,[Plain [Str "42"]]] ,[[Plain [Str "Bob"]] ,[Plain [Str "23"]]]]; =head2 INLINE ELEMENTS =head3 Cite Citation, a list of C<citations> and a list of L<inlines|/INLINE ELEMENTS> (C<content>). See helper function L<citation|/citation> to construct citations. Cite [ @citations ], [ @inlines ] =head3 Code Inline code, a literal string (C<content>) with attributes (C<attr>, C<id>, C<class>, C<classes>, C<keyvals>) Code attributes { %attr }, $content =head3 Emph Emphasized text, a list of L<inlines|/INLINE ELEMENTS> (C<content>). Emph [ @inlines ] =head3 Image Image with alt text (C<content>, a list of L<inlines|/INLINE ELEMENTS>) and C<target> (list of C<url> and C<title>) with attributes (C<attr>, C<id>, C<class>, C<classes>, C<keyvals>). Image attributes { %attr }, [ @inlines ], [ $url, $title ] Serializing the attributes is disabled in api version less then 1.16. =head3 LineBreak Hard line break LineBreak =head3 Link Hyperlink with link text (C<content>, a list of L<inlines|/INLINE ELEMENTS>) and C<target> (list of C<url> and C<title>) with attributes (C<attr>, C<id>, C<class>, C<classes>, C<keyvals>). Link attributes { %attr }, [ @inlines ], [ $url, $title ] Serializing the attributes is disabled in api version less then 1.16. =head3 Math TeX math, given as literal string (C<content>) with C<type> (one of C<DisplayMath> and C<InlineMath>). Math $type, $content =head3 Note Footnote or Endnote, a list of L<blocks|/BLOCK ELEMENTS> (C<content>). Note [ @blocks ] =head3 Quoted Quoted text with quote C<type> (one of C<SingleQuote> and C<DoubleQuote>) and a list of L<inlines|/INLINE ELEMENTS> (C<content>). Quoted $type, [ @inlines ] =head3 RawInline Raw inline with C<format> (a string) and C<content> (a string). RawInline $format, $content =head3 SmallCaps Small caps text, a list of L<inlines|/INLINE ELEMENTS> (C<content>). SmallCaps [ @inlines ] =head3 SoftBreak Soft line break SoftBreak This element was added in pandoc 1.16 as a matter of editing convenience to preserve line breaks (as opposed to paragraph breaks) from input source to output. If you are going to feed a document containing C<SoftBreak> elements to Pandoc E<lt> 1.16 you will have to set the package variable or environment variable C<PANDOC_VERSION> to 1.15 or below. =head3 Space Inter-word space Space =head3 Span Generic container of L<inlines|/INLINE ELEMENTS> (C<content>) with attributes (C<attr>, C<id>, C<class>, C<classes>, C<keyvals>). Span attributes { %attr }, [ @inlines ] =head3 Str Plain text, a string (C<content>). Str $content =head3 Strikeout Strikeout text, a list of L<inlines|/INLINE ELEMENTS> (C<content>). Strikeout [ @inlines ] =head3 Strong Strongly emphasized text, a list of L<inlines|/INLINE ELEMENTS> (C<content>). Strong [ @inlines ] =head3 Subscript Subscripted text, a list of L<inlines|/INLINE ELEMENTS> (C<content>). Supscript [ @inlines ] =head3 Superscript Superscripted text, a list of L<inlines|/INLINE ELEMENTS> (C<content>). Superscript [ @inlines ] =head2 METADATA ELEMENTS See L<Pandoc::Metadata> for documentation of metadata elements C<MetaBool>, C<MetaString>, C<MetaMap>, C<MetaInlines>, C<MetaList>, and C<MetaBlocks>. Helper function C<metadata> can be used to convert scalars, hash references, array references, and Pandoc Inline/Block elements into metadata elements. =head2 TYPE KEYWORDS The following document elements are only as used as type keywords in other document elements: =over =item C<SingleQuote>, C<DoubleQuote> =item C<DisplayMath>, C<InlineMath> =item C<AuthorInText>, C<SuppressAuthor>, C<NormalCitation> =item C<AlignLeft>, C<AlignRight>, C<AlignCenter>, C<AlignDefault> =item C<DefaultStyle>, C<Example>, C<Decimal>, C<LowerRoman>, C<UpperRoman>, C<LowerAlpha>, C<UpperAlpha> =item C<DefaultDelim>, C<Period>, C<OneParen>, C<TwoParens> =back =head1 SEE ALSO Perl module L<Pandoc> implements a wrapper around the pandoc executable. Similar libraries in other programming languages are listed at L<https://github.com/jgm/pandoc/wiki/Pandoc-wrappers-and-interfaces>. =head1 AUTHOR Jakob Voß E<lt>jakob.voss@gbv.deE<gt> =head1 CONTRIBUTORS Benct Philip Jonsson E<lt>bpjonsson@gmail.comE<gt> L<TakeAsk|https://github.com/TakeAsh> =head1 COPYRIGHT AND LICENSE Copyright 2014- Jakob Voß GNU General Public License, Version 2 This module is heavily based on Pandoc by John MacFarlane. =cut ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Metadata.pm�����������������������������������������������������������������������������������������100644��001750��001750�� 24716�13347276615� 17362� 0����������������������������������������������������������������������������������������������������ustar�00voj�����������������������������voj�����������������������������000000��000000��Pandoc-Elements-0.38/lib/Pandoc����������������������������������������������������������������������������������������������������������������������������������������package Pandoc::Metadata; use strict; use warnings; use 5.010001; use Pandoc::Elements; use Scalar::Util qw(blessed reftype); use JSON::PP; use Carp; # # For Pandoc::Metadata::Error # use Carp qw(shortmess longmess); # packages and methods { # key-value map of metadata fields package Pandoc::Document::Metadata; { no warnings 'once'; *to_json = \&Pandoc::Document::Element::to_json; } sub TO_JSON { return { %{ $_[0] } } } sub value { my $map = { c => shift }; Pandoc::Document::MetaMap::value( $map, @_ ) } } { # metadata element parent class package Pandoc::Document::Meta; our @ISA = ('Pandoc::Document::Element'); sub is_meta { 1 } sub value { shift->value(@_) } } # # For Pandoc::Metadata::Error # { # package Pandoc::Metadata::Error; # use overload q[""] => 'shortmess', q[%{}] => 'data', fallback => 1; # use constant { SHORTMESS => 0, LONGMESS => 1, DATA => 2 }; # sub new { # my($class, @values) = @_; # CLASS, (MESSAGE, {DATA}) # bless \@values => $class; # } # sub shortmess { shift->[SHORTMESS] } # sub longmess { shift->[LONGMESS] } # sub data { shift->[DATA] } # sub rethrow { die shift } # sub throw { shift->new( @_ )->rethrow } # } # helpers my @token_keys = qw(last_pointer ref_token plain_key key empty pointer); sub _pointer_token { state $valid_pointer_re = qr{\A (?: [^/] .* | (?: / [^/]* )* ) \z}msx; state $token_re = qr{ \A (?<_last_pointer> (?<_ref_token> (?<_plain_key> (?<_key> [^/] .* \z ) # plain "key" ) | / (?<_key> [^/]* ) # "/key" | (?<_empty> \z ) # "" -- return current element ) (?<_pointer> / .* \z | ) ) \z }msx; # set non-participating keys to undef state $defaults = { map {; "_$_" => undef } @token_keys }; my %opts = @_; $opts{_pointer} //= $opts{_full_pointer} //= $opts{pointer} //= ""; $opts{_pointer} =~ $valid_pointer_re // _bad_pointer( %opts, _error => 'pointer' ); $opts{_pointer} =~ $token_re; # guaranteed to match since validation matched! my %match = %+; unless ( grep { defined $_ } @match{qw(_plain_key _empty)} ) { $match{_key} =~ s!\~1!/!g; $match{_key} =~ s!\~0!~!g; } return (%opts, %$defaults, %match); } sub _bad_pointer { state $params_for = do { my %params_map = ( default => { msg => 'Invalid or unknown pointer reference "%s"', in => 1, _keys => ['_ref_token'], pointer => '_last_pointer' }, pointer => { msg => 'Invalid', in => 0, _keys => [], pointer => '_last_pointer', }, container => { msg => 'No list or mapping "%s"', }, key => { msg => 'Node "%s" doesn\'t correspond to any key', }, range => { msg => 'List index %s out of range', _keys => ['_key'], }, index => { msg => 'Node "%s" not a valid list index', }, ); for my $key ( keys %params_map ) { for my $params ( $params_map{$key} ) { $params = { %{ $params_map{default} }, %$params }; $params->{msg} .= ( $params->{in} ? q[ in] : "" ); $params->{keys} = [ @{ $params->{_keys} }, $params->{pointer}, '_full_pointer' ]; } } \%params_map; }; # # For Pandoc::Metadata::Error # state $data_keys = { # ( map { ; $_ => $_ } qw[element strict boolean] ), # ( map { ; $_ => "_$_" } @token_keys, qw[error] ), # ( pointer => '_full_pointer', next_pointer => '_pointer' ), # }; my ( %opts ) = @_; return undef unless $opts{strict}; $opts{_error} //= 'default'; my $params = $params_for->{ $opts{_error} }; if ( $opts{_error} eq 'container' ) { %opts = _pointer_token( %opts ); } my $msg = sprintf $params->{msg} . q[ (sub)pointer "%s" in pointer "%s"], @opts{ @{ $params->{keys} } }; # # For Pandoc::Metadata::Error # my %data; # @data{ keys %$data_keys } = @opts{ values %$data_keys }; # Pandoc::Metadata::Error->throw( shortmess($msg), longmess($msg), \%data ); croak $msg; } # methods sub _value_args { my $content = shift->{c}; my ($pointer, %opts) = @_ % 2 ? @_ : (undef, @_); $opts{_pointer} = $pointer // $opts{_pointer} // $opts{pointer} // ''; $opts{_full_pointer} //= $opts{_pointer}; return ($content, %opts); } sub Pandoc::Document::MetaString::value { my ($content, %opts) = _value_args(@_); if ($opts{_pointer} ne '') { _bad_pointer(%opts, _error => 'container'); } else { $content; } } sub Pandoc::Document::MetaBool::set_content { $_[0]->{c} = $_[1] && $_[1] ne 'false' && $_[1] ne 'FALSE' ? 1 : 0; } sub Pandoc::Document::MetaBool::TO_JSON { return { t => 'MetaBool', c => $_[0]->{c} ? JSON::true() : JSON::false(), }; } sub Pandoc::Document::MetaBool::value { my ($content, %opts) = _value_args(@_); if ($opts{_pointer} ne '') { _bad_pointer(%opts, _error => 'container'); } elsif (($opts{boolean} // '') eq 'JSON::PP') { $content ? JSON::true() : JSON::false(); } else { $content ? 1 : 0; } } sub Pandoc::Document::MetaMap::value { my ($map, %opts) = _value_args(@_); %opts = _pointer_token(%opts); if (defined $opts{_empty}) { return { map { $_ => $map->{$_}->value(%opts) } keys %$map }; } elsif (exists($map->{$opts{_key}})) { return $map->{$opts{_key}}->value(%opts); } else { _bad_pointer( %opts, _error => 'key'); } } sub Pandoc::Document::MetaList::value { my ($content, %opts) = _value_args(@_); %opts = _pointer_token(%opts); if ( defined $opts{_empty} ) { return [ map { $_->value(%opts) } @$content ] } elsif ($opts{_key} =~ /^[1-9][0-9]*$|^0$/) { if ( $opts{_key} > $#$content ) { return _bad_pointer( %opts, _error => 'range' ); } my $value = $content->[$opts{_key}]; return defined($value) ? $value->value(%opts) : undef; } else { return _bad_pointer( %opts, _error => 'index' ); } } sub Pandoc::Document::MetaInlines::value { my ($content, %opts) = _value_args(@_); if ($opts{_pointer} ne '') { _bad_pointer(%opts, _error => 'container'); } elsif ($opts{element} // '' eq 'keep') { $content; } else { join '', map { $_->string } @$content; } } sub Pandoc::Document::MetaBlocks::string { join "\n\n", map { $_->string } @{$_[0]->content}; } sub Pandoc::Document::MetaBlocks::value { my ($content, %opts) = _value_args(@_); if ($opts{_pointer} ne '') { _bad_pointer(%opts); } elsif ($opts{element} // '' eq 'keep') { $content; } else { $_[0]->string; } } 1; __END__ =head1 NAME Pandoc::Metadata - pandoc document metadata =head1 DESCRIPTION Document metadata such as author, title, and date can be embedded in different documents formats. Metadata can be provided in Pandoc markdown format with L<metadata blocks|http://pandoc.org/MANUAL.html#metadata-blocks> at the top of a markdown file or in YAML format like this: --- title: a title author: - first author - second author published: true ... Pandoc supports document metadata build of strings (L</MetaString>), boolean values (L</MetaBool>), lists (L</MetaList>), key-value maps (L</MetaMap>), lists of inline elements (L</MetaInlines>) and lists of block elements (L</MetaBlocks>). Simple strings and boolean values can also be specified via pandoc command line option C<-M> or C<--metadata>: pandoc -M key=string pandoc -M key=false pandoc -M key=true pandoc -M key Perl module L<Pandoc::Elements> exports functions to construct metadata elements in the internal document model and the general helper function C<metadata>. =head1 COMMON METHODS All Metadata Elements support L<common element methods|Pandoc::Elements/COMMON METHODS> (C<name>, C<to_json>, C<string>, ...) and return true for method C<is_meta>. =head2 value( [ $key | $pointer ] [ %options ] ) Called without an argument this method returns an unblessed deep copy of the metadata element. Plain keys at the root level (unless they start with C</>) and JSON Pointer expressions (L<RFC 6901|http://tools.ietf.org/html/rfc6901>) can be used to select subfields. Note that JSON Pointer escapes slash as C<~1> and character C<~> as C<~0>. URI Fragment syntax is not supported. $doc->value; # full metadata $doc->value(""); # full metadata, explicitly $doc->value('/author'); # author field $doc->value('author'); # author field, plain key $doc->value('/author/name'); # name subfield of author field $doc->value('/author/0'); # first author field $doc->value('/author/0/name'); # name subfield of first author field $doc->value('/~1~0'); # metadata field '/~' $doc->value('/'); # field with empty string as key Returns C<undef> if the selected field does not exist. As a debugging aid you can set option C<strict> to a true value. In this case the method will C<croak> if an invalid pointer, invalid array index, non-existing key or non-existing array index is encountered. Instances of MetaInlines and MetaBlocks are stringified by unless option C<element> is set to C<keep>. Setting option C<boolean> to C<JSON::PP> will return C<JSON::PP:true> or C<JSON::PP::false> for L<MetaBool|/MetaBool> instances. =head1 METADATA ELEMENTS =head2 MetaString A plain text string metadata value. MetaString $string metadata "$string" =head2 MetaBool A Boolean metadata value. The special values C<"false"> and C<"FALSE"> are recognized as false in addition to normal false values (C<0>, C<undef>, C<"">, ...). MetaBool $value metadata JSON::true() metadata JSON::false() =head2 MetaList A list of other metadata elements. MetaList [ @values ] metadata [ @values ] =head2 MetaMap A map of keys to other metadata elements. MetaMap { %map } metadata { %map } =head2 MetaInlines Container for a list of L<inlines|Pandoc::Elements/INLINE ELEMENTS> in metadata. MetaInlines [ @inlines ] =head2 MetaBlocks Container for a list of L<blocks|Pandoc::Elements/BLOCK ELEMENTS> in metadata. MetaBlocks [ @blocks ] The C<string> method concatenates all stringified content blocks separated by empty lines. =cut ��������������������������������������������������Selector.pm�����������������������������������������������������������������������������������������100644��001750��001750�� 6335�13347276615� 17377� 0����������������������������������������������������������������������������������������������������ustar�00voj�����������������������������voj�����������������������������000000��000000��Pandoc-Elements-0.38/lib/Pandoc����������������������������������������������������������������������������������������������������������������������������������������package Pandoc::Selector; use strict; use warnings; use 5.010001; use Pandoc::Elements; my $IDENTIFIER = qr{[\p{L}\p{N}_-]+}; my $NAME = qr{[A-Za-z]+}; sub new { my ($class, $selector) = @_; # TODO: compile selector bless { selector => $selector }, $class; } sub match { my ($self, $element) = @_; foreach my $selector ( split /\|/, $self->{selector} ) { return 1 if _match_expression($selector, $element); } return 0; } sub _match_expression { my ( $selector, $elem ) = @_; $selector =~ s/^\s+|\s+$//g; # name return 0 if $selector =~ s/^($NAME)\s*//i and lc($1) ne lc( $elem->name ); return 1 if $selector eq ''; # type if ( $selector =~ s/^:(document|block|inline|meta)\s*// ) { my $method = "is_$1"; return 0 unless $elem->$method; return 1 if $selector eq ''; } # TODO: :method (e.g. :url) # TODO: [:level=1] # TODO [<number>] # TODO [@<attr>] # id and/or classes return 0 unless $elem->isa('Pandoc::Document::AttributesRole'); return _match_attributes($selector, $elem); } # check #id and .class sub _match_attributes { my ( $selector, $elem ) = @_; $selector =~ s/^\s+|\s+$//g; # trim while ( $selector ne '' ) { if ( $selector =~ s/^#($IDENTIFIER)\s*// ) { return 0 unless $elem->id eq $1; } elsif ( $selector =~ s/^\.($IDENTIFIER)\s*// ) { return 0 unless grep { $1 eq $_ } @{ $elem->attr->[1] }; } else { return 0; } } return 1; } 1; __END__ =head1 NAME Pandoc::Selector - Pandoc document selector language =head1 SYNOPSIS my $selector = Pandoc::Selector->new('Code.perl|CodeBlock.perl'); # check whether an element matches $selector->match($element); # use as element method $element->match('Code.perl|CodeBlock.perl') =head1 DESCRIPTION Pandoc::Selector provides a language to select elements of a Pandoc document. It borrows ideas from L<CSS Selectors|https://www.w3.org/TR/selectors-3/>, L<XPath|https://www.w3.org/TR/xpath/> and similar languages. The language is being developed together with this implementation. =head1 EXAMPLES Header#main Code.perl Code.perl.raw :inline =head1 SELECTOR GRAMMAR Whitespace between parts of the syntax is optional and not included in the following grammar. A B<Selector> is a list of one or more B<expression lists> separated by pipes (C<|>). For instance the selector C<Subscript|Superscript> selects both Subscript elements and Superscript elements. Selector ::= ExpressionList ( '|' ExpressionList )* An B<expression list> is a list of one or more B<expressions>: ExpressionList ::= Expression ( Expression )* An B<expression> is any of B<name expression>, B<id expression>, B<class expression>, and B<type expression>. Expression ::= NameExpression | IdExpression | ClassExpression | TypeExpression NameExpression ::= Name Name ::= [A-Za-z]+ IdExpression ::= '#' [\p{L}\p{N}_-]+ ClassExpression ::= '.' [\p{L}\p{N}_-]+ TypeExpression ::= ':' Name =head1 SEE ALSO See example filter C<select> to select parts of a document. =cut ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������example.md������������������������������������������������������������������������������������������100644��001750��001750�� 123�13347276615� 17475� 0����������������������������������������������������������������������������������������������������ustar�00voj�����������������������������voj�����������������������������000000��000000��Pandoc-Elements-0.38/t/documents���������������������������������������������������������������������������������������������������������������������������������������# Example <http://example.org/>! An ![](image.png) * [test](http://example.com/) ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������outline.md������������������������������������������������������������������������������������������100644��001750��001750�� 425�13347276615� 17526� 0����������������������������������������������������������������������������������������������������ustar�00voj�����������������������������voj�����������������������������000000��000000��Pandoc-Elements-0.38/t/documents���������������������������������������������������������������������������������������������������������������������������������������test document ## section 0.1 ### section 0.1.1 # chapter 1 with content # chapter 2 ## section 2.1 ## section 2.2 text #### subsubsection 2.2.1.1.1 ### subsubsection 2.2.2 # chapter 3 +-------------------+ | # header in table | +-------------------+ # chapter 4 �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������header-identifiers.t��������������������������������������������������������������������������������100644��001750��001750�� 2701�13347276615� 17463� 0����������������������������������������������������������������������������������������������������ustar�00voj�����������������������������voj�����������������������������000000��000000��Pandoc-Elements-0.38/t�������������������������������������������������������������������������������������������������������������������������������������������������use strict; use Test::More; use Pandoc::Elements; use Pandoc::Filter::HeaderIdentifiers; use utf8; my $ids={}; is header_identifier('Hello, nice world!'), 'hello-nice-world', 'header_identifier'; is header_identifier('1ẞ𝟼#6Ä_.-$'), 'ß6ä_.-', 'header_identifier strips characters'; is header_identifier('123#',$ids), 'section', 'header_identifier fallback'; is header_identifier('123#',$ids), 'section-1', 'header_identifier with numbering'; is_deeply $ids, { section => 2 }, 'identifier counts'; is header_identifier('a + + b +'), 'a-b', 'avoid too many hyphens'; is header_identifier('a, + }'), 'a', 'avoid too many hyphens'; is header_identifier('a -+-'), 'a---', 'but not more then allowed'; my $inlines = [ Str "A", Note [ Para [ Str "b" ] ], Str "C" ]; is header_identifier($inlines), 'ac', 'header_identifier without footnotes'; ok "abc123-" =~ /^\p{InPandocHeaderIdentifier}+$/, 'InPandocHeaderIdentifier'; ok "A+Dž" =~ /^\p{^InPandocHeaderIdentifier}+$/, 'InPandocHeaderIdentifier'; my $doc = Document {}, [ map { my ($title, $id) = split '=', $_; Header 1, attributes { id => $id }, [ Str $title ] } ('foo=','test=','test=test-2','test=','123=') ]; my $ids = { foo => 1 }; Pandoc::Filter::HeaderIdentifiers->new->apply($doc, $ids); is_deeply $ids, { foo => 2, test => 5, section => 1 }, 'apply'; is_deeply $doc->query( Header => sub { $_->id } ), [qw(foo-1 test-3 test-2 test-4 section)], 'identifiers added'; done_testing; ���������������������������������������������������������������release-pod-syntax.t��������������������������������������������������������������������������������100644��001750��001750�� 456�13347276615� 17441� 0����������������������������������������������������������������������������������������������������ustar�00voj�����������������������������voj�����������������������������000000��000000��Pandoc-Elements-0.38/t�������������������������������������������������������������������������������������������������������������������������������������������������#!perl BEGIN { unless ($ENV{RELEASE_TESTING}) { require Test::More; Test::More::plan(skip_all => 'these tests are for release candidate testing'); } } # This file was automatically generated by Dist::Zilla::Plugin::PodSyntaxTests. use Test::More; use Test::Pod 1.41; all_pod_files_ok(); ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������examples��������������������������������������������������������������������������������������������000755��001750��001750�� 0�13347276615� 15221� 5����������������������������������������������������������������������������������������������������ustar�00voj�����������������������������voj�����������������������������000000��000000��Pandoc-Elements-0.38/t�������������������������������������������������������������������������������������������������������������������������������������������������deemph.in.md����������������������������������������������������������������������������������������100644��001750��001750�� 63�13347276615� 17511� 0����������������������������������������������������������������������������������������������������ustar�00voj�����������������������������voj�����������������������������000000��000000��Pandoc-Elements-0.38/t/examples����������������������������������������������������������������������������������������������������������������������������������������This *is a `code` and $math$ [section](#x "foo")!* �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������example.json����������������������������������������������������������������������������������������100644��001750��001750�� 4760�13347276615� 20101� 0����������������������������������������������������������������������������������������������������ustar�00voj�����������������������������voj�����������������������������000000��000000��Pandoc-Elements-0.38/t/documents���������������������������������������������������������������������������������������������������������������������������������������[ { "unMeta" : {} }, [ { "t" : "Header", "c" : [ 1, [ "example-httpexample.org", [], [] ], [ { "c" : "Example", "t" : "Str" }, { "c" : [], "t" : "Space" }, { "t" : "Link", "c" : [ [ "", [], [] ], [ { "c" : "http://example.org/", "t" : "Str" } ], [ "http://example.org/", "" ] ] }, { "t" : "Str", "c" : "!" } ] ] }, { "c" : [ { "t" : "Str", "c" : "An" }, { "c" : [], "t" : "Space" }, { "t" : "Image", "c" : [ [ "", [], [] ], [], [ "image.png", "" ] ] } ], "t" : "Para" }, { "t" : "BulletList", "c" : [ [ { "t" : "Plain", "c" : [ { "t" : "Link", "c" : [ [ "", [], [] ], [ { "t" : "Str", "c" : "test" } ], [ "http://example.com/", "" ] ] } ] } ] ] } ] ] ����������������deemph.out.md���������������������������������������������������������������������������������������100644��001750��001750�� 62�13347276615� 17711� 0����������������������������������������������������������������������������������������������������ustar�00voj�����������������������������voj�����������������������������000000��000000��Pandoc-Elements-0.38/t/examples����������������������������������������������������������������������������������������������������������������������������������������This IS A `code` AND $math$ [SECTION](#x "foo")! ������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Filter-ImagesFromCode.t�����������������������������������������������������������������������������100644��001750��001750�� 2561�13347276615� 20003� 0����������������������������������������������������������������������������������������������������ustar�00voj�����������������������������voj�����������������������������000000��000000��Pandoc-Elements-0.38/t�������������������������������������������������������������������������������������������������������������������������������������������������use Test::More; use Pandoc::Elements; use Pandoc::Filter::ImagesFromCode qw(read_file write_file); use File::Temp 'tempdir'; use File::Spec::Functions 'catfile'; use File::stat; my $dir = tempdir( CLEANUP => 1 ); my $perlcode = 'binmode STDOUT, ":utf8";print "hello \x{1F4A9}";'; my $attr = { id => 'x', title => 'a title', class => 'perl', caption => 'a caption', }; my $doc = Document {}, [ CodeBlock attributes $attr, $perlcode ]; my $filter = Pandoc::Filter::ImagesFromCode->new( dir => $dir, from => 'pl', to => 'txt', capture => 1, run => ['perl', '$infile$'], ); $filter->apply($doc); my $infile = catfile($dir, 'x.pl'); ok -f $infile, 'created input file'; is read_file($infile, ':utf8'), $perlcode, 'written input file'; my $outfile = catfile($dir, 'x.txt'); ok -f $outfile, 'created output file'; is read_file($outfile, ':utf8'), "hello \x{1F4A9}", 'written output file'; my $outdate = stat($outfile)->mtime; is_deeply $doc->content, [ Plain [ Image attributes { id => x, class => 'perl' }, [ Str 'a caption' ], [$outfile, 'a title'] ] ], 'transformed document'; if ($ENV{RELEASE_TESTING}) { # skip because of sleep sleep 1; $doc = Document {}, [ CodeBlock attributes $attr, $perlcode ]; $filter->apply($doc); is stat($outfile)->mtime, $outdate, 'output file not modified'; } done_testing; �����������������������������������������������������������������������������������������������������������������������������������������������link-image-attributes.t�����������������������������������������������������������������������������100644��001750��001750�� 1250�13347276615� 20127� 0����������������������������������������������������������������������������������������������������ustar�00voj�����������������������������voj�����������������������������000000��000000��Pandoc-Elements-0.38/t�������������������������������������������������������������������������������������������������������������������������������������������������use strict; use Test::More; use Pandoc::Elements; use JSON; my $oldjson = do { local (@ARGV, $/) = ('t/documents/link-image-oldstyle.json'); <>; }; my $newjson = do { local (@ARGV, $/) = ('t/documents/link-image-attributes.json'); <>; }; my $olddoc = pandoc_json($oldjson); my $newdoc = pandoc_json($newjson); is_deeply $olddoc, $newdoc, 'parse old and new (Pandoc >= 1.16) format'; $Pandoc::Elements::PANDOC_VERSION = '1.16'; is_deeply decode_json($newjson), decode_json($newdoc->to_json), 'encode new format'; $Pandoc::Elements::PANDOC_VERSION = '1.15'; is_deeply decode_json($oldjson), decode_json($newdoc->to_json), 'encode old format'; done_testing; ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������empty.pl��������������������������������������������������������������������������������������������100644��001750��001750�� 1�13347276615� 20061� 0����������������������������������������������������������������������������������������������������ustar�00voj�����������������������������voj�����������������������������000000��000000��Pandoc-Elements-0.38/t/pandoc/filters���������������������������������������������������������������������������������������������������������������������������������� �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������lineblocks-empty-lines.t����������������������������������������������������������������������������100644��001750��001750�� 1147�13347276615� 20324� 0����������������������������������������������������������������������������������������������������ustar�00voj�����������������������������voj�����������������������������000000��000000��Pandoc-Elements-0.38/t�������������������������������������������������������������������������������������������������������������������������������������������������use Test::More 0.96; use Test::Warnings qw(warnings :no_end_test); use Pandoc::Elements; use Pandoc; plan skip_all => 'pandoc >= 1.18 not available' unless (pandoc and pandoc->version >= '1.18'); my $lineblock = <<'END_OF_MD'; | Sven Svensson | | | | Tel: 0123-45 67 89 | | Adress: | | Storgatan 42 | 123 45 Storstad | Sverige END_OF_MD my $doc = pandoc->parse(markdown => $lineblock); my $json; is_deeply [ warnings { $json = $doc->to_json; } ], [], 'uninitialized'; is_deeply [ warnings { my $doc = pandoc->parse( json => $json ); } ], [], 'parse json'; done_testing; �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������document-pandoc-version.t���������������������������������������������������������������������������100644��001750��001750�� 2232�13347276615� 20472� 0����������������������������������������������������������������������������������������������������ustar�00voj�����������������������������voj�����������������������������000000��000000��Pandoc-Elements-0.38/t�������������������������������������������������������������������������������������������������������������������������������������������������use strict; use v5.10; use Test::More; use Test::Exception; use Pandoc::Elements; my @tests = ( # => [ minimum API version , minimum release version ] { pandoc_version => '1.9' } => undef, { pandoc_version => '1.15.1' } => [qw(1.12.3 1.12.1)], { pandoc_version => '1.16.0.2' } => [qw(1.16 1.16)], { pandoc_version => '1.17' } => [qw(1.16 1.16)], { pandoc_version => '1.18' } => [qw(1.17 1.18)], { pandoc_version => '1.18.1' } => [qw(1.17 1.18)], { pandoc_version => 1.19 } => [qw(1.17 1.18)], { pandoc_version => 1.99 } => [qw(1.17 1.18)], { pandoc_version => '1.0' } => undef, { api_version => 1.17 } => [qw(1.17 1.18)], ); while (@tests) { my ($args, $versions) = splice @tests, 0, 2; my $msg = join ' ', map { "$_ ".$args->{$_} } keys %$args; if ($versions) { my ($api, $release) = @$versions; my $doc = Document {}, [], %$args; is $doc->api_version, $api, "$msg => api $api"; is $doc->pandoc_version, $release, "$msg => pandoc $release"; } else { throws_ok { Document {}, [], %$args } qr/pandoc version not supported/, "$msg => error"; } } done_testing; ����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������invalid-version-from-env.t��������������������������������������������������������������������������100644��001750��001750�� 360�13347276615� 20547� 0����������������������������������������������������������������������������������������������������ustar�00voj�����������������������������voj�����������������������������000000��000000��Pandoc-Elements-0.38/t�������������������������������������������������������������������������������������������������������������������������������������������������use strict; use Test::More; use Test::Exception; local $ENV{PANDOC_VERSION} = 'x'; lives_ok { require Pandoc::Elements; ok Pandoc::Elements::pandoc_version() > '1.12.1'; } 'ignore invalid PANDOC_VERSION from ENV'; done_testing; ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Document��������������������������������������������������������������������������������������������000755��001750��001750�� 0�13347276615� 16670� 5����������������������������������������������������������������������������������������������������ustar�00voj�����������������������������voj�����������������������������000000��000000��Pandoc-Elements-0.38/lib/Pandoc����������������������������������������������������������������������������������������������������������������������������������������Element.pm������������������������������������������������������������������������������������������100644��001750��001750�� 6057�13347276615� 20767� 0����������������������������������������������������������������������������������������������������ustar�00voj�����������������������������voj�����������������������������000000��000000��Pandoc-Elements-0.38/lib/Pandoc/Document�������������������������������������������������������������������������������������������������������������������������������package Pandoc::Document::Element; use strict; use warnings; our $VERSION = $Pandoc::Document::VERSION; use JSON (); use Scalar::Util qw(reftype blessed); use Pandoc::Walker (); use subs qw(walk query transform); # Silence syntax warnings sub to_json { JSON->new->utf8->canonical->convert_blessed->encode( $_[0] ); } sub TO_JSON { # Run everything thru this method so arrays/hashes are cloned # and objects without TO_JSON methods are stringified. # Required to ensure correct scalar types for Pandoc. # There is no easy way in Perl to tell if a scalar value is already a string or number, # so we stringify all scalar values and numify/boolify as needed afterwards. my ( $ast, $maybe_blessed ) = @_; if ( $maybe_blessed && blessed $ast ) { return $ast if $ast->can('TO_JSON'); # JSON.pm will convert # may have overloaded stringification! Should we check? # require overload; # return "$ast" if overload::Method($ast, q/""/) or overload::Method($ast, q/0+/); # carp "Non-stringifiable object $ast"; return "$ast"; } elsif ( 'ARRAY' eq reftype $ast ) { return [ map { ref($_) ? TO_JSON( $_, 1 ) : "$_"; } @$ast ]; } elsif ( 'HASH' eq reftype $ast ) { my %ret = %$ast; while ( my ( $k, $v ) = each %ret ) { $ret{$k} = ref($v) ? TO_JSON( $v, 1 ) : "$v"; } return \%ret; } else { return "$ast" } } sub name { $_[0]->{t} } sub content { my $e = shift; $e->set_content(@_) if @_; $e->{c} } sub set_content { # TODO: document this my $e = shift; $e->{c} = @_ == 1 ? $_[0] : [@_] } sub is_document { 0 } sub is_block { 0 } sub is_inline { 0 } sub is_meta { 0 } *walk = *Pandoc::Walker::walk; *query = *Pandoc::Walker::query; *transform = *Pandoc::Walker::transform; sub string { # TODO: fix issue #4 to avoid this duplication if ( $_[0]->name =~ /^(Str|Code|CodeBlock|Math|MetaString)$/ ) { return $_[0]->content; } elsif ( $_[0]->name =~ /^(LineBreak|SoftBreak|Space)$/ ) { return ' '; } join '', @{ $_[0]->query( { 'Str|Code|CodeBlock|Math|MetaString' => sub { $_->content }, 'LineBreak|Space|SoftBreak' => sub { ' ' }, } ); }; } # TODO: replace by new class Pandoc::Selector with compiled code sub match { my $self = shift; foreach my $selector ( split /\|/, shift ) { return 1 if $self->match_simple($selector); } return 0; } sub match_simple { my ( $self, $selector ) = @_; $selector =~ s/^\s+|\s+$//g; # name return 0 if $selector =~ s/^([a-z]+)\s*//i and lc($1) ne lc( $self->name ); return 1 if $selector eq ''; # type if ( $selector =~ s/^:(document|block|inline|meta)\s*// ) { my $method = "is_$1"; return 0 unless $self->$method; return 1 if $selector eq ''; } # id and/or classes return 0 unless $self->can('match_attributes'); return $self->match_attributes($selector); } ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Filter����������������������������������������������������������������������������������������������000755��001750��001750�� 0�13347276615� 16337� 5����������������������������������������������������������������������������������������������������ustar�00voj�����������������������������voj�����������������������������000000��000000��Pandoc-Elements-0.38/lib/Pandoc����������������������������������������������������������������������������������������������������������������������������������������Multifilter.pm��������������������������������������������������������������������������������������100644��001750��001750�� 6125�13347276615� 21341� 0����������������������������������������������������������������������������������������������������ustar�00voj�����������������������������voj�����������������������������000000��000000��Pandoc-Elements-0.38/lib/Pandoc/Filter���������������������������������������������������������������������������������������������������������������������������������package Pandoc::Filter::Multifilter; use strict; use warnings; use 5.010; our $VERSION = '0.34'; use parent 'Pandoc::Filter'; our @EXPORT_OK = (qw(find_filter apply_filter)); use Pandoc::Elements 'pandoc_json'; use Pandoc; use IPC::Cmd 'can_run'; use IPC::Run3; sub new { bless { }, shift; } sub apply { my ( $self, $doc, $format, $meta ) = @_; return $doc if $doc->name ne 'Document'; my $multi = $doc->meta->{multifilter}; return $doc if !$multi or $multi->name ne 'MetaList'; my @filters = map { if ($_->name eq 'MetaMap' and $_->{filter}) { $_->value } elsif ($_->name eq 'MetaString' or $_->name eq 'MetaInlines') { { filter => $_->value } } } @{$multi->content}; foreach (@filters) { my @filter = find_filter($_->{filter}); apply_filter($doc, $format, @filter); } $doc; } our %SCRIPTS = ( hs => 'runhaskell', js => 'node', php => 'php', pl => 'perl', py => 'python', rb => 'ruby', ); sub find_filter { my $name = shift; my $data_dir = shift // pandoc_data_dir; $data_dir =~ s|/$||; foreach my $filter ("$data_dir/filters/$name", $name) { return $filter if -x $filter; if (-e $filter and $filter =~ /\.([a-z]+)$/i) { if ( my $cmd = $SCRIPTS{lc($1)} ) { die "cannot execute filter with $cmd\n" unless can_run($cmd); return ($cmd, $filter); } } } return (can_run($name) or die "filter not found: $name\n"); } sub apply_filter { my ($doc, $format, @filter) = @_; my $stdin = $doc->to_json; my $stdout = ""; my $stderr = ""; run3 [@filter, $format // ''], \$stdin, \$stdout, \$stderr; if ($?) { $stderr .= "\n" if $stderr ne '' and $stderr !~ /\n\z/s; die join(' ','filter failed:',@filter)."\n$stderr"; } my $transformed = eval { pandoc_json($stdout) }; die join(' ','filter emitted no valid JSON:',@filter)."\n" if $@; # modify original document $doc->meta($transformed->meta); $doc->content($transformed->content); return $doc; } __END__ =head1 NAME Pandoc::Filter::Multifilter - apply filters from metadata field C<multifilter> =head1 DESCRIPTION This filter is provided as system-wide executable L<multifilter>, see there for additional documentation. =head1 METHODS =head2 new Create a new multifilter. =head2 apply( $doc [, $format [, $metadata ] ] ) Apply all filters specified in document metadata field C<metafilters>. =head1 FUNCTIONS =head2 find_filter( $name [, $DATADIR ] ) Find a filter by its name in C<$DATADIR/filters>, where C<$DATADIR> is the user data directory (L<~/.pandoc> or L<%appdata%\pandoc>), and in L<$PATH>. Returns a list of command line arguments to execute the filter or throw an exception. =head2 apply_filter( $doc, $format, @filter ) Apply a filter, given by its command line arguments, to a Pandoc L<Document|Pandoc::Elements/Document> element and return a transformed Document or throw an exception on error. Can be called like this: apply_filter( $doc, $format, find_filter( $name ) ); =cut �������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������ImagesFromCode.pm�����������������������������������������������������������������������������������100644��001750��001750�� 13653�13347276615� 21711� 0����������������������������������������������������������������������������������������������������ustar�00voj�����������������������������voj�����������������������������000000��000000��Pandoc-Elements-0.38/lib/Pandoc/Filter���������������������������������������������������������������������������������������������������������������������������������package Pandoc::Filter::ImagesFromCode; use strict; use warnings; use utf8; use Encode; use 5.010; our $VERSION = '0.36'; use Digest::MD5 'md5_hex'; use IPC::Run3; use File::Spec::Functions; use File::stat; use Pandoc::Elements; use Scalar::Util 'reftype'; use parent 'Pandoc::Filter', 'Exporter'; our @EXPORT_OK = qw(read_file write_file); sub new { my ($class, %opts) = @_; $opts{from} //= 'code'; $opts{dir} //= '.'; $opts{dir} =~ s!/$!!; $opts{name} //= sub { $_[0]->id =~ /^[a-z0-9_]+$/i ? $_[0]->id : md5_hex( encode( 'utf8', $_[0]->content ) ); }; die "missing option: to\n" unless $opts{to}; if ('ARRAY' ne reftype $opts{run} or !@{$opts{run}}) { die "missing or empty option: run\n"; } bless \%opts, $class; } sub to { my $to = $_[0]->{to}; my $format = $_[1]; if (ref $to) { return $to->($format); } elsif ($to) { return $to; } else { return 'png'; } } sub action { my $self = shift; sub { my ($e, $format, $m) = @_; return if $e->name ne 'CodeBlock'; my $code = $e->content; my $dir = $self->{dir}; my %args = ( name => $self->{name}->($e), from => $self->{from}, to => $self->to($format), ); $args{infile} = catfile($self->{dir}, "$args{name}.$args{from}"); $args{outfile} = catfile($self->{dir}, "$args{name}.$args{to}"); # TODO: document or remove this experimental code. If keep, expand args my $kv = $e->keyvals; my @options = $kv->get_all('option'); push @options, map { split /\s+/, $_ } $kv->get_all('options'); # TODO: print args in debug mode? # skip transformation if nothing has changed my $in = stat($args{infile}); my $out = stat($args{outfile}); if (!$self->{force} and $in and $out and $in->mtime <= $out->mtime) { if ($code eq read_file($args{infile}, ':utf8')) { # no need to rebuild the same outfile return build_image($e, $args{outfile}); } } write_file($args{infile}, $code, ':utf8'); my ($stderr, $stdout); my @command = map { my $s = $_; #if ($args{substr $s, 1, -1}) $s =~ s|\$([^\$]+)\$| $args{$1} // $1 |eg; $s } @{$self->{run}}; push @command, @options; run3 \@command, \undef, \$stdout, \$stderr, { binmode_stdin => ':utf8', binmode_stdout => ':raw', binmode_stderr => ':raw', }; if ($self->{capture}) { write_file($args{outfile}, $stdout, ':raw'); } # TODO: include $code or $stderr on error in debug mode # TODO: skip error if requested die $stderr if $stderr; return build_image($e, $args{outfile}); } } # build_image( $element [, $filename ] ) # # Maps an element to an L<Image|Pandoc::Elements/Image> element with attributes # from the given element. The attribute C<caption>, if available, is transformed # into image caption. This utility function is useful for filters that transform # content to images. See graphviz, tikz, lilypond and similar filters in the # L<examples|https://metacpan.org/pod/distribution/Pandoc-Elements/examples/>. sub build_image { my $e = shift; my $filename = shift // ''; my $keyvals = $e->keyvals; my $title = $keyvals->get('title') // ''; my $img = Image attributes { id => $e->id, class => $e->class }, [], [$filename, $title]; my $caption = $keyvals->get('caption') // ''; if (defined $caption) { push @{$img->content}, Str($caption); } return Plain [ $img ]; } sub write_file { my ($file, $content, $encoding) = @_; open my $fh, ">$encoding", $file or die "failed to create file $file: $!\n"; print $fh $content; close $fh; } sub read_file { my ($file, $encoding) = @_; open my $fh, "<$encoding", $file or die "failed to open file: $file: $!\n"; my $content = do { local $/; <$fh> }; close $fh or die "failed to close file: $file: $!\n"; return $content; } 1; __END__ =head1 NAME Pandoc::Filter::ImagesFromCode - transform code blocks into images =head1 DESCRIPTION This L<Pandoc::Filter> transforms L<CodeBlock|Pandoc::Elements/CodeBlock> elements into L<Image|Pandoc::Elements/Image> elements. Content of transformed code section and resulting image files are written to files. Attribute C<title> is mapped to the image title and attribute C<caption> to an image caption, if available. =head1 CONFIGURATION =over =item from File extension of input files extracted from code blocks. Defaults to C<code>. =item to File extension of created image files. Can be a fixed string or a code reference that gets the document output format (for instance L<latex> or C<html>) as argument to produce different image formats depending on output format. =item name Code reference that maps the L<CodeBlock|Pandoc::Elements/CodeBlock> element to a filename (without directory and extension). By default the element's C<id> is used if it contains characters no other than C<a-zA-Z0-9_->. Otherwise the name is the MD5 hash of the element's content. =item dir Directory where to place input and output files, relative to the current directory. This directory (default C<.>) is prepended to all image references in the target document. =item run Command to transform input files to output files. Variable references C<$...$> can be used to refer to current values of C<from>, C<to>, C<name>, C<dir>, C<infile> and C<outfile>. Example: run => ['ditaa', '-o', '$infile$', '$outfile$'], =item capture Capture output of command and write it to C<outfile>. Disabled by default. =item force Apply transformation also if input and output file already exists unchanged. Disabled by default. =back =cut �������������������������������������������������������������������������������������link-image-oldstyle.json����������������������������������������������������������������������������100644��001750��001750�� 1314�13347276615� 22310� 0����������������������������������������������������������������������������������������������������ustar�00voj�����������������������������voj�����������������������������000000��000000��Pandoc-Elements-0.38/t/documents���������������������������������������������������������������������������������������������������������������������������������������[ { "unMeta": {} }, [ { "t" : "Para", "c" : [ { "t" : "Image", "c" : [ [], [ "http://example.org/", "" ] ] }, { "t" : "Link", "c" : [ [ { "c" : "http://example.org/", "t" : "Str" } ], [ "http://example.org/", "" ] ] } ] } ] ] ��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������remove-unnumbered-sections.pl�����������������������������������������������������������������������100644��001750��001750�� 1756�13347276615� 22750� 0����������������������������������������������������������������������������������������������������ustar�00voj�����������������������������voj�����������������������������000000��000000��Pandoc-Elements-0.38/examples������������������������������������������������������������������������������������������������������������������������������������������#!/usr/bin/env perl use strict; =head1 NAME unnumbered-sections - remove all unnumbered sections =head1 DESCRIPTION This Pandoc filter removes all unnumbered sections, that is everything from a header with class C<unnumbered> until the next normal header of the same level. For instance this document: # Section # Unnumbered Section {.unnumbered} ... ## Subsection ... # Another Section ... Would be reduced to # Section # Another Section ... =cut use Pandoc::Filter; my $skiplevel = 0; # process all elements pandoc_filter sub { if ($skiplevel > 0) { # end of currently skipped section if ($_->name eq 'Header' and $_->level <= $skiplevel) { $skiplevel = 0; # remove element } else { return []; } } # new unnumbered section to skip if ($_->match('Header.unnumbered')) { $skiplevel = $_->level; return []; } # keep element return }; ������������������HeaderIdentifiers.pm��������������������������������������������������������������������������������100644��001750��001750�� 7311�13347276615� 22415� 0����������������������������������������������������������������������������������������������������ustar�00voj�����������������������������voj�����������������������������000000��000000��Pandoc-Elements-0.38/lib/Pandoc/Filter���������������������������������������������������������������������������������������������������������������������������������package Pandoc::Filter::HeaderIdentifiers; use strict; use warnings; use 5.010; our $VERSION = '0.34'; use parent 'Pandoc::Filter'; use Pandoc::Elements; our @EXPORT = qw(header_identifier InPandocHeaderIdentifier); ## FUNCTIONS sub header_identifier { my $id = shift; my $ids = shift; # stringify inline elements except footnotes $id = join '', @{ pandoc_query( $id, sub { $_->is_inline and $_->name ne 'Note' ? $_->string : \undef }) } if ref $id; # Convert all alphabetic characters to lowercase. $id = lc $id; # these steps not strictly documented but it is how Pandoc works $id =~ s/\p{^InPandocHeaderIdOrWs}+//g; $id =~ s/\p{WhiteSpace}+$//; # Replace all spaces and newlines with hyphens. $id =~ s/\p{WhiteSpace}+/-/g; # Remove all punctuation, except underscores, hyphens, periods, and whitespace. $id =~ s/\p{^InPandocHeaderIdentifier}//g; # remove everything up to the first letter $id =~ s/^[_.0-9-]+//; # if nothing is left, use the identifier 'section' $id ||= 'section'; # add counter on repeated identifiers if ($ids and $ids->{$id}++) { $id .= '-' . ($ids->{$id}-1); } return $id; } ## METHODS sub new { bless { }, shift; } sub apply { my ($self, $doc) = @_; my $ids = @_ > 2 ? $_[2] : {}; # collect existing identifiers $doc->walk( Header => sub { my $id = $_->id; return if $id !~ /^\p{InPandocHeaderIdentifier}+$/ or $id !~ /^\p{Letter}/; if ($id =~ /^(.+)-(\d+)$/) { $id = $1; $ids->{$id} = $2 unless defined $ids->{$id} and $ids->{$id} > $2; } $ids->{$id}++; } ); # add missing identifiers $doc->walk( Header => sub { $_[0]->id( header_identifier( $_[0]->content, $ids ) ) if $_[0]->id eq ''; }); $doc; } ## CHARACTER PROPERTIES sub InPandocHeaderIdentifier { return "+utf8::Letter\n-utf8::Uppercase_Letter\n-utf8::Titlecase_Letter\n0030 0039\n005F\n002d 002e\n"; } sub InPandocHeaderIdOrWs { return "+utf8::Whitespace\n+utf8::Letter\n-utf8::Uppercase_Letter\n-utf8::Titlecase_Letter\n0030 0039\n005F\n002d 002e\n"; } __END__ =head1 NAME Pandoc::Filter::HeaderIdentifiers - Add identifiers to headers =head1 SYNOPSIS my $id = header_identifier( $header->content ); # calculate identifier Pandoc::Filter::HeaderIdentifiers->new->apply($doc); # add all identifiers =head1 DESCRIPTION This L<Pandoc::Filter> adds identifier attributes (L<id|Pandoc::Elements/id>) to all L<Headers|Pandoc::Elements/Header> elements. It uses the same algorithm as internally used by pandoc. The module also exports function C<header_identifier> to calculate an identifier from a list of elements. =head1 FUNCTIONS =head2 header_identifier( $content [, $ids ] ) Returns an identifier for a given list of L<inlines|Pandoc::Elements/INLINE ELEMENTS> or string (C<$content>). Optionally takes into account and updates existing ids, given as hash reference mapping identifier to usage count (C<$ids>). =head1 METHODS =head2 apply( $element [, $ids ] ) Add identifiers to all L<Header|Pandoc::Elements/Header> elements found at a given element (typically a L<Document|Pandoc::Elements/Document>. A hash reference of existing identifier counts (or an empty hash to get the new counts) can be passed in addition. =head1 CHARACTER PROPERTIES =head2 InPandocHeaderIdentifier Matches all Unicode lowercase letters, digits 0 to 9, underscore, hyphen, and period. In the unlikely event that you want to check whether a given string could have been generated as header identifier, use this: $id =~ /^\p{InPandocHeaderIdentifier}+$/ and $id =~ /^\p{Letter}/ =head1 SEE ALSO L<http://pandoc.org/MANUAL.html#header-identifiers> =cut �����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������link-image-attributes.json��������������������������������������������������������������������������100644��001750��001750�� 1655�13347276615� 22647� 0����������������������������������������������������������������������������������������������������ustar�00voj�����������������������������voj�����������������������������000000��000000��Pandoc-Elements-0.38/t/documents���������������������������������������������������������������������������������������������������������������������������������������[ { "unMeta": {} }, [ { "t" : "Para", "c" : [ { "t" : "Image", "c" : [ [ "", [], [] ], [], [ "http://example.org/", "" ] ] }, { "t" : "Link", "c" : [ [ "", [], [] ], [ { "c" : "http://example.org/", "t" : "Str" } ], [ "http://example.org/", "" ] ] } ] } ] ] ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������