]> git.lyx.org Git - lyx.git/blobdiff - src/CutAndPaste.cpp
Account for old versions of Pygments
[lyx.git] / src / CutAndPaste.cpp
index f41ce3641830e5d2be38e554440ee7737410e5ec..17dbdc626e1aa84f45e07e8f0f932eafecb33921 100644 (file)
 #include "support/lassert.h"
 #include "support/limited_stack.h"
 #include "support/lstrings.h"
+#include "support/lyxalgo.h"
 #include "support/TempFile.h"
+#include "support/unique_ptr.h"
 
 #include "frontends/alert.h"
 #include "frontends/Clipboard.h"
 #include "frontends/Selection.h"
 
-#include <boost/tuple/tuple.hpp>
-#include <boost/next_prior.hpp>
-
 #include <string>
+#include <tuple>
 
 using namespace std;
 using namespace lyx::support;
@@ -86,6 +86,8 @@ typedef limited_stack<pair<ParagraphList, DocumentClassConstPtr> > CutStack;
 CutStack theCuts(10);
 // persistent selection, cleared until the next selection
 CutStack selectionBuffer(1);
+// temporary scratch area
+CutStack tempCut(1);
 
 // store whether the tabular stack is newer than the normal copy stack
 // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
@@ -100,18 +102,18 @@ bool checkPastePossible(int index)
 
 
 struct PasteReturnValue {
-       PasteReturnValue(pit_type r_par, pos_type r_pos, bool r_nu) :
-         par(r_par), pos(r_pos), needupdate(r_nu)
+       PasteReturnValue(pit_type r_pit, pos_type r_pos, bool r_nu) :
+         pit(r_pit), pos(r_pos), needupdate(r_nu)
        {}
 
-       pit_type par;
+       pit_type pit;
        pos_type pos;
        bool needupdate;
 };
 
 PasteReturnValue
 pasteSelectionHelper(DocIterator const & cur, ParagraphList const & parlist,
-                     DocumentClassConstPtr oldDocClass, Buffer * tmpbuffer,
+                     DocumentClassConstPtr oldDocClass, cap::BranchAction branchAction,
                      ErrorList & errorlist)
 {
        Buffer const & buffer = *cur.buffer();
@@ -160,7 +162,7 @@ pasteSelectionHelper(DocIterator const & cur, ParagraphList const & parlist,
        // set the paragraphs to plain layout if necessary
        DocumentClassConstPtr newDocClass = buffer.params().documentClassPtr();
        if (cur.inset().usePlainLayout()) {
-               bool forcePlainLayout = cur.inset().forcePlainLayout();
+               bool forcePlainLayout = target_inset->forcePlainLayout();
                Layout const & plainLayout = newDocClass->plainLayout();
                Layout const & defaultLayout = newDocClass->defaultLayout();
                ParagraphList::iterator const end = insertion.end();
@@ -355,12 +357,15 @@ pasteSelectionHelper(DocIterator const & cur, ParagraphList const & parlist,
                            || (is_child && (branchlist.find(name)
                                || buffer.masterBuffer()->params().branchlist().find(name))))
                                break;
-                       if (tmpbuffer) {
+                       switch(branchAction) {
+                       case cap::BRANCH_ADD: {
                                // This is for a temporary buffer, so simply create the branch.
                                // Must not use lyx::dispatch(), since tmpbuffer has no view.
                                DispatchResult dr;
-                               tmpbuffer->dispatch(FuncRequest(LFUN_BRANCH_ADD, name), dr);
-                       } else {
+                               const_cast<Buffer&>(buffer).dispatch(FuncRequest(LFUN_BRANCH_ADD, name), dr);
+                               break;
+                       }
+                       case cap::BRANCH_ASK: {
                                docstring text = bformat(
                                        _("The pasted branch \"%1$s\" is undefined.\n"
                                          "Do you want to add it to the document's branch list?"),
@@ -369,6 +374,10 @@ pasteSelectionHelper(DocIterator const & cur, ParagraphList const & parlist,
                                          text, 0, 1, _("&Add"), _("&Don't Add")) != 0)
                                        break;
                                lyx::dispatch(FuncRequest(LFUN_BRANCH_ADD, name));
+                               break;
+                       }
+                       case cap::BRANCH_IGNORE:
+                               break;
                        }
                        // We need to update the list of branches.
                        need_update = true;
@@ -387,7 +396,7 @@ pasteSelectionHelper(DocIterator const & cur, ParagraphList const & parlist,
 
        // Paste it!
        if (empty) {
-               pars.insert(boost::next(pars.begin(), pit),
+               pars.insert(lyx::next(pars.begin(), pit),
                            insertion.begin(),
                            insertion.end());
 
@@ -395,7 +404,7 @@ pasteSelectionHelper(DocIterator const & cur, ParagraphList const & parlist,
                mergeParagraph(buffer.params(), pars,
                               pit + insertion.size() - 1);
        } else {
-               pars.insert(boost::next(pars.begin(), pit + 1),
+               pars.insert(lyx::next(pars.begin(), pit + 1),
                            insertion.begin(),
                            insertion.end());
 
@@ -480,27 +489,28 @@ PitPosPair eraseSelectionHelper(BufferParams const & params,
 }
 
 
-void putClipboard(ParagraphList const & paragraphs, 
-       DocumentClassConstPtr docclass, docstring const & plaintext)
+Buffer * copyToTempBuffer(ParagraphList const & paragraphs, DocumentClassConstPtr docclass)
 {
        // This used to need to be static to avoid a memory leak. It no longer needs
        // to be so, but the alternative is to construct a new one of these (with a
        // new temporary directory, etc) every time, and then to destroy it. So maybe
        // it's worth just keeping this one around.
-       // FIXME THREAD
        static TempFile tempfile("clipboard.internal");
        tempfile.setAutoRemove(false);
-       static Buffer * staticbuffer = theBufferList().newInternalBuffer(
-                       tempfile.name().absFileName());
-
-       // These two things only really need doing the first time.
-       staticbuffer->setUnnamed(true);
-       staticbuffer->inset().setBuffer(*staticbuffer);
-
+       // The initialization of staticbuffer is thread-safe. Using a lambda
+       // guarantees that the properties are set only once.
+       static Buffer * staticbuffer = [&](){
+               Buffer * b =
+                       theBufferList().newInternalBuffer(tempfile.name().absFileName());
+               b->setUnnamed(true);
+               b->inset().setBuffer(*b);
+               //initialize staticbuffer with b
+               return b;
+       }();
        // Use a clone for the complicated stuff so that we do not need to clean
        // up in order to avoid a crash.
        Buffer * buffer = staticbuffer->cloneBufferOnly();
-       LASSERT(buffer, return);
+       LASSERT(buffer, return 0);
 
        // This needs doing every time.
        // Since setDocumentClass() causes deletion of the old document class
@@ -520,7 +530,18 @@ void putClipboard(ParagraphList const & paragraphs,
        // temporary Buffer, since it does a lot of things to fix them up.
        DocIterator dit = doc_iterator_begin(buffer, &buffer->inset());
        ErrorList el;
-       pasteSelectionHelper(dit, paragraphs, docclass, buffer, el);
+       pasteSelectionHelper(dit, paragraphs, docclass, cap::BRANCH_ADD, el);
+
+       return buffer;
+}
+
+
+void putClipboard(ParagraphList const & paragraphs, 
+       DocumentClassConstPtr docclass, docstring const & plaintext)
+{
+       Buffer * buffer = copyToTempBuffer(paragraphs, docclass);
+       if (!buffer) // already asserted in copyToTempBuffer()
+               return;
 
        // We don't want to produce images that are not used. Therefore,
        // output formulas as MathML. Even if this is not understood by all
@@ -589,8 +610,8 @@ void copySelectionHelper(Buffer const & buf, Text const & text,
        LASSERT(startpit != endpit || start <= end, return);
 
        // Clone the paragraphs within the selection.
-       ParagraphList copy_pars(boost::next(pars.begin(), startpit),
-                               boost::next(pars.begin(), endpit + 1));
+       ParagraphList copy_pars(lyx::next(pars.begin(), startpit),
+                               lyx::next(pars.begin(), endpit + 1));
 
        // Remove the end of the last paragraph; afterwards, remove the
        // beginning of the first paragraph. Keep this order - there may only
@@ -631,7 +652,7 @@ void copySelectionHelper(Buffer const & buf, Text const & text,
        // are not linked to something else.
        it = copy_pars.begin();
        for (; it != it_end; ++it) {
-               it->setBuffer(*static_cast<Buffer *>(0));
+               it->resetBuffer();
                it->setInsetOwner(0);
        }
 
@@ -739,8 +760,8 @@ void switchBetweenClasses(DocumentClassConstPtr oldone,
                if (added_one || newlayouts.find(name) != newlayouts.end()) {
                        // Warn the user.
                        docstring const s = bformat(_("Layout `%1$s' was not found."), name);
-                       errorlist.push_back(
-                               ErrorItem(_("Layout Not Found"), s, it->id(), 0, it->size()));
+                       errorlist.push_back(ErrorItem(_("Layout Not Found"), s,
+                                                     {it->id(), 0}, {it->id(), -1}));
                }
 
                if (in.usePlainLayout())
@@ -775,8 +796,9 @@ void switchBetweenClasses(DocumentClassConstPtr oldone,
                                        layoutName, oldname, newname);
                        // To warn the user that something had to be done.
                        errorlist.push_back(ErrorItem(
-                                       _("Undefined flex inset"),
-                                       s, it.paragraph().id(), it.pos(), it.pos() + 1));
+                                                     _("Undefined flex inset"), s,
+                                                     {it.paragraph().id(), it.pos()},
+                                                     {it.paragraph().id(), it.pos()+1}));
                } else if (code == TABULAR_CODE) {
                        // The recursion above does not catch paragraphs in "hidden" cells,
                        // i.e., ones that are part of a multirow or multicolum. So we need
@@ -801,22 +823,20 @@ vector<docstring> availableSelections(Buffer const * buf)
                // we do not use cit-> here because gcc 2.9x does not
                // like it (JMarc)
                ParagraphList const & pars = (*cit).first;
-               docstring asciiSel;
+               docstring textSel;
                ParagraphList::const_iterator pit = pars.begin();
                ParagraphList::const_iterator pend = pars.end();
                for (; pit != pend; ++pit) {
-                       Paragraph par(*pit, 0, 26);
+                       Paragraph par(*pit, 0, 46);
                        // adapt paragraph to current buffer.
                        par.setBuffer(const_cast<Buffer &>(*buf));
-                       asciiSel += par.asString(AS_STR_INSETS);
-                       if (asciiSel.size() > 25) {
-                               asciiSel.replace(22, docstring::npos,
-                                                from_ascii("..."));
+                       textSel += par.asString(AS_STR_INSETS);
+                       if (textSel.size() > 45) {
+                               support::truncateWithEllipsis(textSel,45);
                                break;
                        }
                }
-
-               selList.push_back(asciiSel);
+               selList.push_back(textSel);
        }
 
        return selList;
@@ -828,8 +848,9 @@ size_type numberOfSelections()
        return theCuts.size();
 }
 
+namespace {
 
-void cutSelection(Cursor & cur, bool doclear, bool realcut)
+void cutSelectionHelper(Cursor & cur, CutStack & cuts, bool doclear, bool realcut, bool putclip)
 {
        // This doesn't make sense, if there is no selection
        if (!cur.selection())
@@ -857,21 +878,20 @@ void cutSelection(Cursor & cur, bool doclear, bool realcut)
                                *text,
                                begpit, endpit,
                                cur.selBegin().pos(), endpos,
-                               bp.documentClassPtr(), theCuts);
+                               bp.documentClassPtr(), cuts);
                        // Stuff what we got on the clipboard.
                        // Even if there is no selection.
-                       putClipboard(theCuts[0].first, theCuts[0].second,
-                               cur.selectionAsString(true));
+                       if (putclip)
+                               putClipboard(cuts[0].first, cuts[0].second,
+                                            cur.selectionAsString(true));
                }
 
                if (begpit != endpit)
                        cur.screenUpdateFlags(Update::Force | Update::FitCursor);
 
-               boost::tie(endpit, endpos) =
-                       eraseSelectionHelper(bp,
-                               text->paragraphs(),
-                               begpit, endpit,
-                               cur.selBegin().pos(), endpos);
+               tie(endpit, endpos) =
+                       eraseSelectionHelper(bp, text->paragraphs(), begpit, endpit,
+                                            cur.selBegin().pos(), endpos);
 
                // cutSelection can invalidate the cursor so we need to set
                // it anew. (Lgb)
@@ -913,6 +933,19 @@ void cutSelection(Cursor & cur, bool doclear, bool realcut)
        }
 }
 
+}
+
+void cutSelection(Cursor & cur, bool doclear, bool realcut)
+{
+       cutSelectionHelper(cur, theCuts, doclear, realcut, true);
+}
+
+
+void cutSelectionToTemp(Cursor & cur, bool doclear, bool realcut)
+{
+       cutSelectionHelper(cur, tempCut, doclear, realcut, false);
+}
+
 
 void copySelection(Cursor const & cur)
 {
@@ -953,20 +986,11 @@ void copySelectionToStack(Cursor const & cur, CutStack & cutstack)
                LBUFERR(text);
                // ok we have a selection. This is always between cur.selBegin()
                // and sel_end cursor
-
-               // copy behind a space if there is one
-               ParagraphList & pars = text->paragraphs();
-               pos_type pos = cur.selBegin().pos();
-               pit_type par = cur.selBegin().pit();
-               while (pos < pars[par].size() &&
-                      pars[par].isLineSeparator(pos) &&
-                      (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
-                       ++pos;
-
-               copySelectionHelper(*cur.buffer(), *text, par, cur.selEnd().pit(),
-                       pos, cur.selEnd().pos(), 
-                       cur.buffer()->params().documentClassPtr(), cutstack);
-
+               copySelectionHelper(*cur.buffer(), *text,
+                                   cur.selBegin().pit(), cur.selEnd().pit(),
+                                   cur.selBegin().pos(), cur.selEnd().pos(), 
+                                   cur.buffer()->params().documentClassPtr(),
+                                   cutstack);
                // Reset the dirty_tabular_stack_ flag only when something
                // is copied to the clipboard (not to the selectionBuffer).
                if (&cutstack == &theCuts)
@@ -1048,29 +1072,37 @@ void clearSelection()
 void clearCutStack()
 {
        theCuts.clear();
+       tempCut.clear();
 }
 
 
-docstring selection(size_t sel_index)
+docstring selection(size_t sel_index, DocumentClassConstPtr docclass)
 {
-       return sel_index < theCuts.size()
-               ? theCuts[sel_index].first.back().asString(AS_STR_INSETS | AS_STR_NEWLINES)
-               : docstring();
+       if (sel_index >= theCuts.size())
+               return docstring();
+
+       unique_ptr<Buffer> buffer(copyToTempBuffer(theCuts[sel_index].first,
+                                                  docclass));
+       if (!buffer)
+               return docstring();
+
+       return buffer->paragraphs().back().asString(AS_STR_INSETS | AS_STR_NEWLINES);
 }
 
 
 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
-                       DocumentClassConstPtr docclass, ErrorList & errorList)
+                                               DocumentClassConstPtr docclass, ErrorList & errorList,
+                                               cap::BranchAction branchAction)
 {
        if (cur.inTexted()) {
                Text * text = cur.text();
                LBUFERR(text);
 
                PasteReturnValue prv =
-                       pasteSelectionHelper(cur, parlist, docclass, 0, errorList);
+                       pasteSelectionHelper(cur, parlist, docclass, branchAction, errorList);
                cur.forceBufferUpdate();
                cur.clearSelection();
-               text->setCursor(cur, prv.par, prv.pos);
+               text->setCursor(cur, prv.pit, prv.pos);
        }
 
        // mathed is handled in InsetMathNest/InsetMathGrid
@@ -1086,7 +1118,20 @@ bool pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
 
        cur.recordUndo();
        pasteParagraphList(cur, theCuts[sel_index].first,
-                          theCuts[sel_index].second, errorList);
+                          theCuts[sel_index].second, errorList, BRANCH_ASK);
+       return true;
+}
+
+
+bool pasteFromTemp(Cursor & cur, ErrorList & errorList)
+{
+       // this does not make sense, if there is nothing to paste
+       if (tempCut.empty() || tempCut[0].first.empty())
+               return false;
+
+       cur.recordUndo();
+       pasteParagraphList(cur, tempCut[0].first,
+                          tempCut[0].second, errorList, BRANCH_IGNORE);
        return true;
 }
 
@@ -1165,6 +1210,7 @@ bool pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs,
                cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
        else
                cur.text()->insertStringAsLines(cur, text, cur.current_font);
+       cur.forceBufferUpdate();
        return true;
 }
 
@@ -1321,7 +1367,7 @@ void selClearOrDel(Cursor & cur)
        if (lyxrc.auto_region_delete)
                selDel(cur);
        else
-               cur.setSelection(false);
+               cur.selection(false);
 }