Skip to content

Instantly share code, notes, and snippets.

@osima
Created January 14, 2012 23:40
Show Gist options
  • Save osima/1613400 to your computer and use it in GitHub Desktop.
Save osima/1613400 to your computer and use it in GitHub Desktop.
markdown to textile converter another version without radeox
//
// markdown から textile への変換だけする
//
import java.util.regex.*
class Conv {
def br = System.getProperty('line.separator')
def getNoteBody = {
def out = ''<<''
def noteHeaderEnd=false
new StringReader(it).each{
if( noteHeaderEnd==false && (it =~ /^#[^#]/).find() ){ noteHeaderEnd=true }
if( noteHeaderEnd==true ){ out << it << br }
}
out.toString()
}
def toTextile = { line->
def m1 = (line =~ /^(.*)<(http.*?)>(.*)$/)
if( m1.find() ){
line = "${m1.group(1)}[${m1.group(2)}]${m1.group(3)}"
}
line = line.replaceAll(/^#### /,'h4. ')
line = line.replaceAll(/^### /, 'h3. ')
line = line.replaceAll(/^## /, 'h2. ')
line = line.replaceAll(/^# /, 'h1. ')
line = line.replaceAll(/^- /, '* ')
line = line.replaceAll(/^ - /, '** ')
line = line.replaceAll(/^ - /, '*** ')
line = line.replaceAll(/^ - /, '**** ')
line = line.replaceAll(/^1. /, '# ')
line = line.replaceAll(/^ 1. /, '## ')
line = line.replaceAll(/^ 1. /, '### ')
line = line.replaceAll(/^ 1. /, '#### ')
line
}
void convert(File inputFile,File outputFile){
def text = inputFile.getText('UTF-8')
text = processString(text)
def w = outputFile.newWriter('UTF-8')
w.print text
w.close()
}
String processString(String text){
text = getNoteBody(text)
def out = ''<<''
boolean inCodeBlock=false
new StringReader(text).each{ line->
boolean onCodeMacro=false
def pat = Pattern.compile('^\\{code\\}')
def m1 = pat.matcher(line)
if( inCodeBlock==false ){
if( m1.find() ){
inCodeBlock=true
onCodeMacro=true
}
}
else{
if( m1.find() ){
inCodeBlock=false
onCodeMacro=true
}
}
if( onCodeMacro ) out << line << br
else {
if( inCodeBlock ){
out << line << br
}
else{
out << toTextile(line) << br
}
}
}
out.toString()
}
}
def encoding = 'UTF-8'
def inputFile = new File(args[0])
def outputFile = new File(args[1])
def content = inputFile.getText(encoding)
def toTextile = { myContent-> new Conv().processString(myContent) }
outputFile.setText( toTextile(content),encoding )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment