112 lines
1.9 KiB
Go
112 lines
1.9 KiB
Go
package main
|
|
|
|
import (
|
|
"bufio"
|
|
"flag"
|
|
"fmt"
|
|
"io"
|
|
"log"
|
|
"os"
|
|
"regexp"
|
|
)
|
|
|
|
func fileExists(file string) bool {
|
|
_, err := os.Stat(file)
|
|
if err == nil {
|
|
return true
|
|
}
|
|
if os.IsNotExist(err) {
|
|
return false
|
|
}
|
|
return false
|
|
}
|
|
|
|
func fileOpen(file string, canCreate bool) (*os.File, bool) {
|
|
if fileExists(file) {
|
|
f, e := os.OpenFile(file, os.O_RDWR, 0666)
|
|
if nil != e {
|
|
return nil, false
|
|
}
|
|
return f, true
|
|
} else if canCreate {
|
|
f, e := os.OpenFile(file, os.O_RDWR|os.O_CREATE, 0666)
|
|
if nil != e {
|
|
return nil, false
|
|
}
|
|
return f, true
|
|
} else {
|
|
return nil, false
|
|
}
|
|
}
|
|
|
|
func fileWrite(file *os.File, txt []string) {
|
|
for i := 0; i < len(txt); i++ {
|
|
file.WriteString(txt[i])
|
|
}
|
|
file.Sync()
|
|
}
|
|
|
|
func fileClose(file *os.File) {
|
|
file.Close()
|
|
}
|
|
|
|
func insertSpace2Line(line string) string {
|
|
reg1 := regexp.MustCompile("([A-Za-z0-9?)/,*])([\u4e00-\u9fa5])")
|
|
reg2 := regexp.MustCompile("([\u4e00-\u9fa5])([A-Za-z0-9?(/,*])")
|
|
line = reg2.ReplaceAllString(reg1.ReplaceAllString(line, "$1 $2"), "$1 $2")
|
|
return line
|
|
}
|
|
|
|
func SpacePipeline(file *os.File) []string {
|
|
var txt []string
|
|
file.Seek(0, io.SeekStart)
|
|
reader := bufio.NewReader(file)
|
|
for {
|
|
line, e := reader.ReadString('\n')
|
|
if nil != e {
|
|
break
|
|
}
|
|
line = insertSpace2Line(line)
|
|
txt = append(txt, line)
|
|
}
|
|
return txt
|
|
}
|
|
|
|
func usage() {
|
|
fmt.Println("SpaceMarkdown")
|
|
fmt.Println("version 0.1.1")
|
|
flag.PrintDefaults()
|
|
}
|
|
|
|
func main() {
|
|
var ifile, ofile string
|
|
var ifd, ofd *os.File
|
|
var ret bool
|
|
|
|
flag.StringVar(&ifile, "i", "", "Input markdown file")
|
|
flag.StringVar(&ofile, "o", "", "Output markdown file")
|
|
|
|
flag.Usage = usage
|
|
flag.Parse()
|
|
|
|
if ifile == "" {
|
|
usage()
|
|
return
|
|
}
|
|
if ofile == "" {
|
|
ofile = ifile
|
|
}
|
|
ifd, ret = fileOpen(ifile, false)
|
|
if !ret {
|
|
log.Println("Can not open " + ifile)
|
|
}
|
|
ofd, ret = fileOpen(ofile, true)
|
|
if !ret {
|
|
log.Println("Can not open " + ofile)
|
|
}
|
|
|
|
fileWrite(ofd, SpacePipeline(ifd))
|
|
fileClose(ifd)
|
|
fileClose(ofd)
|
|
}
|