Method with pre and post filter

This commit is contained in:
Yann Esposito (Yogsototh) 2010-11-05 15:45:28 +01:00
parent 21de51fc7e
commit fd06bc78e8
3 changed files with 74 additions and 14 deletions

View file

@ -14,20 +14,24 @@ task :compile do
require 'rubygems'
require 'kramdown'
require 'filters/markdown_macros'
require 'filters/mkd_post_latex_macros'
pdfname="my_book"
filters=[]
filters<<=MarkdownMacros.new
prefilters=[]
prefilters<<=MarkdownMacros.new
postfilters=[]
postfilters<<=MarkdownPostLatexMacros.new
include_list=[]
Dir.glob("content/**/*.md").each do |file|
text=""
puts file
tmp=File.new(file,"r").read
# pre filters
filters.each do |f|
tmp=f.prefilter( tmp )
prefilters.each do |f|
tmp=f.run( tmp )
end
text <<= tmp
@ -35,7 +39,7 @@ task :compile do
tmp=Kramdown::Document.new(text).to_latex
# post filters
filters.each{ |f| tmp=f.postfilter(tmp) }
postfilters.each{ |f| tmp=f.run(tmp) }
# write
# create tex associated to md

View file

@ -32,22 +32,18 @@ class MarkdownMacros
end
end
def prefilter( content )
def run (content)
content.gsub(/%%% (\w*) %%% ((.|\n)*?) %%%/m) do |m|
puts %{ macro %#{$1}\t=> #{$2}}
puts %{ mkd macro %#{$1}\t=> #{$2}}
@macro[$1.intern]=$2
""
end
end
def postfilter(content)
content.gsub(/((\\textbackslash\{\})?)\\%(\w*)/) do |m|
puts "MATCH: 1. #{$1} 2. #{$2} 3. #{$3}"
end.gsub(/((\\)?)%(\w*)/) do |m|
puts " mkd macro MATCH: 1. #{$1} 2. #{$2} 3. #{$3}"
if $3 != ""
if $1 == ""
macro_value_for($3)
else
"\\texttt{\\%#{$3}}"
'`%'+$3+'`'
end
else
m

View file

@ -0,0 +1,60 @@
# Add macros to Markdown
#
# Here is a %test.
#
# you could add a macro like this
#
# filter.macro={
# :latex => %{\LaTeX}
# }
#
# or within the markdown file by
#
# %%% macro_name %%% macro_value %%%
#
class MarkdownPostLatexMacros
attr_accessor :macro
def initialize()
super
@macro={}
end
def macro_value_for(ident)
return '%' if ident.nil? or ident==""
ident=ident.intern
return %{%#{ident}} if @macro[ident].nil?
if @macro[ident] =~ /ruby: ((.|n)*)/m
return eval $1
else
return @macro[ident]
end
end
def run (content)
content.gsub(/LLL (\w*) LLL ((.|\n)*?) LLL/m) do |m|
name=$1
value=$2
puts %{ ltx macro %#{name}\t=> #{value}}
value=value.gsub(/\\textbackslash\{\}/,'\\').
gsub(/\\%/,'%').
gsub(/\\\{/,'{').
gsub(/\\\}/,'}')
puts %{ ltx macro %#{name}\t=> #{value}}
@macro[name.intern]=value
""
end.gsub(/((\\textbackslash\{\})?)\\%(\w*)/) do |m|
puts " ltx macro MATCH: 1. #{$1} 2. #{$2} 3. #{$3}"
if $3 != ""
if $1 == ""
macro_value_for($3)
else
%{\texttt{%#{$3}}}
end
else
m
end
end
end
end