2 * \file CutAndPaste.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Lars Gullik Bjønnes
8 * \author Alfredo Braunstein
11 * Full author contact details are available in file CREDITS.
16 #include "CutAndPaste.h"
18 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "BufferView.h"
26 #include "ErrorList.h"
28 #include "FuncRequest.h"
29 #include "InsetIterator.h"
30 #include "InsetList.h"
35 #include "Paragraph.h"
36 #include "ParagraphParameters.h"
37 #include "ParIterator.h"
38 #include "TextClass.h"
40 #include "insets/InsetBibitem.h"
41 #include "insets/InsetBranch.h"
42 #include "insets/InsetCommand.h"
43 #include "insets/InsetFlex.h"
44 #include "insets/InsetGraphics.h"
45 #include "insets/InsetGraphicsParams.h"
46 #include "insets/InsetInclude.h"
47 #include "insets/InsetLabel.h"
48 #include "insets/InsetTabular.h"
50 #include "mathed/MathData.h"
51 #include "mathed/InsetMath.h"
52 #include "mathed/InsetMathHull.h"
53 #include "mathed/InsetMathRef.h"
54 #include "mathed/MathSupport.h"
56 #include "support/debug.h"
57 #include "support/docstream.h"
58 #include "support/gettext.h"
59 #include "support/lassert.h"
60 #include "support/limited_stack.h"
61 #include "support/lstrings.h"
63 #include "frontends/alert.h"
64 #include "frontends/Clipboard.h"
65 #include "frontends/Selection.h"
67 #include <boost/tuple/tuple.hpp>
68 #include <boost/next_prior.hpp>
73 using namespace lyx::support;
74 using lyx::frontend::Clipboard;
80 typedef pair<pit_type, int> PitPosPair;
82 typedef limited_stack<pair<ParagraphList, DocumentClassConstPtr> > CutStack;
85 // persistent selection, cleared until the next selection
86 CutStack selectionBuffer(1);
88 // store whether the tabular stack is newer than the normal copy stack
89 // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
90 // when we (hopefully) have a one-for-all paste mechanism.
91 bool dirty_tabular_stack_ = false;
94 bool checkPastePossible(int index)
96 return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
100 pair<PitPosPair, pit_type>
101 pasteSelectionHelper(Cursor const & cur, ParagraphList const & parlist,
102 DocumentClassConstPtr oldDocClass, ErrorList & errorlist)
104 Buffer const & buffer = *cur.buffer();
105 pit_type pit = cur.pit();
106 pos_type pos = cur.pos();
107 InsetText * target_inset = cur.inset().asInsetText();
109 InsetTabular * it = cur.inset().asInsetTabular();
110 target_inset = it? it->cell(cur.idx())->asInsetText() : 0;
112 LASSERT(target_inset, return make_pair(PitPosPair(pit, pos), pit));
113 ParagraphList & pars = target_inset->paragraphs();
116 return make_pair(PitPosPair(pit, pos), pit);
118 BOOST_ASSERT (pos <= pars[pit].size());
120 // Make a copy of the CaP paragraphs.
121 ParagraphList insertion = parlist;
122 DocumentClassConstPtr newDocClass = buffer.params().documentClassPtr();
124 // Now remove all out of the pars which is NOT allowed in the
125 // new environment and set also another font if that is required.
127 // Convert newline to paragraph break in ParbreakIsNewline
128 if (target_inset->getLayout().parbreakIsNewline()
129 || pars[pit].layout().parbreak_is_newline) {
130 for (size_t i = 0; i != insertion.size(); ++i) {
131 for (pos_type j = 0; j != insertion[i].size(); ++j) {
132 if (insertion[i].isNewline(j)) {
133 // do not track deletion of newline
134 insertion[i].eraseChar(j, false);
135 insertion[i].setInsetOwner(target_inset);
136 breakParagraphConservative(
145 // set the paragraphs to plain layout if necessary
146 if (cur.inset().usePlainLayout()) {
147 bool forcePlainLayout = cur.inset().forcePlainLayout();
148 Layout const & plainLayout = newDocClass->plainLayout();
149 Layout const & defaultLayout = newDocClass->defaultLayout();
150 ParagraphList::iterator const end = insertion.end();
151 ParagraphList::iterator par = insertion.begin();
152 for (; par != end; ++par) {
153 Layout const & parLayout = par->layout();
154 if (forcePlainLayout || parLayout == defaultLayout)
155 par->setLayout(plainLayout);
157 } else { // check if we need to reset from plain layout
158 Layout const & defaultLayout = newDocClass->defaultLayout();
159 Layout const & plainLayout = newDocClass->plainLayout();
160 ParagraphList::iterator const end = insertion.end();
161 ParagraphList::iterator par = insertion.begin();
162 for (; par != end; ++par) {
163 Layout const & parLayout = par->layout();
164 if (parLayout == plainLayout)
165 par->setLayout(defaultLayout);
169 InsetText in(cur.buffer());
170 // Make sure there is no class difference.
171 in.paragraphs().clear();
172 // This works without copying any paragraph data because we have
173 // a specialized swap method for ParagraphList. This is important
174 // since we store pointers to insets at some places and we don't
175 // want to invalidate them.
176 insertion.swap(in.paragraphs());
177 cap::switchBetweenClasses(oldDocClass, newDocClass, in, errorlist);
178 insertion.swap(in.paragraphs());
180 ParagraphList::iterator tmpbuf = insertion.begin();
181 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
183 depth_type max_depth = pars[pit].getMaxDepthAfter();
185 for (; tmpbuf != insertion.end(); ++tmpbuf) {
186 // If we have a negative jump so that the depth would
187 // go below 0 depth then we have to redo the delta to
188 // this new max depth level so that subsequent
189 // paragraphs are aligned correctly to this paragraph
191 if (int(tmpbuf->params().depth()) + depth_delta < 0)
194 // Set the right depth so that we are not too deep or shallow.
195 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
196 if (tmpbuf->params().depth() > max_depth)
197 tmpbuf->params().depth(max_depth);
199 // Only set this from the 2nd on as the 2nd depends
200 // for maxDepth still on pit.
201 if (tmpbuf != insertion.begin())
202 max_depth = tmpbuf->getMaxDepthAfter();
204 // Set the inset owner of this paragraph.
205 tmpbuf->setInsetOwner(target_inset);
206 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
207 // do not track deletion of invalid insets
208 if (Inset * inset = tmpbuf->getInset(i))
209 if (!target_inset->insetAllowed(inset->lyxCode()))
210 tmpbuf->eraseChar(i--, false);
213 tmpbuf->setChange(Change(buffer.params().trackChanges ?
214 Change::INSERTED : Change::UNCHANGED));
217 bool const empty = pars[pit].empty();
219 // Make the buf exactly the same layout as the cursor
221 insertion.begin()->makeSameLayout(pars[pit]);
224 // Prepare the paragraphs and insets for insertion.
225 insertion.swap(in.paragraphs());
227 InsetIterator const i_end = inset_iterator_end(in);
228 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
229 // Even though this will also be done later, it has to be done here
230 // since some inset might going to try to access
231 // the buffer() member.
232 it->setBuffer(const_cast<Buffer &>(buffer));
233 switch (it->lyxCode()) {
235 case MATH_HULL_CODE: {
236 // check for equation labels and resolve duplicates
237 InsetMathHull * ins = it->asInsetMath()->asHullInset();
238 std::vector<InsetLabel *> labels = ins->getLabels();
239 for (size_t i = 0; i != labels.size(); ++i) {
242 InsetLabel * lab = labels[i];
243 docstring const oldname = lab->getParam("name");
244 lab->updateLabel(oldname);
245 // We need to update the buffer reference cache.
246 cur.forceBufferUpdate();
247 docstring const newname = lab->getParam("name");
248 if (oldname == newname)
250 // adapt the references
251 for (InsetIterator itt = inset_iterator_begin(in);
252 itt != i_end; ++itt) {
253 if (itt->lyxCode() == REF_CODE) {
254 InsetCommand * ref = itt->asInsetCommand();
255 if (ref->getParam("reference") == oldname)
256 ref->setParam("reference", newname);
257 } else if (itt->lyxCode() == MATH_REF_CODE) {
258 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
259 // this is necessary to prevent an uninitialized
260 // buffer when the RefInset is in a MathBox.
261 // FIXME audit setBuffer calls
262 mi->setBuffer(const_cast<Buffer &>(buffer));
263 if (mi->getTarget() == oldname)
264 mi->changeTarget(newname);
272 // check for duplicates
273 InsetLabel & lab = static_cast<InsetLabel &>(*it);
274 docstring const oldname = lab.getParam("name");
275 lab.updateLabel(oldname);
276 // We need to update the buffer reference cache.
277 cur.forceBufferUpdate();
278 docstring const newname = lab.getParam("name");
279 if (oldname == newname)
281 // adapt the references
282 for (InsetIterator itt = inset_iterator_begin(in); itt != i_end; ++itt) {
283 if (itt->lyxCode() == REF_CODE) {
284 InsetCommand & ref = static_cast<InsetCommand &>(*itt);
285 if (ref.getParam("reference") == oldname)
286 ref.setParam("reference", newname);
287 } else if (itt->lyxCode() == MATH_REF_CODE) {
288 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
289 // this is necessary to prevent an uninitialized
290 // buffer when the RefInset is in a MathBox.
291 // FIXME audit setBuffer calls
292 mi->setBuffer(const_cast<Buffer &>(buffer));
293 if (mi->getTarget() == oldname)
294 mi->changeTarget(newname);
301 InsetInclude & inc = static_cast<InsetInclude &>(*it);
303 // We need to update the list of included files.
304 cur.forceBufferUpdate();
309 // check for duplicates
310 InsetBibitem & bib = static_cast<InsetBibitem &>(*it);
311 docstring const oldkey = bib.getParam("key");
312 bib.updateCommand(oldkey, false);
313 // We need to update the buffer reference cache.
314 cur.forceBufferUpdate();
315 docstring const newkey = bib.getParam("key");
316 if (oldkey == newkey)
318 // adapt the references
319 for (InsetIterator itt = inset_iterator_begin(in);
320 itt != i_end; ++itt) {
321 if (itt->lyxCode() == CITE_CODE) {
322 InsetCommand * ref = itt->asInsetCommand();
323 if (ref->getParam("key") == oldkey)
324 ref->setParam("key", newkey);
331 // check if branch is known to target buffer
333 InsetBranch & br = static_cast<InsetBranch &>(*it);
334 docstring const name = br.branch();
337 bool const is_child = (&buffer != buffer.masterBuffer());
338 BranchList branchlist = buffer.params().branchlist();
339 if ((!is_child && branchlist.find(name))
340 || (is_child && (branchlist.find(name)
341 || buffer.masterBuffer()->params().branchlist().find(name))))
343 // FIXME: add an option to add the branch to the master's BranchList.
344 docstring text = bformat(
345 _("The pasted branch \"%1$s\" is undefined.\n"
346 "Do you want to add it to the document's branch list?"),
348 if (frontend::Alert::prompt(_("Unknown branch"),
349 text, 0, 1, _("&Add"), _("&Don't Add")) != 0)
351 lyx::dispatch(FuncRequest(LFUN_BRANCH_ADD, name));
352 // We need to update the list of branches.
353 cur.forceBufferUpdate();
361 insertion.swap(in.paragraphs());
363 // Split the paragraph for inserting the buf if necessary.
365 breakParagraphConservative(buffer.params(), pars, pit, pos);
369 pars.insert(boost::next(pars.begin(), pit),
373 // merge the empty par with the last par of the insertion
374 mergeParagraph(buffer.params(), pars,
375 pit + insertion.size() - 1);
377 pars.insert(boost::next(pars.begin(), pit + 1),
381 // merge the first par of the insertion with the current par
382 mergeParagraph(buffer.params(), pars, pit);
385 // Store the new cursor position.
386 pit_type last_paste = pit + insertion.size() - 1;
387 pit_type startpit = pit;
389 pos = pars[last_paste].size();
391 // FIXME Should we do it here, or should we let updateBuffer() do it?
392 // Set paragraph buffers. It's important to do this right away
393 // before something calls Inset::buffer() and causes a crash.
394 for (pit_type p = startpit; p <= pit; ++p)
395 pars[p].setBuffer(const_cast<Buffer &>(buffer));
397 // Join (conditionally) last pasted paragraph with next one, i.e.,
398 // the tail of the spliced document paragraph
399 if (!empty && last_paste + 1 != pit_type(pars.size())) {
400 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
401 mergeParagraph(buffer.params(), pars, last_paste);
402 } else if (pars[last_paste + 1].empty()) {
403 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
404 mergeParagraph(buffer.params(), pars, last_paste);
405 } else if (pars[last_paste].empty()) {
406 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
407 mergeParagraph(buffer.params(), pars, last_paste);
409 pars[last_paste + 1].stripLeadingSpaces(buffer.params().trackChanges);
414 return make_pair(PitPosPair(pit, pos), last_paste + 1);
418 PitPosPair eraseSelectionHelper(BufferParams const & params,
419 ParagraphList & pars,
420 pit_type startpit, pit_type endpit,
421 int startpos, int endpos)
423 // Start of selection is really invalid.
424 if (startpit == pit_type(pars.size()) ||
425 (startpos > pars[startpit].size()))
426 return PitPosPair(endpit, endpos);
428 // Start and end is inside same paragraph
429 if (endpit == pit_type(pars.size()) || startpit == endpit) {
430 endpos -= pars[startpit].eraseChars(startpos, endpos, params.trackChanges);
431 return PitPosPair(endpit, endpos);
434 for (pit_type pit = startpit; pit != endpit + 1;) {
435 pos_type const left = (pit == startpit ? startpos : 0);
436 pos_type right = (pit == endpit ? endpos : pars[pit].size() + 1);
437 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.trackChanges);
439 // Logically erase only, including the end-of-paragraph character
440 pars[pit].eraseChars(left, right, params.trackChanges);
442 // Separate handling of paragraph break:
443 if (merge && pit != endpit &&
445 || pars[pit].hasSameLayout(pars[endpit])
446 || pars[endpit].size() == endpos)) {
447 if (pit + 1 == endpit)
448 endpos += pars[pit].size();
449 mergeParagraph(params, pars, pit);
455 // Ensure legal cursor pos:
458 return PitPosPair(endpit, endpos);
462 void putClipboard(ParagraphList const & paragraphs,
463 DocumentClassConstPtr docclass, docstring const & plaintext)
465 // For some strange reason gcc 3.2 and 3.3 do not accept
466 // Buffer buffer(string(), false);
467 // This used to need to be static to avoid a memory leak. It no longer needs
468 // to be so, but the alternative is to construct a new one of these (with a
469 // new temporary directory, etc) every time, and then to destroy it. So maybe
470 // it's worth just keeping this one around.
471 static Buffer * buffer = theBufferList().newInternalBuffer(
472 FileName::tempName("clipboard.internal").absFileName());
473 buffer->setUnnamed(true);
474 buffer->paragraphs() = paragraphs;
475 buffer->inset().setBuffer(*buffer);
476 buffer->params().setDocumentClass(docclass);
478 if (buffer->write(lyx))
479 theClipboard().put(lyx.str(), plaintext);
481 theClipboard().put(string(), plaintext);
483 buffer->paragraphs().clear();
487 /// return true if the whole ParagraphList is deleted
488 static bool isFullyDeleted(ParagraphList const & pars)
490 pit_type const pars_size = static_cast<pit_type>(pars.size());
492 // check all paragraphs
493 for (pit_type pit = 0; pit < pars_size; ++pit) {
494 if (!pars[pit].empty()) // prevent assertion failure
495 if (!pars[pit].isDeleted(0, pars[pit].size()))
502 void copySelectionHelper(Buffer const & buf, Text const & text,
503 pit_type startpit, pit_type endpit,
504 int start, int end, DocumentClassConstPtr dc, CutStack & cutstack)
506 ParagraphList const & pars = text.paragraphs();
508 LASSERT(0 <= start && start <= pars[startpit].size(), /**/);
509 LASSERT(0 <= end && end <= pars[endpit].size(), /**/);
510 LASSERT(startpit != endpit || start <= end, /**/);
512 // Clone the paragraphs within the selection.
513 ParagraphList copy_pars(boost::next(pars.begin(), startpit),
514 boost::next(pars.begin(), endpit + 1));
516 // Remove the end of the last paragraph; afterwards, remove the
517 // beginning of the first paragraph. Keep this order - there may only
518 // be one paragraph! Do not track deletions here; this is an internal
519 // action not visible to the user
521 Paragraph & back = copy_pars.back();
522 back.eraseChars(end, back.size(), false);
523 Paragraph & front = copy_pars.front();
524 front.eraseChars(0, start, false);
526 ParagraphList::iterator it = copy_pars.begin();
527 ParagraphList::iterator it_end = copy_pars.end();
529 for (; it != it_end; ++it) {
530 // Since we have a copy of the paragraphs, the insets
531 // do not have a proper buffer reference. It makes
532 // sense to add them temporarily, because the
533 // operations below depend on that (acceptChanges included).
534 it->setBuffer(const_cast<Buffer &>(buf));
535 // PassThru paragraphs have the Language
536 // latex_language. This is invalid for others, so we
537 // need to change it to the buffer language.
538 if (it->isPassThru())
539 it->changeLanguage(buf.params(),
540 latex_language, buf.language());
543 // do not copy text (also nested in insets) which is marked as
544 // deleted, unless the whole selection was deleted
545 if (!isFullyDeleted(copy_pars))
546 acceptChanges(copy_pars, buf.params());
548 rejectChanges(copy_pars, buf.params());
551 // do some final cleanup now, to make sure that the paragraphs
552 // are not linked to something else.
553 it = copy_pars.begin();
554 for (; it != it_end; ++it) {
555 it->setBuffer(*static_cast<Buffer *>(0));
556 it->setInsetOwner(0);
559 cutstack.push(make_pair(copy_pars, dc));
569 void region(CursorSlice const & i1, CursorSlice const & i2,
570 Inset::row_type & r1, Inset::row_type & r2,
571 Inset::col_type & c1, Inset::col_type & c2)
573 Inset & p = i1.inset();
574 c1 = p.col(i1.idx());
575 c2 = p.col(i2.idx());
578 r1 = p.row(i1.idx());
579 r2 = p.row(i2.idx());
585 docstring grabAndEraseSelection(Cursor & cur)
587 if (!cur.selection())
589 docstring res = grabSelection(cur);
595 bool reduceSelectionToOneCell(Cursor & cur)
597 if (!cur.selection() || !cur.inMathed())
600 CursorSlice i1 = cur.selBegin();
601 CursorSlice i2 = cur.selEnd();
602 if (!i1.inset().asInsetMath())
605 // the easy case: do nothing if only one cell is selected
606 if (i1.idx() == i2.idx())
611 cur.top().pos() = cur.top().lastpos();
617 bool multipleCellsSelected(Cursor const & cur)
619 if (!cur.selection() || !cur.inMathed())
622 CursorSlice i1 = cur.selBegin();
623 CursorSlice i2 = cur.selEnd();
624 if (!i1.inset().asInsetMath())
627 if (i1.idx() == i2.idx())
634 void switchBetweenClasses(DocumentClassConstPtr oldone,
635 DocumentClassConstPtr newone, InsetText & in, ErrorList & errorlist)
639 LASSERT(!in.paragraphs().empty(), /**/);
640 if (oldone == newone)
643 DocumentClass const & oldtc = *oldone;
644 DocumentClass const & newtc = *newone;
647 ParIterator it = par_iterator_begin(in);
648 ParIterator end = par_iterator_end(in);
649 // for remembering which layouts we've had to add
650 set<docstring> newlayouts;
651 for (; it != end; ++it) {
652 docstring const name = it->layout().name();
654 // the pasted text will keep their own layout name. If this layout does
655 // not exist in the new document, it will behave like a standard layout.
656 bool const added_one = newtc.addLayoutIfNeeded(name);
658 newlayouts.insert(name);
660 if (added_one || newlayouts.find(name) != newlayouts.end()) {
662 docstring const s = bformat(_("Layout `%1$s' was not found."), name);
664 ErrorItem(_("Layout Not Found"), s, it->id(), 0, it->size()));
667 if (in.usePlainLayout())
668 it->setLayout(newtc.plainLayout());
670 it->setLayout(newtc[name]);
674 InsetIterator const i_end = inset_iterator_end(in);
675 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
676 if (it->lyxCode() != FLEX_CODE)
677 // FIXME: Should we verify all InsetCollapsable?
680 docstring const layoutName = it->layoutName();
681 docstring const & n = newone->insetLayout(layoutName).name();
682 bool const is_undefined = n.empty() ||
683 n == DocumentClass::plainInsetLayout().name();
687 // The flex inset is undefined in newtc
688 docstring const oldname = from_utf8(oldtc.name());
689 docstring const newname = from_utf8(newtc.name());
691 if (oldname == newname)
692 s = bformat(_("Flex inset %1$s is undefined after "
693 "reloading `%2$s' layout."), layoutName, oldname);
695 s = bformat(_("Flex inset %1$s is undefined because of "
696 "conversion from `%2$s' layout to `%3$s'."),
697 layoutName, oldname, newname);
698 // To warn the user that something had to be done.
699 errorlist.push_back(ErrorItem(
700 _("Undefined flex inset"),
701 s, it.paragraph().id(), it.pos(), it.pos() + 1));
706 vector<docstring> availableSelections(Buffer const * buf)
708 vector<docstring> selList;
712 CutStack::const_iterator cit = theCuts.begin();
713 CutStack::const_iterator end = theCuts.end();
714 for (; cit != end; ++cit) {
715 // we do not use cit-> here because gcc 2.9x does not
717 ParagraphList const & pars = (*cit).first;
719 ParagraphList::const_iterator pit = pars.begin();
720 ParagraphList::const_iterator pend = pars.end();
721 for (; pit != pend; ++pit) {
722 Paragraph par(*pit, 0, 26);
723 // adapt paragraph to current buffer.
724 par.setBuffer(const_cast<Buffer &>(*buf));
725 asciiSel += par.asString(AS_STR_INSETS);
726 if (asciiSel.size() > 25) {
727 asciiSel.replace(22, docstring::npos,
733 selList.push_back(asciiSel);
740 size_type numberOfSelections()
742 return theCuts.size();
746 void cutSelection(Cursor & cur, bool doclear, bool realcut)
748 // This doesn't make sense, if there is no selection
749 if (!cur.selection())
752 // OK, we have a selection. This is always between cur.selBegin()
755 if (cur.inTexted()) {
756 Text * text = cur.text();
761 // make sure that the depth behind the selection are restored, too
762 cur.recordUndoSelection();
763 pit_type begpit = cur.selBegin().pit();
764 pit_type endpit = cur.selEnd().pit();
766 int endpos = cur.selEnd().pos();
768 BufferParams const & bp = cur.buffer()->params();
770 copySelectionHelper(*cur.buffer(),
773 cur.selBegin().pos(), endpos,
774 bp.documentClassPtr(), theCuts);
775 // Stuff what we got on the clipboard.
776 // Even if there is no selection.
777 putClipboard(theCuts[0].first, theCuts[0].second,
778 cur.selectionAsString(true));
781 if (begpit != endpit)
782 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
784 boost::tie(endpit, endpos) =
785 eraseSelectionHelper(bp,
788 cur.selBegin().pos(), endpos);
790 // cutSelection can invalidate the cursor so we need to set
792 // we prefer the end for when tracking changes
796 // sometimes necessary
798 && text->paragraphs()[begpit].stripLeadingSpaces(bp.trackChanges))
801 // need a valid cursor. (Lgb)
802 cur.clearSelection();
804 // After a cut operation, we must make sure that the Buffer is updated
805 // because some further operation might need updated label information for
806 // example. So we cannot just use "cur.forceBufferUpdate()" here.
808 cur.buffer()->updateBuffer();
810 // tell tabular that a recent copy happened
811 dirtyTabularStack(false);
814 if (cur.inMathed()) {
815 if (cur.selBegin().idx() != cur.selEnd().idx()) {
816 // The current selection spans more than one cell.
818 cur.recordUndoInset();
820 // Record only the current cell to avoid a jumping
831 void copySelection(Cursor const & cur)
833 copySelection(cur, cur.selectionAsString(true));
837 void copyInset(Cursor const & cur, Inset * inset, docstring const & plaintext)
841 BufferParams const & bp = cur.buffer()->params();
842 par.setLayout(bp.documentClass().plainLayout());
843 par.insertInset(0, inset, Change(Change::UNCHANGED));
845 theCuts.push(make_pair(pars, bp.documentClassPtr()));
847 // stuff the selection onto the X clipboard, from an explicit copy request
848 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
854 void copySelectionToStack(Cursor const & cur, CutStack & cutstack)
856 // this doesn't make sense, if there is no selection
857 if (!cur.selection())
860 // copySelection can not yet handle the case of cross idx selection
861 if (cur.selBegin().idx() != cur.selEnd().idx())
864 if (cur.inTexted()) {
865 Text * text = cur.text();
867 // ok we have a selection. This is always between cur.selBegin()
868 // and sel_end cursor
870 // copy behind a space if there is one
871 ParagraphList & pars = text->paragraphs();
872 pos_type pos = cur.selBegin().pos();
873 pit_type par = cur.selBegin().pit();
874 while (pos < pars[par].size() &&
875 pars[par].isLineSeparator(pos) &&
876 (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
879 copySelectionHelper(*cur.buffer(), *text, par, cur.selEnd().pit(),
880 pos, cur.selEnd().pos(),
881 cur.buffer()->params().documentClassPtr(), cutstack);
883 // Reset the dirty_tabular_stack_ flag only when something
884 // is copied to the clipboard (not to the selectionBuffer).
885 if (&cutstack == &theCuts)
886 dirtyTabularStack(false);
889 if (cur.inMathed()) {
890 //lyxerr << "copySelection in mathed" << endl;
893 BufferParams const & bp = cur.buffer()->params();
894 // FIXME This should be the plain layout...right?
895 par.setLayout(bp.documentClass().plainLayout());
896 par.insert(0, grabSelection(cur), Font(), Change(Change::UNCHANGED));
898 cutstack.push(make_pair(pars, bp.documentClassPtr()));
905 void copySelectionToStack()
907 if (!selectionBuffer.empty())
908 theCuts.push(selectionBuffer[0]);
912 void copySelection(Cursor const & cur, docstring const & plaintext)
914 // In tablemode, because copy and paste actually use special table stack
915 // we do not attempt to get selected paragraphs under cursor. Instead, a
916 // paragraph with the plain text version is generated so that table cells
917 // can be pasted as pure text somewhere else.
918 if (cur.selBegin().idx() != cur.selEnd().idx()) {
921 BufferParams const & bp = cur.buffer()->params();
922 par.setLayout(bp.documentClass().plainLayout());
923 par.insert(0, plaintext, Font(), Change(Change::UNCHANGED));
925 theCuts.push(make_pair(pars, bp.documentClassPtr()));
927 copySelectionToStack(cur, theCuts);
930 // stuff the selection onto the X clipboard, from an explicit copy request
931 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
935 void saveSelection(Cursor const & cur)
937 // This function is called, not when a selection is formed, but when
938 // a selection is cleared. Therefore, multiple keyboard selection
939 // will not repeatively trigger this function (bug 3877).
941 && cur.selBegin() == cur.bv().cursor().selBegin()
942 && cur.selEnd() == cur.bv().cursor().selEnd()) {
943 LYXERR(Debug::SELECTION, "saveSelection: '" << cur.selectionAsString(true) << "'");
944 copySelectionToStack(cur, selectionBuffer);
951 return !selectionBuffer.empty();
955 void clearSelection()
957 selectionBuffer.clear();
967 docstring selection(size_t sel_index)
969 return sel_index < theCuts.size()
970 ? theCuts[sel_index].first.back().asString(AS_STR_INSETS | AS_STR_NEWLINES)
975 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
976 DocumentClassConstPtr docclass, ErrorList & errorList)
978 if (cur.inTexted()) {
979 Text * text = cur.text();
985 boost::tie(ppp, endpit) =
986 pasteSelectionHelper(cur, parlist, docclass, errorList);
987 cur.forceBufferUpdate();
988 cur.clearSelection();
989 text->setCursor(cur, ppp.first, ppp.second);
992 // mathed is handled in InsetMathNest/InsetMathGrid
993 LASSERT(!cur.inMathed(), /**/);
997 void pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
999 // this does not make sense, if there is nothing to paste
1000 if (!checkPastePossible(sel_index))
1004 pasteParagraphList(cur, theCuts[sel_index].first,
1005 theCuts[sel_index].second, errorList);
1009 void pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs)
1011 // Use internal clipboard if it is the most recent one
1012 if (theClipboard().isInternal()) {
1013 pasteFromStack(cur, errorList, 0);
1017 // First try LyX format
1018 if (theClipboard().hasLyXContents()) {
1019 string lyx = theClipboard().getAsLyX();
1021 // For some strange reason gcc 3.2 and 3.3 do not accept
1022 // Buffer buffer(string(), false);
1023 Buffer buffer("", false);
1024 buffer.setUnnamed(true);
1025 if (buffer.readString(lyx)) {
1027 pasteParagraphList(cur, buffer.paragraphs(),
1028 buffer.params().documentClassPtr(), errorList);
1034 // Then try plain text
1035 docstring const text = theClipboard().getAsText();
1040 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1042 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1046 void pasteSimpleText(Cursor & cur, bool asParagraphs)
1049 // Use internal clipboard if it is the most recent one
1050 if (theClipboard().isInternal()) {
1051 if (!checkPastePossible(0))
1054 ParagraphList const & pars = theCuts[0].first;
1055 ParagraphList::const_iterator it = pars.begin();
1056 for (; it != pars.end(); ++it) {
1057 if (it != pars.begin())
1059 text += (*it).asString();
1061 asParagraphs = false;
1063 // Then try plain text
1064 text = theClipboard().getAsText();
1071 cutSelection(cur, true, false);
1073 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1075 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1079 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
1080 Clipboard::GraphicsType preferedType)
1082 LASSERT(theClipboard().hasGraphicsContents(preferedType), /**/);
1084 // get picture from clipboard
1085 FileName filename = theClipboard().getAsGraphics(cur, preferedType);
1086 if (filename.empty())
1089 // create inset for graphic
1090 InsetGraphics * inset = new InsetGraphics(cur.buffer());
1091 InsetGraphicsParams params;
1092 params.filename = support::DocFileName(filename.absFileName(), false);
1093 inset->setParams(params);
1099 void pasteSelection(Cursor & cur, ErrorList & errorList)
1101 if (selectionBuffer.empty())
1104 pasteParagraphList(cur, selectionBuffer[0].first,
1105 selectionBuffer[0].second, errorList);
1109 void replaceSelectionWithString(Cursor & cur, docstring const & str)
1112 DocIterator selbeg = cur.selectionBegin();
1114 // Get font setting before we cut, we need a copy here, not a bare reference.
1116 selbeg.paragraph().getFontSettings(cur.buffer()->params(), selbeg.pos());
1118 // Insert the new string
1119 pos_type pos = cur.selEnd().pos();
1120 Paragraph & par = cur.selEnd().paragraph();
1121 docstring::const_iterator cit = str.begin();
1122 docstring::const_iterator end = str.end();
1123 for (; cit != end; ++cit, ++pos)
1124 par.insertChar(pos, *cit, font, cur.buffer()->params().trackChanges);
1126 // Cut the selection
1127 cutSelection(cur, true, false);
1131 void replaceSelection(Cursor & cur)
1133 if (cur.selection())
1134 cutSelection(cur, true, false);
1138 void eraseSelection(Cursor & cur)
1140 //lyxerr << "cap::eraseSelection begin: " << cur << endl;
1141 CursorSlice const & i1 = cur.selBegin();
1142 CursorSlice const & i2 = cur.selEnd();
1143 if (i1.inset().asInsetMath()) {
1146 if (i1.idx() == i2.idx()) {
1147 i1.cell().erase(i1.pos(), i2.pos());
1148 // We may have deleted i1.cell(cur.pos()).
1149 // Make sure that pos is valid.
1150 if (cur.pos() > cur.lastpos())
1151 cur.pos() = cur.lastpos();
1153 InsetMath * p = i1.asInsetMath();
1154 Inset::row_type r1, r2;
1155 Inset::col_type c1, c2;
1156 region(i1, i2, r1, r2, c1, c2);
1157 for (Inset::row_type row = r1; row <= r2; ++row)
1158 for (Inset::col_type col = c1; col <= c2; ++col)
1159 p->cell(p->index(row, col)).clear();
1160 // We've deleted the whole cell. Only pos 0 is valid.
1163 // need a valid cursor. (Lgb)
1164 cur.clearSelection();
1166 lyxerr << "can't erase this selection 1" << endl;
1168 //lyxerr << "cap::eraseSelection end: " << cur << endl;
1172 void selDel(Cursor & cur)
1174 //lyxerr << "cap::selDel" << endl;
1175 if (cur.selection())
1176 eraseSelection(cur);
1180 void selClearOrDel(Cursor & cur)
1182 //lyxerr << "cap::selClearOrDel" << endl;
1183 if (lyxrc.auto_region_delete)
1186 cur.setSelection(false);
1190 docstring grabSelection(Cursor const & cur)
1192 if (!cur.selection())
1196 // grab selection by glueing multiple cells together. This is not what
1197 // we want because selections spanning multiple cells will get "&" and "\\"
1200 for (DocIterator dit = cur.selectionBegin();
1201 dit != cur.selectionEnd(); dit.forwardPos())
1202 os << asString(dit.cell());
1206 CursorSlice i1 = cur.selBegin();
1207 CursorSlice i2 = cur.selEnd();
1209 if (i1.idx() == i2.idx()) {
1210 if (i1.inset().asInsetMath()) {
1211 MathData::const_iterator it = i1.cell().begin();
1212 Buffer * buf = cur.buffer();
1213 return asString(MathData(buf, it + i1.pos(), it + i2.pos()));
1215 return from_ascii("unknown selection 1");
1219 Inset::row_type r1, r2;
1220 Inset::col_type c1, c2;
1221 region(i1, i2, r1, r2, c1, c2);
1224 if (i1.inset().asInsetMath()) {
1225 for (Inset::row_type row = r1; row <= r2; ++row) {
1228 for (Inset::col_type col = c1; col <= c2; ++col) {
1231 data += asString(i1.asInsetMath()->
1232 cell(i1.asInsetMath()->index(row, col)));
1236 data = from_ascii("unknown selection 2");
1242 void dirtyTabularStack(bool b)
1244 dirty_tabular_stack_ = b;
1248 bool tabularStackDirty()
1250 return dirty_tabular_stack_;