Instantly share code, notes, and snippets.

@jabofh /tp2md.pl
Last active Oct 10, 2017

Embed
What would you like to do?
Convert TaskPaper formatted File or Input to Markdown on Standard Output
#!/usr/bin/env perl -T
use Getopt::Std;
$VERSION = "0.0.3";
$Getopt::Std::STANDARD_HELP_VERSION = 1;
#===============================================================================
# Functions
#-------------------------------------------------------------------------------
sub VERSION_MESSAGE
{
my $fh = shift;
(my $progname = $0) =~ s|^.*/||;
print $fh "$progname version $VERSION\n";
}
sub HELP_MESSAGE
{
my $fh = shift;
(my $progname = $0) =~ s|^.*/||;
print $fh "\nUsage: $progname [option] FILE\n";
print $fh "\n\tWhere the options are:\n";
print $fh "\t\t-h\tThis Help\n";
print $fh "\t\t-v\tShow Version\n";
print $fh "\t\t-b\tDisable Block-quote Notes\n";
print $fh "\n\tConverts TaskPaper file 'FILE' to Markdown format on STDOUT\n\n";
exit 1;
}
sub main
{
getopts('Hhvb') or HELP_MESSAGE("STDERR");
if ($opt_h or $opt_H) {
VERSION_MESSAGE('STDERR');
HELP_MESSAGE('STDERR');
}
if ($opt_v) {
VERSION_MESSAGE('STDERR');
exit 1;
}
my $blockQuote = $opt_b ? 0 : 1;
my $calcIndent = 0;
my $indentOffset = 0;
my $displayIndent = 0;
while (<>) {
chomp;
next if $_ =~ m|^\s*$|;
my $calcIndent = CountIndent($_);
if ($_ =~ m|^\s*- .*$|) {
$_ = ProcessTasks($_);
} elsif ($_ =~ m|^\s*[^-].+: *@*\w*$|) {
$_ = ProcessProjects($_) ;
$indentOffset = $calcIndent;
} else {
$_ = ProcessNotes($_, $blockQuote);
}
$displayIndent = $calcIndent - $indentOffset;
if ($_ =~ m|@\S+|) {
$_ = ProcessTags($_);
}
$_ = ProcessExhortations($_);
print " " x $displayIndent . $_ . " \n\n";
}
}
sub ProcessProjects($)
{
my $line = $_[0];
my $offset = CountIndent($line);
$line =~ s|^|#|;
$line =~ s|:$||g;
$line =~ s|: *@| @|g;
$line =~ s|\t|#|g;
$line =~ s|^(#+)|$1 |;
return "\n" . $line;
}
sub ProcessTasks($)
{
my $line = $_[0];
my $offset = CountIndent($line);
$line =~ s|^\t+||g;
return $line;
}
sub ProcessNotes($)
{
my $line = $_[0];
my $blockQuote = $_[1];
my $offset = CountIndent($line);
$line =~ s|^\t+||g;
if ($blockQuote) {
$line =~ s|^|> |;
}
return $line;
}
sub CountIndent($)
{
my $string = $_[0];
$string =~ s/^\t+//;
my $indent = length($_[0]) - length($string);
return $indent;
}
sub ProcessTags($)
{
my $line = $_[0];
$line =~ s|\s@(\w+[-]*\w+)| #$1|g;
return $line;
}
sub ProcessExhortations($)
{
my $line = $_[0];
my %exhortations = (
MUST => '_must_',
SHOULD => '_should_',
MAY => '_may_',
BE => '_be_',
NOT => '_not_',
);
foreach my $key (keys %exhortations) {
$line =~ s|$key|$exhortations{$key}|g;
}
$line =~ s/_ _/ /g;
return $line;
}
#===============================================================================
main(@ARGV);
exit(0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment