markslider python3 upgrades

This commit is contained in:
q
2018-10-01 20:36:29 +03:00
parent 47b9b68328
commit f678da2330
6 changed files with 248 additions and 136 deletions

View File

@@ -10,6 +10,7 @@ function helpexit() {
echo ' -n to match non-ascii and non-printable characters, and replace to [arg1]'
echo ' -f to replace match [arg1] with format [arg2], ex: -f "[0-9]\+" "%04d"'
echo ' -p to replace problematic characters [^\w()[]-.] with [arg1]'
echo ' -a to replace non-alphanumeric(+dot) characters [^\w.] with [arg1]'
exit
}
@@ -44,6 +45,10 @@ do [[ "${!i}" = "-h" ]] && helpexit
SRC='[^]\[0-9a-zA-Z_.()-]'
continue
}
[[ "${!i}" = "-a" ]] && {
SRC='[^0-9a-zA-Z.]'
continue
}
[[ -z "$SRC" ]] && {
SRC="${!i}"
continue

View File

@@ -57,6 +57,7 @@ class code:
def posprint(self, y,x,s):
""" Print string at a location """
sys.stdout.write( self.pos(y,x) + str(s) )
self.flush()
def clear(self):
sys.stdout.write( self.CLRSCR+self.pos(0,0) )
@@ -102,7 +103,8 @@ class code:
def get_keys(self):
return self.color_keys
def flush(self):
sys.stdout.flush()
def demo():

View File

@@ -7,7 +7,7 @@ rm -rf markslider
mkdir -p markslider/scripts markslider/markslider
cp -v ansi.py md_color.py markslider.py markslider/markslider/
echo '#!/usr/bin/env python2
echo '#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import sys

View File

@@ -20,7 +20,7 @@
'''Markslider: a slideshow engine based on markdown.'''
__author__ = "Ville Rantanen <ville.q.rantanen@gmail.com>"
__version__ = "0.9"
__version__ = "1.0"
import sys,os,argparse,re,datetime
from argparse import ArgumentParser
@@ -45,6 +45,7 @@ class getch:
class EndProgram( Exception ):
''' Nice exit '''
print('')
pass
class slide_reader:
@@ -82,7 +83,7 @@ class slide_reader:
for row in f:
if not row:
continue
row=row.decode('utf-8').rstrip("\n\r ")
row=row.rstrip("\n\r ")
# find end of show
if row == EOS:
break
@@ -210,13 +211,13 @@ class slide_reader:
""" Launch in a string using tags `command`>
Remove empty lines from beginning and end of stdout.
"""
#~ if not self.opts.execute_read:
#~ return [s]
#~ if s.find("`>")==-1:
#~ return [s]
#~ command=self.re_command.match(s)
#~ if command != None:
output = subprocess.check_output(command.group(2).strip(),shell=True).split("\n")
output = subprocess.check_output(
command.group(2).strip(),
shell = True
)
if type(output) == bytes:
output = output.decode('utf-8')
output = output.split("\n")
while len(output[0].strip())==0:
if len(output)==1: return [""]
del output[0]
@@ -235,7 +236,13 @@ class slide_reader:
"""
#~ 2=title
#~ 3=image command
output = subprocess.check_output("convert %s JPEG:- | jp2a --colors --width=70 -"%image.group(3),shell=True).split("\n")
output = subprocess.check_output(
"convert %s JPEG:- | jp2a --colors --width=70 -"%( image.group(3),),
shell=True
)
if type(output) == bytes:
output = output.decode('utf-8')
output = output.split("\n")
while len(output[0].strip())==0:
if len(output)==1: return [""]
del output[0]
@@ -273,7 +280,7 @@ Special syntaxes:
* Text after a "# End of Slides" is not shown
* Execute shell: ` command -switch `! Beware of malicious code!
* Execute and print output: ` command `> Beware of malicious code!
* Convert images to ASCII, with jp2a: ![](file.jpg)
* Convert images to ASCII, with jp2a: ![](file.jpg)>
Keyboard shortcuts:
'''+get_interactive_help_text()
@@ -350,14 +357,26 @@ def page_print(reader,opts,offset):
coloring = "${b}${U}"
else:
coloring = "${U}${Y}"
print(align_pad+colorify(coloring+page[0],opts)+bc.Z)
print(
align_pad +
colorify(
coloring + page[0],
opts) +
bc.Z
)
if (sys.version_info < (3, 0)):
# python2 magic
page = [row.decode('utf-8') for row in page]
# Print page rows
if not opts.wrap:
page = [cut_line(row,scrsize[1]-1) for row in page]
parsed = md_color.parse(page)
if opts.autocolor:
colored=md_color.colorize(parsed,not opts.color,opts.dark_colors)
colored = md_color.colorize(
parsed,
not opts.color,
opts.dark_colors
)
else:
if opts.color:
colored=[bc.color_string(row[1]) for row in parsed]
@@ -398,8 +417,17 @@ def print_menu(reader,opts):
def print_time(opts):
now=datetime.datetime.now()
bc.posprint( opts.size[0], opts.size[1]-5,
colorify("%02d:%02d"%(now.hour,now.minute),opts))
bc.posprint(
opts.size[0],
opts.size[1]-5,
colorify(
"%02d:%02d"%(
now.hour,
now.minute
),
opts
)
)
def print_help(reader,opts):
''' Create a window with help message '''
@@ -588,24 +616,35 @@ def launch(reader,opts,offset):
Detects URLS and markdown images ![Alt text](/path/to/img.jpg)
"""
if not opts.execute:
bc.posprint(offset[1]-offset[0]+1,0,"Execution not enabled!")
bc.posprint(
offset[1]-offset[0]+1,
0,
"Execution not enabled!"
)
inkey = getch.get()
return
s = reader.get_current_page()[offset[1]]
urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', s)
images = re.findall('!\[[^]]+\]\([^\)]+\)', s)
# sanity check
if s.find("`") == -1 and len(urls) == 0 and len(images) == 0:
return
run_command=re.match("(.*)`(.*)`!(.*)",s)
show_command=re.match("(.*)`(.*)`>(.*)",s)
if show_command != None:
output = subprocess.check_output(show_command.group(2).strip(),shell=True).split("\n")
output = subprocess.check_output(
show_command.group(2).strip(),
shell = True
)
if type(output) == bytes:
output = output.decode('utf-8')
output = output.split("\n")
while len(output[0].strip())==0:
if len(output)==1: return [""]
if len(output)==1: return
del output[0]
while len(output[-1].strip())==0:
if len(output)==1: return [""]
if len(output)==1: return
del output[-1]
for y,l in enumerate(output):
bc.posprint(y+offset[1]-offset[0]+2,0,' '*len(l))
@@ -614,22 +653,37 @@ def launch(reader,opts,offset):
inkey=getch.get()
return
if run_command != None:
subprocess.call(run_command.group(2),
shell=True,executable="/bin/bash")
subprocess.call(
run_command.group(2),
shell = True,
executable = "/bin/bash"
)
inkey=getch.get()
return
# Open URLS last
if len(urls)>0:
# Remove ) at the end of url: [name](link) markdown syntax
subprocess.call("xdg-open '%s' &"%(urls[0].rstrip(")"),),
stdout=subprocess.PIPE,stderr=subprocess.PIPE,
shell=True)
subprocess.call(
"%s '%s' &"%(
get_open_command(),
urls[0].rstrip(")"),
),
stdout = subprocess.PIPE,
stderr = subprocess.PIPE,
shell = True
)
return
if len(images)>0:
image = re.sub('.*\(([^\)]+)\).*', "\\1",images[0])
subprocess.call("xdg-open '%s' &"%(image,),
stdout=subprocess.PIPE,stderr=subprocess.PIPE,
shell=True)
subprocess.call(
"%s '%s' &"%(
get_open_command(),
image,
),
stdout = subprocess.PIPE,
stderr = subprocess.PIPE,
shell = True
)
return
return
@@ -642,16 +696,32 @@ def modify_file(reader,offset):
row+=len(reader.data[page])
if (page+1) in row_restarts:
row=1
subprocess.call("vim +%d -c 'exe \"normal! zt\"' -c %d %s"%(row,row+offset[1],reader.get_current_filename()),
shell=True)
subprocess.call(
"vim +%d -c 'exe \"normal! zt\"' -c %d %s"%(
row,
row + offset[1],
reader.get_current_filename()
),
shell = True
)
def take_screenshot(reader,opts):
out_file=os.path.join(opts.screenshots,"slide%03d.png"%(reader.page+1))
if not os.path.exists(opts.screenshots):
os.mkdir(opts.screenshots)
subprocess.call("sleep 0.5; import -window $WINDOWID '%s'"%(out_file,),
stdout=subprocess.PIPE,stderr=subprocess.PIPE,
shell=True)
subprocess.call(
"sleep 0.5; import -window $WINDOWID '%s'"%(out_file,),
stdout = subprocess.PIPE,
stderr = subprocess.PIPE,
shell = True
)
def get_open_command():
if sys.platform.startswith("darwin"):
return "open"
else:
return "xdg-open"
def main():

Binary file not shown.

View File

@@ -21,8 +21,10 @@ Any ANSI control code: ${3A}, ${1;34;42m}, etc..
'''%(" ".join(bc.get_keys()))
parser=ArgumentParser(description=usage,
epilog=__author__)
parser = ArgumentParser(
description = usage,
epilog = __author__
)
parser.add_argument("-v","--version",action="version",version=__version__)
parser.add_argument("-D",action="store_true",dest="debug",default=False,
@@ -122,6 +124,45 @@ def md_re_compile(d):
sys.exit(1)
return n
def read_data2(fp):
data = []
# Read data
for row in f:
if not row:
continue
row = row.decode('utf-8').rstrip("\n\r ")
data.append(row)
return data
def read_data3(fp):
data = []
# Read data
for row in f:
if not row:
continue
row = row.rstrip("\n\r ")
data.append(row)
return data
def write_colored2(colored, opts):
for c in colored:
sys.stdout.write(c.encode('utf-8'))
if opts.zero:
sys.stdout.write(bc.Z)
sys.stdout.write("\n")
if opts.zero_final:
sys.stdout.write(bc.Z.encode('utf-8'))
def write_colored3(colored, opts):
for c in colored:
sys.stdout.write(c)
if opts.zero:
sys.stdout.write(bc.Z)
sys.stdout.write("\n")
if opts.zero_final:
sys.stdout.write(bc.Z)
# re: regular expression, bc: bright colors, bcc: continue with this color after inline
# dc: dark colors, dcc: continued color after inline
@@ -216,21 +257,15 @@ if __name__ == "__main__":
f = sys.stdin
else:
f = open(opts.filename, 'r')
data=[]
# Read data
for row in f:
if not row:
continue
row=row.decode('utf-8').rstrip("\n\r ")
data.append(row)
if (sys.version_info > (3, 0)):
data = read_data3(f)
else:
data = read_data2(f)
data = parse(data)
colored = colorize(data, not opts.color, opts.dark_colors, opts.debug)
for c in colored:
sys.stdout.write(c.encode('utf-8'))
if opts.zero:
sys.stdout.write(bc.Z)
sys.stdout.write("\n")
if opts.zero_final:
sys.stdout.write(bc.Z.encode('utf-8'))
if (sys.version_info > (3, 0)):
write_colored3(colored, opts)
else:
write_colored2(colored, opts)