Pandoc-Elements-0.15 000755 001750 001750 0 12633504025 13174 5 ustar 00voj voj 000000 000000 README 100644 001750 001750 24527 12633504025 14167 0 ustar 00voj voj 000000 000000 Pandoc-Elements-0.15 NAME
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!' ],
])->to_json;
can be converted for instance to HTML with 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 create abstract syntax
trees (AST) of Pandoc documents. Pandoc can convert
the resulting data structure to many other document formats, such as
HTML, LaTeX, ODT, and ePUB.
Please make sure to use at least Pandoc 1.12 when processing documents
See also module Pandoc::Filter, command line scripts pandocwalk and
pod2pandoc, and the internal modules Pandoc::Walker,
Pandoc::Filter::Lazy, and Pod::Simple::Pandoc.
EXPORTED 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" in DOCUMENT ELEMENT).
* Type keywords such as "Decimal" and "LowerAlpha" to be used as types
in other document elements.
* The helper following functions "pandoc_json", "attributes",
"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".
attributes { key => $value, ... }
Maps a hash reference into an attributes list with id, classes, and
ordered key-value pairs. The special keys "id" and "classes" are
recognized but setting multi-value attributes or controlled order is not
supported with this function. You can always manually create an
attributes structure:
[ $id, [ @classes ], [ key => $value, ... ] ]
Elements with attributes (element accessor method "attr") also provide
the accessor method "id", "classes", and "class". See Hash::MultiValue
for easy access to key-value-pairs.
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", C>AuthorInText>, "SuppressAuthor"),
"citationNoteNum" (integer), and "citationHash" (integer). The helper
method "citation" can be used to construct such hash by filling in
default values and 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]
element( $name => $content )
Create a Pandoc document element of arbitrary name. This function is
only exported on request.
ELEMENTS
Document elements are encoded as Perl data structures equivalent to the
JSON structure, emitted with pandoc output format "json". All elements
are blessed objects that provide the following element methods and
additional accessor methods specific to each element.
ELEMENT METHODS
to_json
Return the element as JSON encoded string. The following are equivalent:
$element->to_json;
JSON->new->utf8->convert_blessed->encode($element);
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 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
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.
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")
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").
Div $attributes, [ @blocks ]
Header
Header with "level" (integer), attributes ("attr"), and text ("content",
a list of inlines).
Header $level, $attributes, [ @inlines ]
HorizontalRule
Horizontal rule
HorizontalRule
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" in citation to construct citations.
Cite [ @citations ], [ @inlines ]
Code
Inline code, a literal string ("content") with attributes ("attr")
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").
Image [ @inlines ], [ $url, $title ]
LineBreak
Hard line break
LineBreak
Link
Hyperlink with link text ("content", a list of inlines) and "target"
(list of "url" and "title").
Link [ @inlines ], [ $url, $title ]
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 ]
Space
Inter-word space
Space
Span
Generic container of inlines ("content") with attributes ("attr").
Span attributes { %attr }, [ @inlines ]
Str
Plain text, a string ("content").
Str $text
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
MetaBlocks
MetaBool
MetaInlines
MetaList
MetaMap
MetaString
DOCUMENT ELEMENT
Document
Root element, consisting of metadata hash ("meta") and document element
array ("content").
Document $meta, [ @blocks ]
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
Pandoc implements a wrapper around the pandoc executable.
Text.Pandoc.Definition
contains the original definition of Pandoc document data
structure in Haskell. This module version was last aligned with
pandoc-types-1.12.4.
AUTHOR
Jakob Voß
COPYRIGHT AND LICENSE
Copyright 2014- Jakob Voß
GNU General Public License, Version 2
This module is heavily based on Pandoc by John MacFarlane.
Changes 100644 001750 001750 3640 12633504025 14553 0 ustar 00voj voj 000000 000000 Pandoc-Elements-0.15 Revision history for Pandoc-Elements
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
t 000755 001750 001750 0 12633504025 13360 5 ustar 00voj voj 000000 000000 Pandoc-Elements-0.15 ast.t 100644 001750 001750 1305 12633504025 14473 0 ustar 00voj voj 000000 000000 Pandoc-Elements-0.15/t use 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->[0]->{unMeta};
is $meta, $doc->meta, '->meta';
ok $meta->{title}->is_meta, 'is_meta';
is $meta->{title}->name, 'MetaInlines', 'name';
my $para = $doc->[1]->[0];
is $para->name, 'Para', 'name';
is_deeply $para->content, [ Str 'test' ];
ok $para->is_block, 'is_block';
ok !$para->is_document, '!is_document';
done_testing;
LICENSE 100644 001750 001750 43525 12633504025 14313 0 ustar 00voj voj 000000 000000 Pandoc-Elements-0.15 This 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.
cpanfile 100644 001750 001750 370 12633504025 14741 0 ustar 00voj voj 000000 000000 Pandoc-Elements-0.15 requires 'perl', '5.010';
# core modules
requires 'Pod::Simple', '3.08';
requires 'List::Util';
requires 'Scalar::Util';
requires 'Pod::Usage';
requires 'JSON';
on test => sub {
requires 'Test::More', '0.96';
requires 'Test::Output';
};
dist.ini 100644 001750 001750 132 12633504025 14675 0 ustar 00voj voj 000000 000000 Pandoc-Elements-0.15 author=Jakob Voß
[@Milla]
[PruneFiles]
filename=examples/Makefile
match=^examples/.*\.md
lazy.t 100644 001750 001750 2123 12633504025 14662 0 ustar 00voj voj 000000 000000 Pandoc-Elements-0.15/t use strict;
use v5.010;
use Test::More;
use Pandoc::Elements;
use Pandoc::Filter::Lazy;
foreach my $code (
'sub { return unless $_->name eq "Emph"; return [] }',
'Emph => sub { [] }'
) {
my $filter = Pandoc::Filter::Lazy->new($code);
ok !$filter->error, 'no error';
my $doc = Document {}, [ Para [ Str "hello", Emph [ Str "world" ] ] ];
$filter->apply($doc);
is_deeply $doc, Document({}, [ Para [ Str "hello" ] ]), 'apply';
is $filter->script, $code;
is $filter->code, <new( $code );
CODE
}
my %lazy = (
"Emph\t =>sub { [] }" => 'Emph => sub { [] }',
"#id => sub { [] }" => "'#id' => sub { [] }",
'Code|CodeBlock => say $_->class' =>
"'Code|CodeBlock' => sub { say \$_->class }",
':class => say $_->class' => "':class' => sub { say \$_->class }",
);
while ( my ($got, $expect) = each %lazy ) {
my $filter = Pandoc::Filter::Lazy->new($got);
ok !$filter->error;
is $filter->script, $expect, $got;
}
done_testing;
META.yml 100644 001750 001750 1610 12633504025 14524 0 ustar 00voj voj 000000 000000 Pandoc-Elements-0.15 ---
abstract: 'create and process Pandoc documents'
author:
- 'Jakob Voß'
build_requires:
Test::More: '0.96'
Test::Output: '0'
configure_requires:
Module::Build::Tiny: '0.039'
dynamic_config: 0
generated_by: 'Dist::Zilla version 5.035, Dist::Milla version v1.0.8, 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:
JSON: '0'
List::Util: '0'
Pod::Simple: '3.08'
Pod::Usage: '0'
Scalar::Util: '0'
perl: '5.010'
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.15'
x_contributors:
- 'Jakob Voß '
MANIFEST 100644 001750 001750 1451 12633504025 14407 0 ustar 00voj voj 000000 000000 Pandoc-Elements-0.15 # This file was automatically generated by Dist::Zilla::Plugin::Manifest v5.035.
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/myemph.pl
examples/remove-unnumbered-sections.pl
examples/theorem.pl
lib/Pandoc/Elements.pm
lib/Pandoc/Filter.pm
lib/Pandoc/Filter/Lazy.pm
lib/Pandoc/Walker.pm
lib/Pod/Simple/Pandoc.pm
script/pandocwalk
script/pod2pandoc
t/accessors.t
t/ast.t
t/attributes.t
t/citation.t
t/documents/example.json
t/documents/example.md
t/elements.t
t/example.md
t/example.tex
t/examples/deemph.in.md
t/examples/deemph.out.md
t/filter.t
t/lazy.t
t/match.t
t/outline
t/pandoc_filter.t
t/pandocwalk.t
t/pod-simple-pandoc.t
t/release-pod-syntax.t
t/stringify.t
t/synopsis.t
t/walker.t
Build.PL 100644 001750 001750 227 12633504025 14532 0 ustar 00voj voj 000000 000000 Pandoc-Elements-0.15 # This Build.PL for Pandoc-Elements was generated by Dist::Zilla::Plugin::ModuleBuildTiny 0.006.
use 5.010;
use Module::Build::Tiny 0.039;
Build_PL();
match.t 100644 001750 001750 1433 12633504025 15002 0 ustar 00voj voj 000000 000000 Pandoc-Elements-0.15/t use strict;
use Test::More;
use Pandoc::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('#id'), 'no id match';
my $e = Code attributes { id => 'abc', classes => ['f0.0','bar']} , '';
ok $e->match('#abc'), 'id match';
ok !$e->match('#xyz'), 'id no match';
ok !$e->match('#1'), 'id no match';
ok $e->match('.f0.0'), 'class match';
ok $e->match('.bar .f0.0'), 'classes match';
ok !$e->match('.xyz'), 'class no match';
ok $e->match("code\t:inline .bar#abc .f0.0"), 'multiple match';
done_testing;
outline 100755 001750 001750 251 12633504025 15103 0 ustar 00voj voj 000000 000000 Pandoc-Elements-0.15/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.json 100644 001750 001750 3277 12633504025 14707 0 ustar 00voj voj 000000 000000 Pandoc-Elements-0.15 {
"abstract" : "create and process Pandoc documents",
"author" : [
"Jakob Voß"
],
"dynamic_config" : 0,
"generated_by" : "Dist::Zilla version 5.035, Dist::Milla version v1.0.8, 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.8",
"Test::Pod" : "1.41"
}
},
"runtime" : {
"requires" : {
"JSON" : "0",
"List::Util" : "0",
"Pod::Simple" : "3.08",
"Pod::Usage" : "0",
"Scalar::Util" : "0",
"perl" : "5.010"
}
},
"test" : {
"requires" : {
"Test::More" : "0.96",
"Test::Output" : "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.15",
"x_contributors" : [
"Jakob Voß "
]
}
filter.t 100644 001750 001750 2544 12633504025 15177 0 ustar 00voj voj 000000 000000 Pandoc-Elements-0.15/t use 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!" ];
});
ok !$filter->error, 'no error';
$filter->apply($doc);
is_deeply $doc->content, [ Str('HELLO'), Str(' world!') ], "don't filter injected elements";
done_testing;
walker.t 100644 001750 001750 4144 12633504025 15175 0 ustar 00voj voj 000000 000000 Pandoc-Elements-0.15/t use 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;
citation.t 100644 001750 001750 633 12633504025 15501 0 ustar 00voj voj 000000 000000 Pandoc-Elements-0.15/t use strict;
use Test::More;
use Pandoc::Elements;
my $c = citation {
id => 'foo',
prefix => [ Str "see" ],
suffix => [ Str "p.", Space, Str "42" ]
};
is_deeply $c, {
citationId => 'foo',
citationHash => 1,
citationMode => NormalCitation,
citationNoteNum => 0,
citationPrefix => [ Str "see" ],
citationSuffix => [ Str "p.", Space, Str "42" ],
};
done_testing;
elements.t 100644 001750 001750 1474 12633504025 15527 0 ustar 00voj voj 000000 000000 Pandoc-Elements-0.15/t use strict;
use Test::More;
use Pandoc::Elements qw(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';
done_testing;
example.md 100644 001750 001750 127 12633504025 15455 0 ustar 00voj voj 000000 000000 Pandoc-Elements-0.15/t # Section with *ÄÖÜ* and [link](http://example.org/)
## Subsection with **äöü**
synopsis.t 100644 001750 001750 2062 12633504025 15574 0 ustar 00voj voj 000000 000000 Pandoc-Elements-0.15/t use strict;
use Test::More;
use Pandoc::Elements;
use JSON;
my $ast = Document {
title => MetaInlines [ Str 'Greeting' ]
}, [
Header( 1, attributes { id => 'de' }, [ Str 'Gruß' ] ),
Para [ Str 'hello, world!' ],
];
is_deeply $ast, [
{
unMeta => {
title => {
t => 'MetaInlines',
c => [{ t => 'Str', c => 'Greeting' }]
}
}
},
[
{
t => 'Header',
c => [ 1, ['de',[],[]], [ { t => 'Str', c => 'Gruß' } ] ]
},
{ t => 'Para', c => [ { t => 'Str', c => 'hello, world!' } ] }
]
];
my $json = JSON->new->utf8->convert_blessed->encode($ast);
is_deeply decode_json($json), $ast, 'encode/decode JSON';
is_deeply Pandoc::Elements::pandoc_json($json), $ast, 'pandoc_json';
$json = $ast->to_json;
is_deeply decode_json($json), $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.t 100644 001750 001750 1644 12633504025 15677 0 ustar 00voj voj 000000 000000 Pandoc-Elements-0.15/t use strict;
use Test::More;
use Pandoc::Elements;
my $e = CodeBlock attributes { classes => ['perl'], id => 2 }, 'say "Hi";';
is_deeply $e->attr, $e->{c}->[0], 'CodeBlock->attr';
is $e->id, '2', 'AttributeRole->id';
is_deeply $e->classes, ['perl'], 'AttributeRole->classes';
is $e->class, 'perl', 'AttributeRole->class';
is $e->content, 'say "Hi";', 'CodeBlock->content';
$e = Quoted SingleQuote, 'x';
is $e->type->name, 'SingleQuote', 'Quoted';
# TODO: OrderedList with ListAttributes, Table etc.
$e = DefinitionList [
[ [ Str 'term 1' ],
[ [ Para Str 'definition 1' ] ] ],
[ [ Str 'term 2' ],
[ [ Para Str 'definition 2' ],
[ Para Str 'definition 3' ] ] ],
];
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';
done_testing;
example.tex 100644 001750 001750 167 12633504025 15661 0 ustar 00voj voj 000000 000000 Pandoc-Elements-0.15/t \section{Section with \emph{ÄÖÜ} and \href{http://example.org/}{link}}
\subsection{Subsection with \textbf{äöü}}
stringify.t 100644 001750 001750 776 12633504025 15715 0 ustar 00voj voj 000000 000000 Pandoc-Elements-0.15/t use strict;
use Test::More;
use Pandoc::Elements;
my $ast = Document { }, [
Header(1,attributes {},[ Str 'hello', Code attributes {}, ', ' ]),
BulletList [ [ Plain [ Str 'world', Space, Str '!' ] ] ],
];
is $ast->string, 'hello, world !';
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';
done_testing;
__DATA__
# hello`,`
* world !
attributes.t 100644 001750 001750 517 12633504025 16056 0 ustar 00voj voj 000000 000000 Pandoc-Elements-0.15/t use strict;
use Test::More;
use Pandoc::Elements qw(attributes);
is_deeply attributes { }, ['',[],[]], 'empty attributes';
is_deeply attributes(undef), ['',[],[]], 'empty attributes (undef)';
is_deeply attributes { classes => [qw(x y)], answer => 42, id => 0 },
['0',[qw(x y)],[ answer => 42 ]], 'classes and id';
done_testing;
pandocwalk.t 100644 001750 001750 2035 12633504025 16030 0 ustar 00voj voj 000000 000000 Pandoc-Elements-0.15/t use strict;
use Test::More;
use Test::Output;
plan skip_all => 'release test' unless $ENV{RELEASE_TESTING};
if ( (`pandoc -v` // '') !~ /^pandoc (\d+)\.(\d+)/ or ($1 eq '1' and $2 < 12) ) {
plan skip_all => 'pandoc >= 1.12 required';
}
my $header = 'Header=>sub{say " " x ($_->level-1), $_->string }';
my $link = 'Link=>sub{say $_->url}';
output_like { system($^X,'script/pandocwalk') } qr/^Usage:/, qr//, 'usage';
output_is {
system($^X,'script/pandocwalk','t/example.tex',$link);
} "http://example.org/\n", "", "Link (perl code)";
output_is {
system($^X,'script/pandocwalk','t/example.tex',$header);
} "Section with ÄÖÜ and link\n Subsection with äöü\n", "", "Header (perl code)";
output_is {
system($^X,'script/pandocwalk','t/example.tex','t/outline');
} "Section with ÄÖÜ and link\n Subsection with äöü\n", "", "Header (executable)";
output_is {
system("$^X script/pandocwalk t/outline < t/example.md");
} "Section with ÄÖÜ and link\n Subsection with äöü\n", "", "Markdown from STDIN";
done_testing;
examples 000755 001750 001750 0 12633504025 14733 5 ustar 00voj voj 000000 000000 Pandoc-Elements-0.15 caps.pl 100755 001750 001750 1203 12633504025 16355 0 ustar 00voj voj 000000 000000 Pandoc-Elements-0.15/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);
# alternative to modify in-place (comment out previous line to enable)
$_->{c} = 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
script 000755 001750 001750 0 12633504025 14421 5 ustar 00voj voj 000000 000000 Pandoc-Elements-0.15 pandocwalk 100755 001750 001750 3041 12633504025 16630 0 ustar 00voj voj 000000 000000 Pandoc-Elements-0.15/script #!/usr/bin/env perl
use strict;
use 5.010;
our $VERSION = '0.15';
use Pod::Usage;
pod2usage(1) unless @ARGV;
my $script = pop @ARGV;
my $pipe;
if ( -f $script ) {
$pipe = sub {
exec($script) or die "can't exec $script\n";
};
}
else {
use Pandoc::Filter::Lazy;
my $filter = Pandoc::Filter::Lazy->new($script);
if ( $filter->error ) {
say STDERR "Failed to compile filter code:\n";
say STDERR $filter->code( indent => ' ' ) . "\n";
say STDERR $filter->error;
exit 1;
}
$pipe = sub {
my $json = ;
exit 1 if substr( $json, 0, 1 ) ne '[';
my $ast = Pandoc::Elements::pandoc_json($json);
$filter->apply($ast);
};
}
my $pid = open( STDIN, "-|" ) // die "cannot fork: $!\n";
if ( $pid == 0 ) {
exec( 'pandoc', @ARGV, '-t', 'json' ) or die "can't exec pandoc: $!\n";
}
else {
binmode STDOUT, ':encoding(UTF-8)';
$pipe->();
}
=head1 NAME
pandocwalk - parse document with pandoc and process abstract syntax tree
=head1 SYNOPSIS
pandocwalk [ options ] [ SCRIPT | 'SELECTOR => ACTION' ]
Calls pandoc with given options to parse a document and process its abstract
syntax tree. A processing script must be given as executable file or as Perl
code to filter the document. See L for filter syntax.
=head2 EXAMPLES
Extract all URLs from a HTML file:
pandocwalk document.html 'Link => say $_->url'
Extract table of contents from a LaTeX file:
pandocwalk document.tex 'Header => say " " x $_->level, $_->string'
=cut
pod2pandoc 100755 001750 001750 4404 12633504025 16542 0 ustar 00voj voj 000000 000000 Pandoc-Elements-0.15/script #!/usr/bin/env perl
use strict;
require 5.010;
my $VERSION = '0.15';
use Getopt::Long;
use Pod::Usage;
use Pod::Simple::Pandoc;
my %opt;
GetOptions( \%opt, 'help|h|?', 'man', 'filter=s' ) or exit 1;
pod2usage(1) if $opt{help};
pod2usage( -verbose => 2 ) if $opt{man};
@ARGV = '-' unless @ARGV;
my $combined;
foreach my $input (@ARGV) {
my $doc = Pod::Simple::Pandoc->parse_file($input);
if ($combined) {
push @{ $combined->content }, @{ $doc->content };
}
else {
$combined = $doc;
}
}
if ( $opt{filter} ) {
use Pandoc::Filter::Lazy;
my $filter = Pandoc::Filter::Lazy->new( $opt{filter} );
if ( $filter->error ) {
say STDERR "Failed to compile filter code:\n";
say STDERR $filter->code( indent => ' ' ) . "\n";
say STDERR $filter->error;
exit 1;
}
else {
$filter->apply($combined);
}
}
print $combined->to_json;
=head1 NAME
pod2pandoc - convert Pod to Pandoc document model
=head1 SYNOPSIS
pod2pandoc [OPTIONS] [INPUT...] | pandoc -f json ...
=head1 DESCRIPTION
C converts POD format documentation (L) to the abstract
document model used by L for further processing to
other document formats (HTML, Markdown, LaTeX, PDF, EPUB, docx, ODT, man,
ICML...). By default or with input C<-> a document is read from STDIN. Multiple
input files are combined to one document.
Conversion is based on L which uses L.
=head2 Examples
pod2pandoc Module.pm | pandoc -f json -o Module.pdf
pod2pandoc Module.pm | pandoc -f json -o Module.html
Or even shorter (not implemented yet):
pod2pandoc Module.pm -- -o Module.pdf
With processing:
pod2pandoc --filter 'Header => Para [ Strong [ Str $_->string ] ]' Module.pm
=head1 OPTIONS
=over
=item --filter 'SELECTOR => ACTION'
Preprocess the document. See L for filter syntax.
=item --help|-h|-?
Print out usage information and exit
=item --man
Print the full manual page and exit
=back
=head1 SEE ALSO
This script together with Pandoc can be used as customizable replacement for
specialized Pod converter scripts such as L, L,
L, L, L, L, and L.
=cut
pandoc_filter.t 100644 001750 001750 2107 12633504025 16516 0 ustar 00voj voj 000000 000000 Pandoc-Elements-0.15/t use 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('{"t":"Str","c":"☃"}');
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.pl 100755 001750 001750 1026 12633504025 16674 0 ustar 00voj voj 000000 000000 Pandoc-Elements-0.15/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.pl 100644 001750 001750 1316 12633504025 16730 0 ustar 00voj voj 000000 000000 Pandoc-Elements-0.15/examples #!/usr/bin/env perl
use strict;
=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 sub {
my ($e,$f,$m) = @_;
return unless $e->name eq 'Emph' and $f eq '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
deflist.pl 100755 001750 001750 1404 12633504025 17064 0 ustar 00voj voj 000000 000000 Pandoc-Elements-0.15/examples #!/usr/bin/env perl
use strict;
=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
theorem.pl 100644 001750 001750 2246 12633504025 17077 0 ustar 00voj voj 000000 000000 Pandoc-Elements-0.15/examples #!/usr/bin/env perl
use strict;
=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 sub {
my ($e, $f, $m) = @_;
return unless $e->match('Div.theorem');
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
comments.pl 100755 001750 001750 1533 12633504025 17262 0 ustar 00voj voj 000000 000000 Pandoc-Elements-0.15/examples #!/usr/bin/env perl
use strict;
=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
Pandoc 000755 001750 001750 0 12633504025 15067 5 ustar 00voj voj 000000 000000 Pandoc-Elements-0.15/lib Filter.pm 100644 001750 001750 12037 12633504025 17035 0 ustar 00voj voj 000000 000000 Pandoc-Elements-0.15/lib/Pandoc package Pandoc::Filter;
use strict;
use warnings;
use 5.010;
our $VERSION = '0.15';
use JSON;
use Carp;
use Scalar::Util 'reftype';
use List::Util;
use Pandoc::Walker;
use Pandoc::Elements ();
use parent 'Exporter';
our @EXPORT = qw(pandoc_filter pandoc_walk stringify);
sub stringify {
$_[0]->string;
}
sub pandoc_walk(@) { ## no critic
my $filter = Pandoc::Filter->new(@_);
my $ast = Pandoc::Elements::pandoc_json();
binmode STDOUT, ':encoding(UTF-8)';
$filter->apply( $ast, @ARGV ? $ARGV[0] : '' );
}
sub pandoc_filter(@) { ## no critic
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;
}
# constructor and methods
sub new {
my $class = shift;
bless {
action => Pandoc::Walker::action(@_),
error => '',
}, $class;
}
sub error {
$_[0]->{error};
}
sub action {
return $_[0]->{action};
my $actions = $_[0]->{actions};
sub {
my ( $element, $format, $meta ) = @_;
foreach my $action (@$actions) {
local $_ = $element;
$action->( $element, $format, $meta );
}
}
}
# TODO: refactor with method action
sub apply {
my ( $self, $ast, $format, $meta ) = @_;
$format ||= '';
$meta ||= eval { $ast->[0]->{unMeta} } || {};
if ( $self->{action} ) {
Pandoc::Walker::transform( $ast, $self->{action}, $format, $meta );
}
# foreach my $action (@{$self->{actions}}) {
# Pandoc::Walker::transform( $ast, $action, $format, $meta );
# }
$ast;
}
1;
__END__
=encoding utf-8
=head1 NAME
Pandoc::Filter - process Pandoc abstract syntax tree
=head1 SYNOPSIS
The following 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;
return Para [ Emph $_->content ];
};
To apply this filter on a Markdown file:
pandoc --filter flatten.pl -t markdown < input.md
See L for more
examples of filters.
=head1 DESCRIPTION
Pandoc::Filter is a port of
L from Python to modern
Perl. The module provide provides functions to aid writing Perl scripts that
process a L abstract syntax tree (AST) serialized as
JSON. See L for documentation of AST elements.
This module is based on L and its function C. Please
consider using its function interface (C, C, C) instead
of this module.
=head1 METHODS
=head2 new( @actions | %actions )
Create a new filter with one or more action functions, given as code
reference(s). Each function is expected to return an element, an empty array
reference, or C to modify, remove, or keep a traversed element in the
AST. The current element is passed to an action function both as first argument
and in the special variable C<$_>. Output format (if specified) and document
metadata are passed as second and third argument.
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.
=head2 size
Return the number of actions in this filter.
=head1 FUNCTIONS
The following functions are exported by default.
=head2 pandoc_walk( @actions | %actions )
Read a single line of JSON from STDIN and walk down the AST. Implicitly sets
binmode UTF-8 for STDOUT.
=head2 pandoc_filter( @actions | %actions )
Read a single line of JSON from STDIN, apply actions and print the resulting
AST as single line of JSON. This function is roughly equivalent to
my $ast = Pandoc::Elements::pandoc_json(<>);
Pandoc::Filter->new(@actions)->apply($ast, @ARGV ? $ARGV[0] : ());
say $ast->to_json;
=head2 stringify( $ast )
Walks the ast and returns concatenated string content, leaving out all
formatting. This function is also accessible as method of L
since version 0.12, so I in a later
version.
=head1 SEE ALSO
Script L installed with this module facilitates execution of
C to traverse a document.
=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.pm 100644 001750 001750 14235 12633504025 17037 0 ustar 00voj voj 000000 000000 Pandoc-Elements-0.15/lib/Pandoc package Pandoc::Walker;
use strict;
use warnings;
use 5.010;
our $VERSION = '0.15';
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 { $_ = $_[0]; $action->( $_[0], @args ) };
}
else {
return $action;
}
}
sub action {
my @actions;
my @args;
# $selector => $action [, @arguments ]
if ( !ref $_[0] ) {
@actions = ( shift, shift );
@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) {
$_ = $_[0];
@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);
# replace current item with result element(s)
if ( defined $res ) {
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 { $_ = $_[0]; $action->(@_); return } );
}
sub query(@) { ## no critic
my $ast = shift;
my $action = action(@_);
my $list = [];
transform( $ast, sub { $_ = $_[0]; push @$list, $action->(@_); 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.
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. 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),
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
pod-simple-pandoc.t 100644 001750 001750 1250 12633504025 17216 0 ustar 00voj voj 000000 000000 Pandoc-Elements-0.15/t use strict;
use Test::More;
use Pandoc::Elements;
use_ok 'Pod::Simple::Pandoc';
my $parser = new_ok('Pod::Simple::Pandoc');
my $file = 'lib/Pod/Simple/Pandoc.pm';
# note explain $parser->_parser->parse_file($file)->root;
my $doc = $parser->parse_file($file);
isa_ok( $doc, 'Pandoc::Document', );
is_deeply $doc->query(
Header => sub { $_[0]->level == 1 ? $_[0]->string : () } ),
[ 'NAME', 'SYNOPSIS', 'DESCRIPTION', 'METHODS', 'MAPPING', 'LIMITATIONS', 'SEE ALSO' ],
'got header';
$doc = $parser->parse_string(<
=back
POD
is_deeply $doc,
Document({}, [ BlockQuote [ Para [ Emph [ Str 'hello' ] ] ] ]),
'parse_string';
done_testing;
Elements.pm 100644 001750 001750 50764 12633504025 17375 0 ustar 00voj voj 000000 000000 Pandoc-Elements-0.15/lib/Pandoc package Pandoc::Elements;
use strict;
use warnings;
use 5.010;
our $VERSION = '0.15';
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'],
# 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 content) ],
Code => [ Inline => qw(attr content) ],
Space => ['Inline'],
LineBreak => ['Inline'],
Math => [ Inline => qw(type content) ],
RawInline => [ Inline => qw(format content) ],
Link => [ Inline => qw(content target) ],
Image => [ Inline => qw(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 constructors
foreach (
qw(DefaultDelim Period OneParen TwoParens SingleQuote DoubleQuote
DisplayMath InlineMath AuthorInText SuppressAuthor NormalCitation
AlignLeft AlignRight AlignCenter AlignDefault DefaultStyle Example
Decimal LowerRoman UpperRoman LowerAlpha UpperAlpha)
)
{
$ELEMENTS{$_} = ['Inline'];
}
use Carp;
use JSON qw(decode_json);
use Scalar::Util qw(reftype);
use Pandoc::Walker qw(walk);
use parent 'Exporter';
our @EXPORT = ( keys %ELEMENTS, qw(Document attributes citation pandoc_json) );
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 $class = "Pandoc::Document::$name";
my @parents = map { "Pandoc::Document::$_" } ($parent);
$parent = join ' ', map { "Pandoc::Document::$_" } $parent,
map { 'AttributesRole' } grep { $_ eq 'attr' } @accessors;
eval "package $class; our \@ISA = qw($parent);";
*{ __PACKAGE__ . "::$name" } = Scalar::Util::set_prototype(
sub {
croak "$name expects $numargs arguments, but given " . scalar @_
if @_ != $numargs;
bless { t => $name, c => ( @_ == 1 ? $_[0] : [@_] ) }, $class;
},
'$' x $numargs
);
for ( my $i = 0 ; $i < @accessors ; $i++ ) {
my $code = @accessors == 1 ? "\$_[0]->{c}" : "\$_[0]->{c}->[$i]";
# auto-bless on access via accessor (TODO: move to constructor?)
if ( $accessors[$i] =~ s/:\[(.+)\]$// ) {
$code = "[ map { bless \$_, 'Pandoc::Document::$1' } \@{$code} ]";
}
for ( split '/', $accessors[$i] ) {
*{ $class . "::$_" } = 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($$) {
@_ == 2 or croak "Document expects 2 arguments, but given " . scalar @_;
return bless [ { unMeta => $_[0] }, $_[1] ], 'Pandoc::Document';
}
# specific accessors
sub Pandoc::Document::Link::url { $_[0]->{c}->[1][0] }
sub Pandoc::Document::Link::title { $_[0]->{c}->[1][1] }
sub Pandoc::Document::Image::url { $_[0]->{c}->[1][0] }
sub Pandoc::Document::Image::title { $_[0]->{c}->[1][1] }
sub Pandoc::Document::DefinitionPair::term { $_[0]->[0] }
sub Pandoc::Document::DefinitionPair::definitions { $_[0]->[1] }
# additional functions
sub attributes($) {
my ($attrs) = @_;
return [
defined $attrs->{id} ? $attrs->{id} : '',
defined $attrs->{classes} ? $attrs->{classes} : [],
[
map { $_ => $attrs->{$_} }
grep { $_ ne 'id' and $_ ne 'classes' }
keys %$attrs
]
];
}
sub citation($) {
my $a = shift;
{
citationId => $a->{id} // "missing",
citationPrefix => $a->{prefix} // [],
citationSuffix => $a->{suffix} // [],
citationMode => $a->{mode} // bless(
{ t => 'NormalCitation', c => [] },
'Pandoc::Document::NormalCitation'
),
citationNoteNum => $a->{num} // 0,
citationHash => $a->{hash} // 1,
};
}
sub pandoc_json($) {
shift if $_[0] =~ /^Pandoc::/;
my $ast = eval { decode_json( $_[0] ) };
if ($@) {
$@ =~ s/ at [^ ]+Elements\.pm line \d+//;
chomp $@;
croak $@;
}
return unless reftype $ast;
if ( reftype $ast eq 'ARRAY' ) {
$ast = Document( $ast->[0]->{unMeta}, $ast->[1] );
}
elsif ( reftype $ast eq 'HASH' ) {
$ast = element( $ast->{t}, $ast->{c} );
}
walk $ast, sub {
bless $_[0], 'Pandoc::Document::' . $_[0]->{t};
};
return $ast;
}
# document element packages
{
package Pandoc::Document;
use strict;
our $VERSION = '0.04';
our @ISA = ('Pandoc::Document::Element');
sub TO_JSON { [ @{ $_[0] } ] }
sub name { 'Document' }
sub meta { $_[0]->[0]->{unMeta} }
sub content { $_[0]->[1] }
sub is_document { 1 }
}
{
package Pandoc::Document::Element;
use strict;
use warnings;
our $VERSION = $Pandoc::Document::VERSION;
use JSON ();
use Scalar::Util qw(reftype);
use Pandoc::Walker ();
sub to_json {
JSON->new->utf8->convert_blessed->encode( $_[0] );
}
sub TO_JSON { return { %{ $_[0] } } }
sub name { $_[0]->{t} }
sub content { $_[0]->{c} }
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|Math)$/ ) {
return $_[0]->content;
}
elsif ( $_[0]->name =~ /^(LineBreak|Space)$/ ) {
return ' ';
}
join '', @{
$_[0]->query(
{
'Str|Code|Math' => sub { $_->content },
'LineBreak|Space' => 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);
}
}
{
package Pandoc::Document::AttributesRole;
my $IDENTIFIER = qr{\p{L}(\p{L}|[0-9_:.-])*};
sub id { $_[0]->attr->[0] }
sub classes { $_[0]->attr->[1] }
sub class { join ' ', @{ $_[0]->classes } }
sub match_attributes {
my ( $self, $selector ) = @_;
$selector =~ s/^\s+|\s+$//g;
while ( $selector ne '' ) {
if ( $selector =~ s/^#($IDENTIFIER)\s*// ) {
return 0 unless $self->id eq $1;
}
elsif ( $selector =~ s/^\.($IDENTIFIER)\s*// ) {
return 0 unless grep { $1 eq $_ } @{ $self->classes };
}
else {
return 0;
}
}
return 1;
}
}
{
package Pandoc::Document::Block;
our $VERSION = $PANDOC::Document::VERSION;
our @ISA = ('Pandoc::Document::Element');
sub is_block { 1 }
}
{
package Pandoc::Document::Inline;
our $VERSION = $PANDOC::Document::VERSION;
our @ISA = ('Pandoc::Document::Element');
sub is_inline { 1 }
}
{
package Pandoc::Document::Meta;
our $VERSION = $PANDOC::Document::VERSION;
our @ISA = ('Pandoc::Document::Element');
sub is_meta { 1 }
}
1;
__END__
=encoding utf-8
=head1 NAME
Pandoc::Elements - create and process Pandoc documents
=begin markdown
# STATUS
[](https://travis-ci.org/nichtich/Pandoc-Elements)
[](https://coveralls.io/r/nichtich/Pandoc-Elements)
[](http://cpants.cpanauthors.org/dist/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!' ],
])->to_json;
can be converted for instance to HTML with 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 create abstract syntax trees
(AST) of L documents. Pandoc can convert the
resulting data structure to many other document formats, such as HTML, LaTeX,
ODT, and ePUB.
Please make sure to use at least Pandoc 1.12 when processing documents
See also module L, command line scripts L and
L, and the internal modules L,
L, and L.
=head2 EXPORTED 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 helper following functions C, C, C, and
C.
=back
=head3 pandoc_json $json
Parse a JSON string, as emitted by pandoc in JSON format. This is the reverse
to method C.
=head3 attributes { key => $value, ... }
Maps a hash reference into an attributes list with id, classes, and ordered
key-value pairs. The special keys C and C are recognized but
setting multi-value attributes or controlled order is not supported with this
function. You can always manually create an attributes structure:
[ $id, [ @classes ], [ key => $value, ... ] ]
Elements with attributes (element accessor method C) also provide the
accessor method C, C, and C. See L for
easy access to key-value-pairs.
=head3 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>AuthorInText>, C), C (integer), and
C (integer). The helper method C can be used to
construct such hash by filling in default values and 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]
=head3 element( $name => $content )
Create a Pandoc document element of arbitrary name. This function is only
exported on request.
=head1 ELEMENTS
Document elements are encoded as Perl data structures equivalent to the JSON
structure, emitted with pandoc output format C. All elements are blessed
objects that provide the following element methods and additional accessor
methods specific to each element.
=head2 ELEMENT METHODS
=head3 to_json
Return the element as JSON encoded string. The following are equivalent:
$element->to_json;
JSON->new->utf8->convert_blessed->encode($element);
=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
a link text (C) and a link target (C) with C and
C.
=head3 is_block
True if the element is a L
=head3 is_inline
True if the element is an inline L
=head3 is_meta
True if the element is a L
=head3 is_document
True if the element is a L
=head3 walk(...)
Walk the element tree with L
=head3 query(...)
Query the element to extract results with L
=head3 transform(...)
Transform the element tree with L
=head3 string
Returns a concatenated string of element content, leaving out all formatting.
=head2 BLOCK ELEMENTS
=head3 BlockQuote
Block quote, consisting of a list of L (C)
BlockQuote [ @blocks ]
=head3 BulletList
Unnumbered list of items (C=C), each a list of
L
BulletList [ [ @blocks ] ]
=head3 CodeBlock
Code block (literal string C) with attributes (C)
CodeBlock $attributes, $content
=head3 DefinitionList
Definition list, consisting of a list of pairs (C=C),
each a term (C, a list of L) and one
or more definitions (C, a list of L).
DefinitionList [ @definitions ]
# each item in @definitions being a pair of the form
[ [ @inlines ], [ @blocks ] ]
=head3 Div
Generic container of L (C) with attributes
(C).
Div $attributes, [ @blocks ]
=head3 Header
Header with C (integer), attributes (C), and text (C, a
list of L).
Header $level, $attributes, [ @inlines ]
=head3 HorizontalRule
Horizontal rule
HorizontalRule
=head3 Null
Nothing
Null
=head3 OrderedList
Numbered list of items (C=C), each a list of L), preceded by list attributes (start number, numbering style, and
delimiter).
OrderedList [ $start, $style, $delim ], [ [ @blocks ] ]
Supported styles are C, C, C, C,
C, C, and C.
Supported delimiters are C, C, C, and
C.
=head3 Para
Paragraph, consisting of a list of L
(C).
Para [ $elements ]
=head3 Plain
Plain text, not a paragraph, consisting of a list of L (C).
Plain [ @inlines ]
=head3 RawBlock
Raw block with C and C string.
RawBlock $format, $content
=head3 Table
Table, with C
, column C, relative column C (0 =
default), column C (each a list of L), and
C (each a list of lists of L).
Table [ @inlines ], [ @alignments ], [ @width ], [ @headers ], [ @rows ]
Possible alignments are C, C, C, and
C.
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 and a list of L
(C). See helper function L to construct citations.
Cite [ @citations ], [ @inlines ]
=head3 Code
Inline code, a literal string (C) with attributes (C)
Code attributes { %attr }, $content
=head3 Emph
Emphasized text, a list of L (C).
Emph [ @inlines ]
=head3 Image
Image with alt text (C, a list of L) and
C (list of C and C).
Image [ @inlines ], [ $url, $title ]
=head3 LineBreak
Hard line break
LineBreak
=head3 Link
Hyperlink with link text (C, a list of L)
and C (list of C and C).
Link [ @inlines ], [ $url, $title ]
=head3 Math
TeX math, given as literal string (C) with C (one of
C and C).
Math $type, $content
=head3 Note
Footnote or Endnote, a list of L (C).
Note [ @blocks ]
=head3 Quoted
Quoted text with quote C (one of C and C) and a
list of L (C).
Quoted $type, [ @inlines ]
=head3 RawInline
Raw inline with C (a string) and C (a string).
RawInline $format, $content
=head3 SmallCaps
Small caps text, a list of L (C).
SmallCaps [ @inlines ]
=head3 Space
Inter-word space
Space
=head3 Span
Generic container of L (C) with attributes
(C).
Span attributes { %attr }, [ @inlines ]
=head3 Str
Plain text, a string (C).
Str $text
=head3 Strikeout
Strikeout text, a list of L (C).
Strikeout [ @inlines ]
=head3 Strong
Strongly emphasized text, a list of L (C).
Strong [ @inlines ]
=head3 Subscript
Subscripted text, a list of L (C).
Supscript [ @inlines ]
=head3 Superscript
Superscripted text, a list of L (C).
Superscript [ @inlines ]
=head2 METADATA ELEMENTS
=head3 MetaBlocks
=head3 MetaBool
=head3 MetaInlines
=head3 MetaList
=head3 MetaMap
=head3 MetaString
=head2 DOCUMENT ELEMENT
=head3 Document
Root element, consisting of metadata hash (C) and document element array
(C).
Document $meta, [ @blocks ]
=head2 TYPE KEYWORDS
The following document elements are only as used as type keywords in other
document elements:
=over
=item
C, C
=item
C, C
=item
C, C, C
=item
C, C, C, C
=item
C, C, C, C, C,
C, C
=item
C, C, C, C
=back
=head1 SEE ALSO
L implements a wrapper around the pandoc executable.
L