Skip to content

Instantly share code, notes, and snippets.

@zmwangx
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zmwangx/9801100 to your computer and use it in GitHub Desktop.
Save zmwangx/9801100 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3.3
# Convert LaTeX type dashes: - for hyphen, -- for en-dash, --- for
# em-dash to html: -, –, — in markdown.
#
# Usage:
# python dashify FILE_PATH
# ./dashify FILE_PATH
#
# One file allowed at a time. A backup file will be created each time
# in case of accidents. To remove the backup file, run the
# accompanying ./remove_backup.sh.
#
# Caveat:
# "---" at the beginning of a line (after '\n') is regarded as a
# header indicator or a horizontal rule, hence not converted.
import sys
usage = '''usage:
python dashify FILE_PATH
./dashify FILE_PATH'''
if sys.argv[0] == 'python':
if len(sys.argv) != 3:
print(usage)
exit(1)
file_path = sys.argv[2]
else:
if len(sys.argv) != 2:
print(usage)
exit(1)
file_path = sys.argv[1]
inbuf = open(file_path, 'r')
intext = inbuf.read()
inbuf.close()
# backup the file in case of accident
outbuf = open(file_path + '.backup', 'w')
outbuf.write(intext)
outbuf.close()
# convert dashes
converted = ''
length = len(intext)
i = 0;
while i < length:
if intext[i] != '-':
converted += intext[i]
i += 1
continue
else:
if i + 2 < length:
if (intext[i + 1] == intext[i + 2] == '-'):
# check if --- is at the beginning of a line (header
# or horizontal rule); if so, skip all subsequent
# hyphens
if i == 0 or intext[i - 1] == '\n':
while i < length and intext[i] == '-':
converted += '-'
i += 1
continue
converted += '&mdash;'
i += 3
continue
if i + 1 < length:
if (intext[i + 1] == '-'):
converted += '&ndash;'
i += 2
continue
converted += '-'
i += 1
continue
# write to the original file
outbuf = open(file_path, 'w')
outbuf.write(converted)
outbuf.close()
#!/bin/zsh
rm -i **/*.backup
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment