Skip to content

Commit

Permalink
Fixed option parsing (again) and added "f_spines" chunk option
Browse files Browse the repository at this point in the history
Reverted to old way to parse chunk options. Regex based version didn't
work for all options and the old one is more robust.

Added "f_spines" option to remove spines from generated figures.
Defaults to True (meaning keep spines, set False to remove spines from
generated figs.)
  • Loading branch information
Matti Pastell committed Nov 13, 2014
1 parent 6c86519 commit d7f7b4e
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 51 deletions.
18 changes: 13 additions & 5 deletions pweave/formatters.py
Original file line number Diff line number Diff line change
Expand Up @@ -394,7 +394,7 @@ def initformat(self):
indent = '',
termindent = '',
figfmt = '.png',
extension = 'md',
extension = 'txt',
width = '15 cm',
doctype = 'leanpub')

Expand All @@ -405,12 +405,18 @@ def formatfigure(self, chunk):
result = ""
figstring = ""

for fig in fignames:
figstring += '![](%s)\\\n' % (fig)
#print chunk["name"]

if chunk['caption']:
result += '![%s](%s)\n' % (caption, fignames[0])
if fignames:
result += '![%s](%s)\n' % (caption, fignames[0])
if (len(fignames) > 1):
for fig in fignames[1:]:
figstring += '![](%s)\n' % (fig)
sys.stderr.write("Warning, only the first figure gets a caption\n")
else:
for fig in fignames:
figstring += '![](%s)\n' % (fig)
result += figstring
return(result)

Expand Down Expand Up @@ -502,7 +508,6 @@ def formatfigure(self, chunk):
return(result)


return(figstring)

class PwebMDtoHTMLFormatter(PwebHTMLFormatter):

Expand Down Expand Up @@ -631,6 +636,9 @@ def format_docchunk(self, chunk):
#self.formatted = pandoc.communicate()[0]
#self.formatted




class PwebFormats(object):
"""Contains a dictionary of available output formats"""
formats = {'tex' : {'class' : PwebTexFormatter, 'description' : 'Latex with verbatim for code and results'},
Expand Down
18 changes: 15 additions & 3 deletions pweave/processors.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,13 @@ def _runcode(self, chunk):
if chunk.has_key("source"):
source = chunk["source"]
if os.path.isfile(source):
chunk["content"] = open(source, "r").read() + chunk['content']
chunk["content"] = "\n" + open(source, "r").read().rstrip() + "\n" + chunk['content']
else:
chunk["content"] = self.loadstring("import inspect\nprint(inspect.getsource(%s))" % source) + chunk['content']
chunk_text = chunk["content"] #Get the text from chunk
module_text = self.loadstring("import inspect\nprint(inspect.getsource(%s))" % source) #Get the module source using inspect
chunk["content"] = module_text.rstrip()
if chunk_text.strip() != "":
chunk["content"] += "\n" + chunk_text



Expand Down Expand Up @@ -185,11 +189,19 @@ def savefigs(self, chunk):
for i in figs:
plt.figure(i)
plt.figure(i).set_size_inches(chunk['f_size'])
#plt.figure(i).set_size_inches(4,4)
if not chunk["f_spines"]:
axes = plt.figure(i).axes
for ax in axes:
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.yaxis.set_ticks_position('left')
ax.xaxis.set_ticks_position('bottom')


name = Pweb.figdir + '/' + prefix + "_" + str(i) + self.formatdict['figfmt']
for format in self.formatdict['savedformats']:
plt.savefig(Pweb.figdir + '/' + prefix + "_" + str(i) + format)

plt.draw()
fignames.append(name)
#plt.clf()
Expand Down
1 change: 1 addition & 0 deletions pweave/pweb.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ class Pweb(object):
f_pos = "htpb",
f_size = (8, 6),
f_env = None,
f_spines = True,
complete = True,
engine = "python"
)
Expand Down
57 changes: 14 additions & 43 deletions pweave/readers.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,53 +102,24 @@ def parse(self):
chunks.append({"type" : "doc", "content" : read, "number" : docN})
self.parsed = chunks


def getoptions(self, opt):
"""Option format is "label, a = 1, b=2, c=3"
'label' does not have to exist."""
# what separates options?
opt_separate = ","
# how are options assigned?
opt_assign = "="

rel = re.match(self.code_begin, opt)
if not rel:
return({})
optstring = rel.groups()[0]
# Aliases for False and True to conform with Sweave syntax
FALSE = False
TRUE = True

#Parse options from chunk to a dictionary
optstring = opt.replace('<<', '').replace('>>=', '').strip()
if not optstring:
return({})
# separate out options without splitting up quoted strings
# that may contain more quoting characters
# copes with e.g. "what's up o'brien?"
# http://stackoverflow.com/a/2787064/1157089
opts_regex = r'''((?:[^{}"']|"[^"]*"|'[^']*')+)'''.format(opt_separate)
# split on this regex and strip whitespace
opts = re.split(opts_regex, optstring)[1::2]
opts = [o.strip() for o in opts]

# First option can be a name/label without an =
if opt_assign not in opts[0]:
opts[0] = 'name=%s' % opts[0]

# split on first occurence of =
chunkoptions = dict(o.split(opt_assign, 1) for o in opts)
for key in chunkoptions:
# strip outer whitespace
chunkoptions[key] = chunkoptions[key].strip()
# strip outer quotes if matched
chunkoptions[key] = re.sub(r'^"(.*)"$', r'\1', chunkoptions[key])
chunkoptions[key] = re.sub(r"^'(.*)'$", r'\1', chunkoptions[key])
# replace boolean strings with boolean values
# all caps is sweave syntax. could use .lower() here to
# accept arbitrary capitalisation
value = chunkoptions[key]
if str(value) in ('True', 'TRUE'):
chunkoptions[key] = True
elif str(value) in ('False', 'FALSE'):
chunkoptions[key] = False
else:
pass
#First option can be a name/label
if optstring.split(',')[0].find('=')==-1:
splitted = optstring.split(',')
splitted[0] = 'name = "%s"' % splitted[0]
optstring = ','.join(splitted)

if 'label' in chunkoptions:
exec("chunkoptions = dict(" + optstring + ")")
if chunkoptions.has_key('label'):
chunkoptions['name'] = chunkoptions['label']

return(chunkoptions)
Expand Down

0 comments on commit d7f7b4e

Please sign in to comment.