Skip to content

Instantly share code, notes, and snippets.

@edrzmr
Created March 25, 2018 23:32
Show Gist options
  • Save edrzmr/850224aa66b820fd101b323b07bed9ae to your computer and use it in GitHub Desktop.
Save edrzmr/850224aa66b820fd101b323b07bed9ae to your computer and use it in GitHub Desktop.
Markdown Formatter
#!/usr/bin/env python3
DEBUG = False
def debug(*args, **keywords):
if DEBUG is False:
return
print(*args, **keywords)
def blockReadFromFile(fin, last_status):
line = ''
block = ''
for line in fin:
line = line.strip()
if line.startswith('--') or line.startswith('=='):
if block is not '':
block += '\n'
block += line
return (block, 'under')
if line.startswith('-') or line.startswith('*'):
block += line
return (block, 'list')
# end of block
if line is '':
# removing duplicated empty lines
if block is not '':
return (block, 'ok')
else:
continue
block += line + ' '
# end of file
if line is '':
return (block, 'eof')
# last block
return (block, 'last')
def blockFormat(block, cols=80):
out = ''
while True:
try:
pos = block[:cols+1].rindex(' ')
except:
out = out.strip()
if out is not '':
out += ' '
out += block
break
out += block[:pos] + '\n'
block = block[pos+1:]
return out.strip()
def formatFile(filename):
status = 'none'
fin = open(filename, 'r')
while True:
old_status = status
(block, status) = blockReadFromFile(fin, old_status)
if block is '':
break
if status is 'ok' and old_status is 'list':
print()
if status is 'ok' and old_status is 'ok':
print()
if status is 'last' and old_status is 'list':
print()
if status is 'under' and old_status is 'list':
print()
if status is 'under' and old_status is 'under':
print()
if status is 'list' and old_status is 'under':
print()
if status is 'list' and old_status is 'ok':
print()
debug('~~~~~~~~~~~~~~~~~~, ' + status + ', ' + old_status)
print(blockFormat(block))
debug('+++++++++++++++++++')
if __name__ == '__main__':
import sys
try:
formatFile(sys.argv[1])
except:
print('usage: ' + sys.argv[0] + ' <filename>')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment