Example #1
0
 def saveDocumentAs(self, doc):
     """ Saves the document, always asking for a name.
     
     Returns True if saving succeeded.
     
     """
     filename = doc.url().toLocalFile()
     if filename:
         filetypes = app.filetypes(os.path.splitext(filename)[1])
     else:
         filename = app.basedir()  # default directory to save to
         import documentinfo
         import ly.lex
         filetypes = app.filetypes(
             ly.lex.extensions[documentinfo.mode(doc)])
     caption = app.caption(_("dialog title", "Save File"))
     filename = QFileDialog.getSaveFileName(self, caption, filename,
                                            filetypes)
     if not filename:
         return False  # cancelled
     if not util.iswritable(filename):
         QMessageBox.warning(
             self, app.caption(_("Error")),
             _("Can't write to destination:\n\n{url}").format(url=filename))
         return False
     url = QUrl.fromLocalFile(filename)
     doc.setUrl(url)
     recentfiles.add(url)
     return self.saveDocument(doc)
Example #2
0
 def saveCopyAs(self):
     import ly.lex
     doc = self.currentDocument()
     if not self.currentView().textCursor().hasSelection():
         import documentinfo
         mode = documentinfo.mode(doc)
         data = doc.encodedText()
         caption = app.caption(_("dialog title", "Save Copy"))
     else:
         import fileinfo
         text = self.currentView().textCursor().selection().toPlainText()
         mode = fileinfo.textmode(text)
         data = util.encode(text)
         caption = app.caption(_("dialog title", "Save Selection"))
     filetypes = app.filetypes(ly.lex.extensions[mode])
     dirname = os.path.dirname(doc.url().toLocalFile()) or app.basedir()
     filename = QFileDialog.getSaveFileName(self, caption, dirname, filetypes)
     if not filename:
         return # cancelled
     try:
         with open(filename, "w") as f:
             f.write(data)
     except IOError as e:
         msg = _("{message}\n\n{strerror} ({errno})").format(
             message = _("Could not write to: {url}").format(url=filename),
             strerror = e.strerror,
             errno = e.errno)
         QMessageBox.critical(self, app.caption(_("Error")), msg)
Example #3
0
 def saveDocumentAs(self, doc):
     """ Saves the document, always asking for a name.
     
     Returns True if saving succeeded.
     
     """
     filename = doc.url().toLocalFile()
     if filename:
         filetypes = app.filetypes(os.path.splitext(filename)[1])
     else:
         filename = app.basedir() # default directory to save to
         import documentinfo
         import ly.lex
         filetypes = app.filetypes(ly.lex.extensions[documentinfo.mode(doc)])
     caption = app.caption(_("dialog title", "Save File"))
     filename = QFileDialog.getSaveFileName(self, caption, filename, filetypes)
     if not filename:
         return False # cancelled
     if not util.iswritable(filename):
         QMessageBox.warning(self, app.caption(_("Error")),
             _("Can't write to destination:\n\n{url}").format(url=filename))
         return False
     url = QUrl.fromLocalFile(filename)
     doc.setUrl(url)
     recentfiles.add(url)
     return self.saveDocument(doc)
Example #4
0
 def saveCopyAs(self):
     import ly.lex
     doc = self.currentDocument()
     if not self.currentView().textCursor().hasSelection():
         import documentinfo
         mode = documentinfo.mode(doc)
         data = doc.encodedText()
         caption = app.caption(_("dialog title", "Save Copy"))
     else:
         import fileinfo
         text = self.currentView().textCursor().selection().toPlainText()
         mode = fileinfo.textmode(text)
         data = util.encode(util.platform_newlines(text))
         caption = app.caption(_("dialog title", "Save Selection"))
     filetypes = app.filetypes(ly.lex.extensions[mode])
     dirname = os.path.dirname(doc.url().toLocalFile()) or app.basedir()
     filename = QFileDialog.getSaveFileName(self, caption, dirname, filetypes)[0]
     if not filename:
         return # cancelled
     try:
         with open(filename, "wb") as f:
             f.write(data)
     except IOError as e:
         msg = _("{message}\n\n{strerror} ({errno})").format(
             message = _("Could not write to: {url}").format(url=filename),
             strerror = e.strerror,
             errno = e.errno)
         QMessageBox.critical(self, app.caption(_("Error")), msg)
Example #5
0
def save(mainwindow):
    title = inputdialog.getText(mainwindow,
        _("Save as Template"),
        _("Please enter a template name:"), regexp=r"\w(.*\w)?")
    if not title:
        return
    
    # get the text and insert cursor position or selection
    cursor = mainwindow.textCursor()
    text = cursor.document().toPlainText()
    
    repls = [(cursor.position(), '${CURSOR}')]
    if cursor.hasSelection():
        repls.append((cursor.anchor(), '${ANCHOR}'))
        repls.sort()
        
    result = []
    prev = 0
    for pos, what in repls:
        result.append(text[prev:pos].replace('$', '$$'))
        result.append(what)
        prev = pos
    result.append(text[prev:].replace('$', '$$'))
    text = ''.join(result)
    
    # add header line, if it is lilypond, enable autorun
    headerline = '-*- template; indent: no;'
    if documentinfo.mode(cursor.document()) == 'lilypond':
        headerline += ' template-run;'
    text = headerline + '\n' + text
    
    # save the new snippet
    model.model().saveSnippet(None, text, title)
Example #6
0
 def saveCopyAs(self):
     import ly.lex
     doc = self.currentDocument()
     if not self.currentView().textCursor().hasSelection():
         import documentinfo
         mode = documentinfo.mode(doc)
         data = doc.encodedText()
         caption = app.caption(_("dialog title", "Save Copy"))
     else:
         import fileinfo
         text = self.currentView().textCursor().selection().toPlainText()
         mode = fileinfo.textmode(text)
         data = util.encode(text)
         caption = app.caption(_("dialog title", "Save Selection"))
     filetypes = app.filetypes(ly.lex.extensions[mode])
     dirname = os.path.dirname(doc.url().toLocalFile()) or app.basedir()
     filename = QFileDialog.getSaveFileName(self, caption, dirname,
                                            filetypes)
     if not filename:
         return  # cancelled
     try:
         with open(filename, "w") as f:
             f.write(data)
     except (IOError, OSError) as err:
         QMessageBox.warning(
             self, app.caption(_("Error")),
             _("Can't write to destination:\n\n{url}\n\n{error}").format(
                 url=filename, error=err.strerror))
Example #7
0
 def saveCopyAs(self):
     import ly.lex
     doc = self.currentDocument()
     if not self.currentView().textCursor().hasSelection():
         import documentinfo
         mode = documentinfo.mode(doc)
         data = doc.encodedText()
         caption = app.caption(_("dialog title", "Save Copy"))
     else:
         import fileinfo
         text = self.currentView().textCursor().selection().toPlainText()
         mode = fileinfo.textmode(text)
         data = util.encode(text)
         caption = app.caption(_("dialog title", "Save Selection"))
     filetypes = app.filetypes(ly.lex.extensions[mode])
     dirname = os.path.dirname(doc.url().toLocalFile()) or app.basedir()
     filename = QFileDialog.getSaveFileName(self, caption, dirname, filetypes)
     if not filename:
         return # cancelled
     try:
         with open(filename, "w") as f:
             f.write(data)
     except (IOError, OSError) as err:
         QMessageBox.warning(self, app.caption(_("Error")),
             _("Can't write to destination:\n\n{url}\n\n{error}").format(
                 url=filename, error=err.strerror))
Example #8
0
 def __init__(self, document):
     QSyntaxHighlighter.__init__(self, document)
     self._fridge = ly.lex.Fridge()
     app.settingsChanged.connect(self.rehighlight)
     self._highlighting = metainfo.info(document).highlighting
     document.loaded.connect(self._resetHighlighting)
     self._mode = documentinfo.mode(document, False)
     variables.manager(document).changed.connect(self._variablesChange)
Example #9
0
def htmlCopy(document, type='editor'):
    """Returns a new QTextDocument with highlighting set as HTML textcharformats."""
    data = textformats.formatData(type)
    doc = QTextDocument()
    doc.setDefaultFont(data.font)
    doc.setPlainText(document.toPlainText())
    highlight(doc, HighlightFormats(data), ly.lex.state(documentinfo.mode(document)))
    return doc
Example #10
0
 def path(self):
     """Returns the path the saved document text would have if a temporary area was created, else None."""
     if self._directory:
         basename = None
         if not self.document().url().isEmpty():
             basename = os.path.basename(self.document().url().path())
         if not basename:
             basename = 'document' + ly.lex.extensions[documentinfo.mode(self.document())]
         return os.path.join(self._directory, basename)
Example #11
0
 def path(self):
     """Returns the path the saved document text would have if a temporary area was created, else None."""
     if self._directory:
         basename = None
         if not self.document().url().isEmpty():
             basename = os.path.basename(self.document().url().path())
         if not basename:
             basename = 'document' + ly.lex.extensions[documentinfo.mode(
                 self.document())]
         return os.path.join(self._directory, basename)
Example #12
0
    def saveDocument(self, doc, save_as=False):
        """ Saves the document, asking for a name if necessary.

        If save_as is True, a name is always asked.
        Returns True if saving succeeded.

        """
        if save_as or doc.url().isEmpty():
            filename = doc.url().toLocalFile()
            if filename:
                filetypes = app.filetypes(os.path.splitext(filename)[1])
            else:
                # find a suitable directory to save to
                for d in self.historyManager.documents()[1::]:
                    if d.url().toLocalFile():
                        directory = os.path.dirname(d.url().toLocalFile())
                        break
                else:
                    directory = app.basedir() # default directory to save to
                
                import documentinfo
                import ly.lex
                filename = os.path.join(directory, documentinfo.defaultfilename(doc))
                filetypes = app.filetypes(ly.lex.extensions[documentinfo.mode(doc)])
            caption = app.caption(_("dialog title", "Save File"))
            filename = QFileDialog.getSaveFileName(self, caption, filename, filetypes)[0]
            if not filename:
                return False # cancelled
            url = QUrl.fromLocalFile(filename)
        else:
            url = doc.url()

        if QSettings().value("strip_trailing_whitespace", False, bool):
            import reformat
            reformat.remove_trailing_whitespace(QTextCursor(doc))

        # we only support local files for now
        filename = url.toLocalFile()
        b = backup.backup(filename)
        try:
            doc.save(url)
        except IOError as e:
            msg = _("{message}\n\n{strerror} ({errno})").format(
                message = _("Could not write to: {url}").format(url=filename),
                strerror = e.strerror,
                errno = e.errno)
            QMessageBox.critical(self, app.caption(_("Error")), msg)
            return False
        else:
            if b:
                backup.removeBackup(filename)
            recentfiles.add(doc.url())
        return True
Example #13
0
def save(mainwindow):

    titles = dict((snippets.title(name), name)
                  for name in model.model().names()
                  if 'template' in snippets.get(name).variables)
    title = inputdialog.getText(mainwindow,
                                _("Save as Template"),
                                _("Please enter a template name:"),
                                regexp=r"\w(.*\w)?",
                                complete=sorted(titles))
    if not title:
        return

    if title in titles:
        if QMessageBox.critical(
                mainwindow, _("Overwrite Template?"),
                _("A template named \"{name}\" already exists.\n\n"
                  "Do you want to overwrite it?").format(name=title),
                QMessageBox.Yes | QMessageBox.Cancel) != QMessageBox.Yes:
            return
        name = titles[title]
    else:
        name = None

    # get the text and insert cursor position or selection
    cursor = mainwindow.textCursor()
    text = cursor.document().toPlainText()

    repls = [(cursor.position(), '${CURSOR}')]
    if cursor.hasSelection():
        repls.append((cursor.anchor(), '${ANCHOR}'))
        repls.sort()

    result = []
    prev = 0
    for pos, what in repls:
        result.append(text[prev:pos].replace('$', '$$'))
        result.append(what)
        prev = pos
    result.append(text[prev:].replace('$', '$$'))
    text = ''.join(result)

    # add header line, if it is lilypond, enable autorun
    headerline = '-*- template; indent: no;'
    if documentinfo.mode(cursor.document()) == 'lilypond':
        dinfo = documentinfo.docinfo(cursor.document())
        if dinfo.complete() and dinfo.has_output():
            headerline += ' template-run;'
    text = headerline + '\n' + text

    # save the new snippet
    model.model().saveSnippet(name, text, title)
Example #14
0
def save(mainwindow):
    
    titles = dict((snippets.title(name), name)
                  for name in model.model().names()
                  if 'template' in snippets.get(name).variables)
    title = inputdialog.getText(mainwindow,
        _("Save as Template"),
        _("Please enter a template name:"),
        regexp=r"\w(.*\w)?", complete=sorted(titles))
    if not title:
        return
    
    if title in titles:
        if QMessageBox.critical(mainwindow,
            _("Overwrite Template?"),
            _("A template named \"{name}\" already exists.\n\n"
              "Do you want to overwrite it?").format(name=title),
            QMessageBox.Yes | QMessageBox.Cancel) != QMessageBox.Yes:
            return
        name = titles[title]
    else:
        name = None
    
    # get the text and insert cursor position or selection
    cursor = mainwindow.textCursor()
    text = cursor.document().toPlainText()
    
    repls = [(cursor.position(), '${CURSOR}')]
    if cursor.hasSelection():
        repls.append((cursor.anchor(), '${ANCHOR}'))
        repls.sort()
        
    result = []
    prev = 0
    for pos, what in repls:
        result.append(text[prev:pos].replace('$', '$$'))
        result.append(what)
        prev = pos
    result.append(text[prev:].replace('$', '$$'))
    text = ''.join(result)
    
    # add header line, if it is lilypond, enable autorun
    headerline = '-*- template; indent: no;'
    if documentinfo.mode(cursor.document()) == 'lilypond':
        headerline += ' template-run;'
    text = headerline + '\n' + text
    
    # save the new snippet
    model.model().saveSnippet(name, text, title)
Example #15
0
 def initializeDocument(self):
     """This method is always called by the __init__ method.
     
     The default implementation does nothing for generic QTextDocuments,
     but for document.Document instances it connects to some additional
     signals to keep the mode up-to-date (reading it from the variables if
     needed) and initializes whether to enable visual highlighting from the
     document's metainfo.
     
     """
     document = self.document()
     if hasattr(document, "url"):
         self._highlighting = metainfo.info(document).highlighting
         document.loaded.connect(self._resetHighlighting)
         self._mode = documentinfo.mode(document, False)
         variables.manager(document).changed.connect(self._variablesChange)
Example #16
0
 def initializeDocument(self):
     """This method is always called by the __init__ method.
     
     The default implementation does nothing for generic QTextDocuments,
     but for document.Document instances it connects to some additional
     signals to keep the mode up-to-date (reading it from the variables if
     needed) and initializes whether to enable visual highlighting from the
     document's metainfo.
     
     """
     document = self.document()
     if hasattr(document, 'url'):
         self._highlighting = metainfo.info(document).highlighting
         document.loaded.connect(self._resetHighlighting)
         self._mode = documentinfo.mode(document, False)
         variables.manager(document).changed.connect(self._variablesChange)
Example #17
0
def html_copy(cursor, scheme='editor', number_lines=False):
    """Return a new QTextDocument with highlighting set as HTML textcharformats.
    
    The cursor is a cursor of a document.Document instance. If the cursor 
    has a selection, only the selection is put in the new document.
    
    If number_lines is True, line numbers are added.
    
    """
    data = textformats.formatData(scheme)
    doc = QTextDocument()
    doc.setDefaultFont(data.font)
    doc.setPlainText(cursor.document().toPlainText())
    if metainfo.info(cursor.document()).highlighting:
        highlight(doc, mapping(data),
                  ly.lex.state(documentinfo.mode(cursor.document())))
    if cursor.hasSelection():
        # cut out not selected text
        start, end = cursor.selectionStart(), cursor.selectionEnd()
        cur1 = QTextCursor(doc)
        cur1.setPosition(start, QTextCursor.KeepAnchor)
        cur2 = QTextCursor(doc)
        cur2.setPosition(end)
        cur2.movePosition(QTextCursor.End, QTextCursor.KeepAnchor)
        cur2.removeSelectedText()
        cur1.removeSelectedText()
    if number_lines:
        c = QTextCursor(doc)
        f = QTextCharFormat()
        f.setBackground(QColor('#eeeeee'))
        if cursor.hasSelection():
            num = cursor.document().findBlock(
                cursor.selectionStart()).blockNumber() + 1
            last = cursor.document().findBlock(cursor.selectionEnd())
        else:
            num = 1
            last = cursor.document().lastBlock()
        lastnum = last.blockNumber() + 1
        padding = len(format(lastnum))
        block = doc.firstBlock()
        while block.isValid():
            c.setPosition(block.position())
            c.setCharFormat(f)
            c.insertText('{0:>{1}d} '.format(num, padding))
            block = block.next()
            num += 1
    return doc
Example #18
0
    def saveDocument(self, doc, save_as=False):
        """ Saves the document, asking for a name if necessary.
        
        If save_as is True, a name is always asked.
        Returns True if saving succeeded.
        
        """
        if save_as or doc.url().isEmpty():
            filename = doc.url().toLocalFile()
            if filename:
                filetypes = app.filetypes(os.path.splitext(filename)[1])
            else:
                directory = app.basedir() # default directory to save to
                import documentinfo
                import ly.lex
                filename = os.path.join(directory, documentinfo.defaultfilename(doc))
                filetypes = app.filetypes(ly.lex.extensions[documentinfo.mode(doc)])
            caption = app.caption(_("dialog title", "Save File"))
            filename = QFileDialog.getSaveFileName(self, caption, filename, filetypes)
            if not filename:
                return False # cancelled
            url = QUrl.fromLocalFile(filename)
        else:
            url = doc.url()
        
        if QSettings().value("strip_trailing_whitespace", False, bool):
            import reformat
            reformat.remove_trailing_whitespace(QTextCursor(doc))

        # we only support local files for now
        filename = url.toLocalFile()
        b = backup.backup(filename)
        try:
            doc.save(url)
        except IOError as e:
            msg = _("{message}\n\n{strerror} ({errno})").format(
                message = _("Could not write to: {url}").format(url=filename),
                strerror = e.strerror,
                errno = e.errno)
            QMessageBox.critical(self, app.caption(_("Error")), msg)
            return False
        else:
            if b:
                backup.removeBackup(filename)
            recentfiles.add(doc.url())
        return True
Example #19
0
def html_copy(cursor, scheme="editor", number_lines=False):
    """Return a new QTextDocument with highlighting set as HTML textcharformats.
    
    The cursor is a cursor of a document.Document instance. If the cursor 
    has a selection, only the selection is put in the new document.
    
    If number_lines is True, line numbers are added.
    
    """
    data = textformats.formatData(scheme)
    doc = QTextDocument()
    doc.setDefaultFont(data.font)
    doc.setPlainText(cursor.document().toPlainText())
    if metainfo.info(cursor.document()).highlighting:
        highlight(doc, mapping(data), ly.lex.state(documentinfo.mode(cursor.document())))
    if cursor.hasSelection():
        # cut out not selected text
        start, end = cursor.selectionStart(), cursor.selectionEnd()
        cur1 = QTextCursor(doc)
        cur1.setPosition(start, QTextCursor.KeepAnchor)
        cur2 = QTextCursor(doc)
        cur2.setPosition(end)
        cur2.movePosition(QTextCursor.End, QTextCursor.KeepAnchor)
        cur2.removeSelectedText()
        cur1.removeSelectedText()
    if number_lines:
        c = QTextCursor(doc)
        f = QTextCharFormat()
        f.setBackground(QColor("#eeeeee"))
        if cursor.hasSelection():
            num = cursor.document().findBlock(cursor.selectionStart()).blockNumber() + 1
            last = cursor.document().findBlock(cursor.selectionEnd())
        else:
            num = 1
            last = cursor.document().lastBlock()
        lastnum = last.blockNumber() + 1
        padding = len(format(lastnum))
        block = doc.firstBlock()
        while block.isValid():
            c.setPosition(block.position())
            c.setCharFormat(f)
            c.insertText("{0:>{1}d} ".format(num, padding))
            block = block.next()
            num += 1
    return doc
Example #20
0
def save(mainwindow):

    titles = dict((snippets.title(name), name)
                  for name in model.model().names()
                  if 'template' in snippets.get(name).variables)

    # would it make sense to run LilyPond after creating a document from this
    # template?
    cursor = mainwindow.textCursor()
    template_run = False
    if documentinfo.mode(cursor.document()) == 'lilypond':
        dinfo = documentinfo.docinfo(cursor.document())
        if dinfo.complete() and dinfo.has_output():
            template_run = True

    dlg = TemplateDialog(mainwindow)
    c = QCompleter(sorted(titles), dlg.lineEdit())
    dlg.lineEdit().setCompleter(c)
    dlg.runCheck().setChecked(template_run)

    result = dlg.exec_()
    dlg.deleteLater()
    if not result:
        return  # cancelled

    title = dlg.text()
    template_run = dlg.runCheck().isChecked()

    if title in titles:
        if QMessageBox.critical(
                mainwindow, _("Overwrite Template?"),
                _("A template named \"{name}\" already exists.\n\n"
                  "Do you want to overwrite it?").format(name=title),
                QMessageBox.Yes | QMessageBox.Cancel) != QMessageBox.Yes:
            return
        name = titles[title]
    else:
        name = None

    # get the text and insert cursor position or selection
    text = cursor.document().toPlainText()

    repls = [(cursor.position(), '${CURSOR}')]
    if cursor.hasSelection():
        repls.append((cursor.anchor(), '${ANCHOR}'))
        repls.sort()

    result = []
    prev = 0
    for pos, what in repls:
        result.append(text[prev:pos].replace('$', '$$'))
        result.append(what)
        prev = pos
    result.append(text[prev:].replace('$', '$$'))
    text = ''.join(result)

    # add header line, if desired enable autorun
    headerline = '-*- template; indent: no;'
    if template_run:
        headerline += ' template-run;'
    text = headerline + '\n' + text

    # save the new snippet
    model.model().saveSnippet(name, text, title)
Example #21
0
 def _variablesChange(self):
     """Called whenever the variables have changed. Checks the mode."""
     mode = documentinfo.mode(self.document(), False)
     if mode != self._mode:
         self._mode = mode
         self.rehighlight()
Example #22
0
def save(mainwindow):

    titles = dict((snippets.title(name), name)
                  for name in model.model().names()
                  if 'template' in snippets.get(name).variables)

    # would it make sense to run LilyPond after creating a document from this
    # template?
    cursor = mainwindow.textCursor()
    template_run = False
    if documentinfo.mode(cursor.document()) == 'lilypond':
        dinfo = documentinfo.docinfo(cursor.document())
        if dinfo.complete() and dinfo.has_output():
            template_run = True

    dlg = TemplateDialog(mainwindow)
    c = QCompleter(sorted(titles), dlg.lineEdit())
    dlg.lineEdit().setCompleter(c)
    dlg.runCheck().setChecked(template_run)

    result = dlg.exec_()
    dlg.deleteLater()
    if not result:
        return # cancelled

    title = dlg.text()
    template_run = dlg.runCheck().isChecked()

    if title in titles:
        if QMessageBox.critical(mainwindow,
            _("Overwrite Template?"),
            _("A template named \"{name}\" already exists.\n\n"
              "Do you want to overwrite it?").format(name=title),
            QMessageBox.Yes | QMessageBox.Cancel) != QMessageBox.Yes:
            return
        name = titles[title]
    else:
        name = None

    # get the text and insert cursor position or selection
    text = cursor.document().toPlainText()

    repls = [(cursor.position(), '${CURSOR}')]
    if cursor.hasSelection():
        repls.append((cursor.anchor(), '${ANCHOR}'))
        repls.sort()

    result = []
    prev = 0
    for pos, what in repls:
        result.append(text[prev:pos].replace('$', '$$'))
        result.append(what)
        prev = pos
    result.append(text[prev:].replace('$', '$$'))
    text = ''.join(result)

    # add header line, if desired enable autorun
    headerline = '-*- template; indent: no;'
    if template_run:
        headerline += ' template-run;'
    text = headerline + '\n' + text

    # save the new snippet
    model.model().saveSnippet(name, text, title)
Example #23
0
 def _variablesChange(self):
     mode = documentinfo.mode(self.document(), False)
     if mode != self._mode:
         self._mode = mode
         self.rehighlight()
Example #24
0
 def _variablesChange(self):
     """Called whenever the variables have changed. Checks the mode."""
     mode = documentinfo.mode(self.document(), False)
     if mode != self._mode:
         self._mode = mode
         self.rehighlight()