#!/bin/env perl -w

#
# cutief8 - a script to convert plain ASCII quotes and double dashes
# to their "smart" UTF-8 equivalents -- left and right quotes and em-dashes.
#
# Programatically generated by Pete Goodeve from
#   SmartyPants  -  A Plug-In for Movable Type, Blosxom, and BBEdit
#   by John Gruber
#   http://daringfireball.net
#
# See the readme or POD for details, installation instructions, and
# license information.
#
# Original Copyright (c) 2003-2004 John Gruber
# This conversion 2016/7/12 Pete Goodeve
#

$VERSION = "1.1";

# Configurable variables:
my $smartypants_attr = "1";  # Can be changed by command-line parameter:
                             #  1 =>  "--" for em-dashes; no en-dash support
                             #  2 =>  "---" for em-dashes; "--" for en-dashes
                             #  3 =>  "--" for em-dashes; "---" for en-dashes
                             #  See docs for more configuration options.

my $html_mode = 0;           # set true if html so tags will be skipped

# Globals:
my $tags_to_skip = qr!<(/?)(?:pre|code|kbd|script|math)[\s>]!;

# Main entry:
{

		#### Check for command-line switches: ###########################
		my %cli_opts;
		use Getopt::Long;
		Getopt::Long::Configure('pass_through');
		GetOptions(\%cli_opts,
			'version',
			'shortversion',
			'1',
			'2',
			'3',
			'n',
			'm',
			'r',
			't',
		);
		if ($cli_opts{'version'}) {		# Version info
			print "\nThis is cutief8, version $VERSION.\n";
			exit 0;
		}
		if ($cli_opts{'shortversion'}) {		# Just the version number string.
			print $VERSION;
			exit 0;
		}
		if ($cli_opts{'1'}) { $smartypants_attr = 1 };	# default
		if ($cli_opts{'2'}) { $smartypants_attr = 2 };	# old SmartyPants style
		if ($cli_opts{'3'}) { $smartypants_attr = 3 };
		if ($cli_opts{'n'}) { $smartypants_attr = 2 };	# more mnemonic...
		if ($cli_opts{'m'}) { $smartypants_attr = 3 };
		if ($cli_opts{'r'}) { $smartypants_attr = -1 };
		if ($cli_opts{'t'}) { $html_mode = 1 };         # 't' for tags (html)


		#### Process incoming text: #####################################
     my $old = $/;
     undef $/;               # slurp the whole file
     my $text = <>;
     $/ = $old;
     print SmartyPants($text, $smartypants_attr);
}



sub SmartyPants {
    # Parameters:
    my $text = shift;   # text to be parsed
    my $attr = shift;   # value of the smart_quotes="" attribute

    # Options to specify which transformations to make:
    my ($do_quotes, $do_backticks, $do_dashes, $do_ellipses, $do_stupefy);
    my $convert_quot = 0;  # should we translate &quot; entities into normal quotes?

    # Parse attributes:
    # 0 : do nothing
    # 1 : set all
    # 2 : set all, using old school en- and em- dash shortcuts
    # 3 : set all, using inverted old school en and em- dash shortcuts
    # 
    # q : quotes
    # b : backtick quotes (``double'' only)
    # B : backtick quotes (``double'' and `single')
    # d : dashes
    # D : old school dashes
    # i : inverted old school dashes
    # e : ellipses
    # w : convert &quot; entities to " for Dreamweaver users

    if ($attr eq "0") {
        # Do nothing.
        return $text;
    }
    elsif ($attr eq "1") {
        # Do everything, turn all options on.
        $do_quotes    = 1;
        $do_backticks = 1;
        $do_dashes    = 1;
        $do_ellipses  = 1;
    }
    elsif ($attr eq "2") {
        # Do everything, turn all options on, use old school dash shorthand.
        $do_quotes    = 1;
        $do_backticks = 1;
        $do_dashes    = 2;
        $do_ellipses  = 1;
    }
    elsif ($attr eq "3") {
        # Do everything, turn all options on, use inverted old school dash shorthand.
        $do_quotes    = 1;
        $do_backticks = 1;
        $do_dashes    = 3;
        $do_ellipses  = 1;
    }
    elsif ($attr eq "-1") {
        # Special "stupefy" mode.
        $do_stupefy   = 1;
    }
    else {
        my @chars = split(//, $attr);
        foreach my $c (@chars) {
            if    ($c eq "q") { $do_quotes    = 1; }
            elsif ($c eq "b") { $do_backticks = 1; }
            elsif ($c eq "B") { $do_backticks = 2; }
            elsif ($c eq "d") { $do_dashes    = 1; }
            elsif ($c eq "D") { $do_dashes    = 2; }
            elsif ($c eq "i") { $do_dashes    = 3; }
            elsif ($c eq "e") { $do_ellipses  = 1; }
            elsif ($c eq "w") { $convert_quot = 1; }
            else {
                # Unknown attribute option, ignore.
            }
        }
    }

    my $tokens ||= _tokenize($text);
    my $result = '';
    my $in_pre = 0;  # Keep track of when we're inside <pre> or <code> tags.

    my $prev_token_last_char = "";  # This is a cheat, used to get some context
                                    # for one-character tokens that consist of 
                                    # just a quote char. What we do is remember
                                    # the last character of the previous text
                                    # token, to use as context to curl single-
                                    # character quote tokens correctly.

    foreach my $cur_token (@$tokens) {
        if ($cur_token->[0] eq "tag" && $html_mode) {
            # Don't mess with quotes inside tags.
            $result .= $cur_token->[1];
            if ($cur_token->[1] =~ m/$tags_to_skip/) {
                $in_pre = defined $1 && $1 eq '/' ? 0 : 1;
            }
        } else {
            my $t = $cur_token->[1];
            my $last_char = substr($t, -1); # Remember last char of this token before processing.
            if (! $in_pre) {
                $t = ProcessEscapes($t);

                if ($convert_quot) {
                    $t =~ s/&quot;/"/g;
                }

                if ($do_dashes) {
                    $t = EducateDashes($t)                  if ($do_dashes == 1);
                    $t = EducateDashesOldSchool($t)         if ($do_dashes == 2);
                    $t = EducateDashesOldSchoolInverted($t) if ($do_dashes == 3);
                }

                $t = EducateEllipses($t) if $do_ellipses;

                # Note: backticks need to be processed before quotes.
                if ($do_backticks) {
                    $t = EducateBackticks($t);
                    $t = EducateSingleBackticks($t) if ($do_backticks == 2);
                }

                if ($do_quotes) {
                    if ($t eq q/'/) {
                        # Special case: single-character ' token
                        if ($prev_token_last_char =~ m/\S/) {
                            $t = "’";
                        }
                        else {
                            $t = "‘";
                        }
                    }
                    elsif ($t eq q/"/) {
                        # Special case: single-character " token
                        if ($prev_token_last_char =~ m/\S/) {
                            $t = "”";
                        }
                        else {
                            $t = "“";
                        }
                    }
                    else {
                        # Normal case:                  
                        $t = EducateQuotes($t);
                    }
                }

                $t = StupefyEntities($t) if $do_stupefy;
                $t = UnProcessEscapes($t);
            }
            $prev_token_last_char = $last_char;
            $result .= $t;
        }
    }

    return $result;
}


sub EducateQuotes {
#
#   Parameter:  String.
#
#   Returns:    The string, with "educated" curly quote HTML entities.
#
#   Example input:  "Isn't this fun?"
#   Example output: “Isn’t this fun?”
#

    local $_ = shift;

    # Tell perl not to gripe when we use $1 in substitutions,
    # even when it's undefined. Use $^W instead of "no warnings"
    # for compatibility with Perl 5.005:
    local $^W = 0;


    # Make our own "punctuation" character class, because the POSIX-style
    # [:PUNCT:] is only available in Perl 5.6 or later:
    my $punct_class = qr/[!"#\$\%'()*+,-.\/:;<=>?\@\[\\\]\^_`{|}~]/;

    # Special case if the very first character is a quote
    # followed by punctuation at a non-word-break. Close the quotes by brute force:
    s/^'(?=$punct_class\B)/’/;
    s/^"(?=$punct_class\B)/”/;


    # Special case for double sets of quotes, e.g.:
    #   <p>He said, "'Quoted' words in a larger quote."</p>
    s/"'(?=\w)/“‘/g;
    s/'"(?=\w)/‘“/g;

    # Special case for decade abbreviations (the '80s):
    s/'(?=\d{2}s)/’/g;

    my $close_class = qr![^\ \t\r\n\[\{\(\-]!;
    my $dec_dashes = qr/–|—/;

    # Get most opening single quotes:
    s {
        (
            \s          |   # a whitespace char, or
            &nbsp;      |   # a non-breaking space entity, or
            --          |   # dashes, or
            &[mn]dash;  |   # named dash entities
            $dec_dashes |   # or decimal entities
            &\#x201[34];    # or hex
        )
        '                   # the quote
        (?=\w)              # followed by a word character
    } {$1‘}xg;
    # Single closing quotes:
    s {
        ($close_class)?
        '
        (?(1)|          # If $1 captured, then do nothing;
          (?=\s | s\b)  # otherwise, positive lookahead for a whitespace
        )               # char or an 's' at a word ending position. This
                        # is a special case to handle something like:
                        # "<i>Custer</i>'s Last Stand."
    } {$1’}xgi;

    # Any remaining single quotes should be opening ones:
    s/'/‘/g;


    # Get most opening double quotes:
    s {
        (
            \s          |   # a whitespace char, or
            &nbsp;      |   # a non-breaking space entity, or
            --          |   # dashes, or
            &[mn]dash;  |   # named dash entities
            $dec_dashes |   # or decimal entities
            &\#x201[34];    # or hex
        )
        "                   # the quote
        (?=\w)              # followed by a word character
    } {$1“}xg;

    # Double closing quotes:
    s {
        ($close_class)?
        "
        (?(1)|(?=\s))   # If $1 captured, then do nothing;
                           # if not, then make sure the next char is whitespace.
    } {$1”}xg;

    # Any remaining quotes should be opening ones.
    s/"/“/g;

    return $_;
}


sub EducateBackticks {
#
#   Parameter:  String.
#   Returns:    The string, with ``backticks'' -style double quotes
#               translated into HTML curly quote entities.
#
#   Example input:  ``Isn't this fun?''
#   Example output: “Isn't this fun?”
#

    local $_ = shift;
    s/``/“/g;
    s/''/”/g;
    return $_;
}


sub EducateSingleBackticks {
#
#   Parameter:  String.
#   Returns:    The string, with `backticks' -style single quotes
#               translated into HTML curly quote entities.
#
#   Example input:  `Isn't this fun?'
#   Example output: ‘Isn’t this fun?’
#

    local $_ = shift;
    s/`/‘/g;
    s/'/’/g;
    return $_;
}


sub EducateDashes {
#
#   Parameter:  String.
#
#   Returns:    The string, with each instance of "--" translated to
#               an em-dash UTF-8 character.
#

    local $_ = shift;
#    s/--/—/g;
    s/(^|[^-])--([^-]|$)/$1—$2/g;
    return $_;
}


sub EducateDashesOldSchool {
#
#   Parameter:  String.
#
#   Returns:    The string, with each instance of "--" translated to
#               an en-dash UTF-8 character, and each "---" translated to
#               an em-dash UTF-8 character.
#

    local $_ = shift;
#    s/---/—/g;    # em
#    s/--/–/g;     # en
    s/(^|[^-])---([^-]|$)/$1—$2/g;    # em
    s/(^|[^-])--([^-]|$)/$1–$2/g;     # en
    return $_;
}


sub EducateDashesOldSchoolInverted {
#
#   Parameter:  String.
#
#   Returns:    The string, with each instance of "--" translated to
#               an em-dash UTF-8 character, and each "---" translated to
#               an en-dash UTF-8 character. Two reasons why: First, unlike the
#               en- and em-dash syntax supported by
#               EducateDashesOldSchool(), it's compatible with existing
#               entries written before SmartyPants 1.1, back when "--" was
#               only used for em-dashes.  Second, em-dashes are more
#               common than en-dashes, and so it sort of makes sense that
#               the shortcut should be shorter to type. (Thanks to Aaron
#               Swartz for the idea.)
#

    local $_ = shift;
#    s/---/–/g;    # en
#    s/--/—/g;     # em
    s/(^|[^-])---([^-]|$)/$1–$2/g;     # en
    s/(^|[^-])--([^-]|$)/$1—$2/g;    # em
    return $_;
}


sub EducateEllipses {
#
#   Parameter:  String.
#   Returns:    The string, with each instance of "..." translated to
#               an ellipsis UTF-8 character. Also converts the case where
#               there are spaces between the dots.
#
#   Example input:  Huh...?
#   Example output: Huh…?
#

    local $_ = shift;
    s/\.\.\./…/g;
    s/\. \. \./…/g;
    return $_;
}


sub StupefyEntities {
#
#   Parameter:  String.
#   Returns:    The string, with each SmartyPants UTF-8 character translated to
#               its ASCII counterpart.
#
#   Example input:  “Hello — world.”
#   Example output: "Hello -- world."
#

    local $_ = shift;

    s/–/-/g;      # en-dash
    s/—/--/g;     # em-dash

    s/‘/'/g;      # open single quote
    s/’/'/g;      # close single quote

    s/“/"/g;      # open double quote
    s/”/"/g;      # close double quote

    s/…/.../g;    # ellipsis

    return $_;
}


sub SmartyPantsVersion {
    return $VERSION;
}


sub ProcessEscapes {
#
#   Parameter:  String.
#   Returns:    The string, with after processing the following backslash
#               escape sequences. This is useful if you want to force a "dumb"
#               quote or other character to appear. The numeric  entities
#               generated will be reverted by UnProcessEscapes after other processing.
#
#               Escape  Value
#               ------  -----
#               \\      &#92;
#               \"      &#34;
#               \'      &#39;
#               \.      &#46;
#               \-      &#45;
#               \`      &#96;
#
    local $_ = shift;

    s! \\\\ !&#92;!gx;
    s! \\"  !&#34;!gx;
    s! \\'  !&#39;!gx;
    s! \\\. !&#46;!gx;
    s! \\-  !&#45;!gx;
    s! \\`  !&#96;!gx;

    return $_;
}


sub UnProcessEscapes {
#
#   Parameter:  String with numeric entities from backslash escapes.
#   Returns:    The string, with original characters restored.
#
#                 Value
#                 -----
#                 &#92;    \    
#                 &#34;    "
#                 &#39;    '
#                 &#46;    .
#                 &#45;    -
#                 &#96;    `
#
    local $_ = shift;

    s!&#92;!\\!g;
    s!&#34;!"!g;
    s!&#39;!'!g;
    s!&#46;!.!g;
    s!&#45;!-!g;
    s!&#96;!`!g;

    return $_;
}


sub _tokenize {
#
#   Parameter:  String containing HTML markup.
#   Returns:    Reference to an array of the tokens comprising the input
#               string. Each token is either a tag (possibly with nested,
#               tags contained therein, such as <a href="<MTFoo>">, or a
#               run of text between tags. Each element of the array is a
#               two-element array; the first is either 'tag' or 'text';
#               the second is the actual value.
#
#
#   Based on the _tokenize() subroutine from Brad Choate's MTRegex plugin.
#       <http://www.bradchoate.com/past/mtregex.php>
#

    my $str = shift;
    my $pos = 0;
    my $len = length $str;
    my @tokens;

    my $depth = 6;
    my $nested_tags = join('|', ('(?:<(?:[^<>]') x $depth) . (')*>)' x  $depth);
    my $match = qr/(?s: <! ( -- .*? -- \s* )+ > ) |  # comment
                   (?s: <\? .*? \?> ) |              # processing instruction
                   $nested_tags/x;                   # nested tags

    while ($str =~ m/($match)/g) {
        my $whole_tag = $1;
        my $sec_start = pos $str;
        my $tag_start = $sec_start - length $whole_tag;
        if ($pos < $tag_start) {
            push @tokens, ['text', substr($str, $pos, $tag_start - $pos)];
        }
        push @tokens, ['tag', $whole_tag];
        $pos = pos $str;
    }
    push @tokens, ['text', substr($str, $pos, $len - $pos)] if $pos < $len;
    \@tokens;
}


1;
__END__


=pod

=encoding utf-8

=head1 NAME

B<Cutief8>


=head1 SYNOPSIS

B<cutief8.pl> [ B<-t> ] [ B<-n> ] [ B<-m> ] [ B<-1> ] [ B<-2> ] [ B<-3> ] [ B<-r> ]
    [ B<--version> ] [ B<--shortversion> ] [ I<file> ]


=head1 DESCRIPTION

Cutief8 is a utility that translates plain ASCII
punctuation characters into "smart" UTF-8 typographic punctuation
characters. cutief8 can perform the following transformations:

=over 4

=item *

Straight quotes ( " and ' ) into "curly" quote UTF-8 characters

=item *

Backticks-style quotes (``like this'') into "curly" quote UTF-8 characters

=item *

Dashes (C<--> and C<--->) into en- and em-dash characters

=item *

Three consecutive dots (C<...>) into an ellipsis character

=back

If the 't' option is set the text is assumed to be HTML, and Cutief8
will not modify characters within HTML tags, or insideC<< <pre> >>,
C<< <code> >>, C<< <kbd> >>, C<< <script> >>, or C<< <math> >> tag blocks.
Typically, these blocks are used to display text where smart quotes and
other "smart punctuation" would not be appropriate, such as source code
or example markup.
Without the 't' option, all text is processed, and angle-brackets are
assumed to be normal text.


=head2 Backslash Escapes

If you need to use literal straight quotes (or plain hyphens and
periods), Cutief8 accepts the following backslash escape sequences
to force non-smart punctuation. It does so by transforming the escaped
character temporarily into an HTML numeric entity, then back again
after processing (with the backslash removed):

              Escape
              ------
                \\
                \"
                \'
                \.
                \-
                \`

This is useful, for example, when you want to use straight quotes as
foot and inch marks: 6'2" tall; a 17" iMac.


=head1 OPTIONS

Use "--" to end switch parsing. For example, to open a file named "-z", use:

	cutief8.pl -- -z

=over 4


=item B<-t>

Indicates that the text contains HTML tags, which won't be converted.
The text should not contain stray '<' and '>' characters, as these may
confuse things.  If the option is not set, all the text is converted.


=item B<-1>

Performs default Cutief8 transformations: quotes (including
backticks-style), em-dashes, and ellipses. '--' (dash dash) is used to
signify an em-dash; there is no support for en-dashes.  This is the
default when no options supplied.


=item B<-n> (or B<-2>)

Same as default B<-1>, except that it uses the old-school typewriter
shorthand for dashes: '--' (dash dash) for en-dashes, '---' (dash dash dash)
for em-dashes.


=item B<-m> (or B<-3>)

Same as B<-n>, but inverts the shorthand for dashes: '--'
(dash dash) for em-dashes, and '---' (dash dash dash) for en-dashes.


=item B<-r> 

Revert conversions -- turn UTF-8 back to plain ASCII. (Note:
en-dashes become plain dashes, em-dashes double-dashes.)


=item B<-v>, B<--version>

Display the app's name and version number.


=item B<-s>, B<--shortversion>

Display the short-form version number.


=back




=head2 Algorithmic Shortcomings

One situation in which quotes will get curled the wrong way is when
apostrophes are used at the start of leading contractions. For example:

    'Twas the night before Christmas.

In the case above, Cutief8 will turn the apostrophe into an opening
single-quote, when in fact it should be a closing one. I don't think
this problem can be solved in the general case -- every word processor
I've tried gets this wrong as well. In such cases, it's best to use the
proper UTF-8 character for closing single-quotes (’) by hand.



=head1 VERSION HISTORY

    Cutief8 verion 1.0 12 July 2016

    +   Translated the original SmartyPants HTML entities into UTF-8
    using the "Recode" app, with some pre and post processing with  "matt".
    Removed the unused plugin code, and tweaked a few other features
    to be more suitable for standalone use.


    For SmartyPants History, please refer to the original SmartyPants.pl:
    
    http://daringfireball.net/projects/smartypants/

    (Version used for Cutief8: 1.5.1 -- Fri 12 Mar 2004)
    

=head1 AUTHOR

    John Gruber (for SmartyPants)
    http://daringfireball.net

    Pete Goodeve (Cutief8)


=head1 COPYRIGHT AND LICENSE

    Cutief8 Copyright (c) 2016 Pete Goodeve
    Licence as for SmartyPants below.

    SmartyPants Copyright (c) 2003 John Gruber
    (http://daringfireball.net/)
    All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

*   Redistributions of source code must retain the above copyright
    notice, this list of conditions and the following disclaimer.

*   Redistributions in binary form must reproduce the above copyright
    notice, this list of conditions and the following disclaimer in the
    documentation and/or other materials provided with the distribution.

*   Neither the name "SmartyPants" nor the names of its contributors may
    be used to endorse or promote products derived from this software
    without specific prior written permission.

This software is provided by the copyright holders and contributors "as is"
and any express or implied warranties, including, but not limited to, the 
implied warranties of merchantability and fitness for a particular purpose 
are disclaimed. In no event shall the copyright owner or contributors be 
liable for any direct, indirect, incidental, special, exemplary, or 
consequential damages (including, but not limited to, procurement of 
substitute goods or services; loss of use, data, or profits; or business 
interruption) however caused and on any theory of liability, whether in 
contract, strict liability, or tort (including negligence or otherwise) 
arising in any way out of the use of this software, even if advised of the
possibility of such damage.

=cut
