From 950d9b36f8b765937270a79661df961f3e031d25 Mon Sep 17 00:00:00 2001 From: Louis Date: Mon, 16 Jun 2014 23:07:40 +0200 Subject: [PATCH] Improving chord \[ parsing --- songbook_core/plastex_chord.py | 42 +++++++++++++++++++++------------- 1 file changed, 26 insertions(+), 16 deletions(-) diff --git a/songbook_core/plastex_chord.py b/songbook_core/plastex_chord.py index b3a71eee..9ff2fa13 100644 --- a/songbook_core/plastex_chord.py +++ b/songbook_core/plastex_chord.py @@ -5,9 +5,13 @@ r"""PlasTeX module to deal with chords commands of the songs LaTeX package Chords are set using commands like \[C]. This package parses those commands. """ +import logging + from plasTeX import Command, Environment, Macro from plasTeX.Base.LaTeX.Math import BeginDisplayMath +LOGGER = logging.getLogger(__name__) + # Count the number of levels of 'verse' environment: IN_VERSE==1 means that we # are in a 'verse' environment; IN_VERSE==2 means that we are in two included # 'verse' environment, and so on. @@ -55,19 +59,19 @@ class Chorus(Environment): -class BeginChord(Command): +class Chord(Command): """Beginning of a chord notation""" macroName = 'chord' - macroMode = Command.MODE_BEGIN + macroMode = Command.MODE_NONE + + def __init__(self, *args, **kwargs): + super(Chord, self).__init__(*args, **kwargs) + self.chord = "" @property def source(self): """Return chord LaTeX code.""" - return r'\[{}]'.format(''.join([str(item) for item in self.childNodes])) - -class EndChord(Command): - """End of a chord notation""" - macroMode = Command.MODE_END + return r'\[{}]'.format(self.chord) class BeginChordOrDisplayMath(BeginDisplayMath): r"""Wrapper to BeginDisplayMath @@ -92,19 +96,25 @@ class BeginChordOrDisplayMath(BeginDisplayMath): def invoke(self, tex): """Process this macro""" if IN_VERSE: - begin = BeginChord() - self.ownerDocument.context.push(begin) # pylint: disable=no-member - self.parse(tex) + chord = Chord() for token in tex: if token.nodeType == token.TEXT_NODE and token.nodeValue == ']': break else: - begin.appendChild(token) - - end = EndChord() - self.ownerDocument.context.push(end) # pylint: disable=no-member - - return [begin] + if token.nodeName == '#text': + chord.chord += str(token) + elif token.nodeName == "active::&": + chord.chord += '&' + else: + LOGGER.warning(( + "{}: Unexpected character '{}' in chord " + "argument. Continuing anyway.").format( + tex.filename, + token.source, + )) + break + + return [chord] else: return super(BeginChordOrDisplayMath, self).invoke(tex)