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"
40 #include "insets/InsetBranch.h"
41 #include "insets/InsetCommand.h"
42 #include "insets/InsetFlex.h"
43 #include "insets/InsetGraphics.h"
44 #include "insets/InsetGraphicsParams.h"
45 #include "insets/InsetInclude.h"
46 #include "insets/InsetLabel.h"
47 #include "insets/InsetTabular.h"
49 #include "mathed/MathData.h"
50 #include "mathed/InsetMath.h"
51 #include "mathed/InsetMathHull.h"
52 #include "mathed/InsetMathRef.h"
53 #include "mathed/MathSupport.h"
55 #include "support/debug.h"
56 #include "support/docstream.h"
57 #include "support/gettext.h"
58 #include "support/limited_stack.h"
59 #include "support/lstrings.h"
61 #include "frontends/alert.h"
62 #include "frontends/Clipboard.h"
63 #include "frontends/Selection.h"
65 #include <boost/tuple/tuple.hpp>
66 #include <boost/next_prior.hpp>
71 using namespace lyx::support;
72 using lyx::frontend::Clipboard;
78 typedef pair<pit_type, int> PitPosPair;
80 typedef limited_stack<pair<ParagraphList, DocumentClass const *> > CutStack;
83 // persistent selection, cleared until the next selection
84 CutStack selectionBuffer(1);
86 // store whether the tabular stack is newer than the normal copy stack
87 // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
88 // when we (hopefully) have a one-for-all paste mechanism.
89 bool dirty_tabular_stack_ = false;
92 bool checkPastePossible(int index)
94 return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
98 pair<PitPosPair, pit_type>
99 pasteSelectionHelper(Cursor & cur, ParagraphList const & parlist,
100 DocumentClass const * const oldDocClass, ErrorList & errorlist)
102 Buffer const & buffer = *cur.buffer();
103 pit_type pit = cur.pit();
104 pos_type pos = cur.pos();
105 InsetText * target_inset = cur.inset().asInsetText();
107 InsetTabular * it = cur.inset().asInsetTabular();
108 target_inset = it? it->cell(cur.idx())->asInsetText() : 0;
110 LASSERT(target_inset, return make_pair(PitPosPair(pit, pos), pit));
111 ParagraphList & pars = target_inset->paragraphs();
114 return make_pair(PitPosPair(pit, pos), pit);
116 BOOST_ASSERT (pos <= pars[pit].size());
118 // Make a copy of the CaP paragraphs.
119 ParagraphList insertion = parlist;
120 DocumentClass const * const newDocClass =
121 buffer.params().documentClassPtr();
123 // Now remove all out of the pars which is NOT allowed in the
124 // new environment and set also another font if that is required.
126 // Convert newline to paragraph break in ERT inset.
127 // This should not be here!
128 InsetCode const code = target_inset->lyxCode();
129 if (code == ERT_CODE || code == LISTINGS_CODE) {
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, e.g., InsetLabel::updateCommand() is 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 = static_cast<InsetMathHull &>(*it);
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->updateCommand(oldname, false);
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) {
255 static_cast<InsetCommand &>(*itt);
256 if (ref.getParam("reference") == oldname)
257 ref.setParam("reference", newname);
258 } else if (itt->lyxCode() == MATH_REF_CODE) {
260 static_cast<InsetMathHull &>(*itt);
261 // this is necessary to prevent an uninitialized
262 // buffer when the RefInset is in a MathBox.
263 // FIXME audit setBuffer calls
264 mi.setBuffer(const_cast<Buffer &>(buffer));
265 if (mi.asRefInset()->getTarget() == oldname)
266 mi.asRefInset()->changeTarget(newname);
274 // check for duplicates
275 InsetCommand & lab = static_cast<InsetCommand &>(*it);
276 docstring const oldname = lab.getParam("name");
277 lab.updateCommand(oldname, false);
278 // We need to update the buffer reference cache.
279 cur.forceBufferUpdate();
280 docstring const newname = lab.getParam("name");
281 if (oldname == newname)
283 // adapt the references
284 for (InsetIterator itt = inset_iterator_begin(in); itt != i_end; ++itt) {
285 if (itt->lyxCode() == REF_CODE) {
286 InsetCommand & ref = static_cast<InsetCommand &>(*itt);
287 if (ref.getParam("reference") == oldname)
288 ref.setParam("reference", newname);
289 } else if (itt->lyxCode() == MATH_REF_CODE) {
291 static_cast<InsetMathHull &>(*itt);
292 // this is necessary to prevent an uninitialized
293 // buffer when the RefInset is in a MathBox.
294 // FIXME audit setBuffer calls
295 mi.setBuffer(const_cast<Buffer &>(buffer));
296 if (mi.asRefInset()->getTarget() == oldname)
297 mi.asRefInset()->changeTarget(newname);
304 InsetInclude & inc = static_cast<InsetInclude &>(*it);
306 // We need to update the list of included files.
307 cur.forceBufferUpdate();
312 // check for duplicates
313 InsetCommand & bib = static_cast<InsetCommand &>(*it);
314 docstring const oldkey = bib.getParam("key");
315 bib.updateCommand(oldkey, false);
316 // We need to update the buffer reference cache.
317 cur.forceBufferUpdate();
318 docstring const newkey = bib.getParam("key");
319 if (oldkey == newkey)
321 // adapt the references
322 for (InsetIterator itt = inset_iterator_begin(in);
323 itt != i_end; ++itt) {
324 if (itt->lyxCode() == CITE_CODE) {
326 static_cast<InsetCommand &>(*itt);
327 if (ref.getParam("key") == oldkey)
328 ref.setParam("key", newkey);
335 // check if branch is known to target buffer
337 InsetBranch & br = static_cast<InsetBranch &>(*it);
338 docstring const name = br.branch();
341 bool const is_child = (&buffer != buffer.masterBuffer());
342 BranchList branchlist = buffer.params().branchlist();
343 if ((!is_child && branchlist.find(name))
344 || (is_child && (branchlist.find(name)
345 || buffer.masterBuffer()->params().branchlist().find(name))))
347 // FIXME: add an option to add the branch to the master's BranchList.
348 docstring text = bformat(
349 _("The pasted branch \"%1$s\" is undefined.\n"
350 "Do you want to add it to the document's branch list?"),
352 if (frontend::Alert::prompt(_("Unknown branch"),
353 text, 0, 1, _("&Add"), _("&Don't Add")) != 0)
355 lyx::dispatch(FuncRequest(LFUN_BRANCH_ADD, name));
356 // We need to update the list of branches.
357 cur.forceBufferUpdate();
365 insertion.swap(in.paragraphs());
367 // Split the paragraph for inserting the buf if necessary.
369 breakParagraphConservative(buffer.params(), pars, pit, pos);
373 pars.insert(boost::next(pars.begin(), pit),
377 // merge the empty par with the last par of the insertion
378 mergeParagraph(buffer.params(), pars,
379 pit + insertion.size() - 1);
381 pars.insert(boost::next(pars.begin(), pit + 1),
385 // merge the first par of the insertion with the current par
386 mergeParagraph(buffer.params(), pars, pit);
389 // Store the new cursor position.
390 pit_type last_paste = pit + insertion.size() - 1;
391 pit_type startpit = pit;
393 pos = pars[last_paste].size();
395 // FIXME Should we do it here, or should we let updateBuffer() do it?
396 // Set paragraph buffers. It's important to do this right away
397 // before something calls Inset::buffer() and causes a crash.
398 for (pit_type p = startpit; p <= pit; ++p)
399 pars[p].setBuffer(const_cast<Buffer &>(buffer));
401 // Join (conditionally) last pasted paragraph with next one, i.e.,
402 // the tail of the spliced document paragraph
403 if (!empty && last_paste + 1 != pit_type(pars.size())) {
404 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
405 mergeParagraph(buffer.params(), pars, last_paste);
406 } else if (pars[last_paste + 1].empty()) {
407 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
408 mergeParagraph(buffer.params(), pars, last_paste);
409 } else if (pars[last_paste].empty()) {
410 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
411 mergeParagraph(buffer.params(), pars, last_paste);
413 pars[last_paste + 1].stripLeadingSpaces(buffer.params().trackChanges);
418 return make_pair(PitPosPair(pit, pos), last_paste + 1);
422 PitPosPair eraseSelectionHelper(BufferParams const & params,
423 ParagraphList & pars,
424 pit_type startpit, pit_type endpit,
425 int startpos, int endpos)
427 // Start of selection is really invalid.
428 if (startpit == pit_type(pars.size()) ||
429 (startpos > pars[startpit].size()))
430 return PitPosPair(endpit, endpos);
432 // Start and end is inside same paragraph
433 if (endpit == pit_type(pars.size()) || startpit == endpit) {
434 endpos -= pars[startpit].eraseChars(startpos, endpos, params.trackChanges);
435 return PitPosPair(endpit, endpos);
438 for (pit_type pit = startpit; pit != endpit + 1;) {
439 pos_type const left = (pit == startpit ? startpos : 0);
440 pos_type right = (pit == endpit ? endpos : pars[pit].size() + 1);
441 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.trackChanges);
443 // Logically erase only, including the end-of-paragraph character
444 pars[pit].eraseChars(left, right, params.trackChanges);
446 // Separate handling of paragraph break:
447 if (merge && pit != endpit &&
449 || pars[pit].hasSameLayout(pars[endpit])
450 || pars[endpit].size() == endpos)) {
451 if (pit + 1 == endpit)
452 endpos += pars[pit].size();
453 mergeParagraph(params, pars, pit);
459 // Ensure legal cursor pos:
462 return PitPosPair(endpit, endpos);
466 void putClipboard(ParagraphList const & paragraphs,
467 DocumentClass const * const docclass, docstring const & plaintext)
469 // For some strange reason gcc 3.2 and 3.3 do not accept
470 // Buffer buffer(string(), false);
471 // This needs to be static to avoid a memory leak. When a Buffer is
472 // constructed, it constructs a BufferParams, which in turn constructs
473 // a DocumentClass, via new, that is never deleted. If we were to go to
474 // some kind of garbage collection there, or a shared_ptr, then this
475 // would not be needed.
476 static Buffer * buffer = theBufferList().newBuffer(
477 FileName::tempName().absFileName() + "_clipboard.internal");
478 buffer->setUnnamed(true);
479 buffer->paragraphs() = paragraphs;
480 buffer->inset().setBuffer(*buffer);
481 buffer->params().setDocumentClass(docclass);
483 if (buffer->write(lyx))
484 theClipboard().put(lyx.str(), plaintext);
486 theClipboard().put(string(), plaintext);
488 buffer->paragraphs().clear();
492 /// return true if the whole ParagraphList is deleted
493 static bool isFullyDeleted(ParagraphList const & pars)
495 pit_type const pars_size = static_cast<pit_type>(pars.size());
497 // check all paragraphs
498 for (pit_type pit = 0; pit < pars_size; ++pit) {
499 if (!pars[pit].empty()) // prevent assertion failure
500 if (!pars[pit].isDeleted(0, pars[pit].size()))
507 void copySelectionHelper(Buffer const & buf, Text const & text,
508 pit_type startpit, pit_type endpit,
509 int start, int end, DocumentClass const * const dc, CutStack & cutstack)
511 ParagraphList const & pars = text.paragraphs();
513 LASSERT(0 <= start && start <= pars[startpit].size(), /**/);
514 LASSERT(0 <= end && end <= pars[endpit].size(), /**/);
515 LASSERT(startpit != endpit || start <= end, /**/);
517 // Clone the paragraphs within the selection.
518 ParagraphList copy_pars(boost::next(pars.begin(), startpit),
519 boost::next(pars.begin(), endpit + 1));
521 // Remove the end of the last paragraph; afterwards, remove the
522 // beginning of the first paragraph. Keep this order - there may only
523 // be one paragraph! Do not track deletions here; this is an internal
524 // action not visible to the user
526 Paragraph & back = copy_pars.back();
527 back.eraseChars(end, back.size(), false);
528 Paragraph & front = copy_pars.front();
529 front.eraseChars(0, start, false);
531 ParagraphList::iterator it = copy_pars.begin();
532 ParagraphList::iterator it_end = copy_pars.end();
534 for (; it != it_end; it++) {
535 // Since we have a copy of the paragraphs, the insets
536 // do not have a proper buffer reference. It makes
537 // sense to add them temporarily, because the
538 // operations below depend on that (acceptChanges included).
539 it->setBuffer(const_cast<Buffer &>(buf));
540 // PassThru paragraphs have the Language
541 // latex_language. This is invalid for others, so we
542 // need to change it to the buffer language.
543 if (text.inset().getLayout().isPassThru())
544 it->changeLanguage(buf.params(),
545 latex_language, buf.language());
548 // do not copy text (also nested in insets) which is marked as
549 // deleted, unless the whole selection was deleted
550 if (!isFullyDeleted(copy_pars))
551 acceptChanges(copy_pars, buf.params());
553 rejectChanges(copy_pars, buf.params());
556 // do some final cleanup now, to make sure that the paragraphs
557 // are not linked to something else.
558 it = copy_pars.begin();
559 for (; it != it_end; it++) {
560 it->setBuffer(*static_cast<Buffer *>(0));
561 it->setInsetOwner(0);
564 DocumentClass * d = const_cast<DocumentClass *>(dc);
565 cutstack.push(make_pair(copy_pars, d));
575 void region(CursorSlice const & i1, CursorSlice const & i2,
576 Inset::row_type & r1, Inset::row_type & r2,
577 Inset::col_type & c1, Inset::col_type & c2)
579 Inset & p = i1.inset();
580 c1 = p.col(i1.idx());
581 c2 = p.col(i2.idx());
584 r1 = p.row(i1.idx());
585 r2 = p.row(i2.idx());
591 docstring grabAndEraseSelection(Cursor & cur)
593 if (!cur.selection())
595 docstring res = grabSelection(cur);
601 bool reduceSelectionToOneCell(Cursor & cur)
603 if (!cur.selection() || !cur.inMathed())
606 CursorSlice i1 = cur.selBegin();
607 CursorSlice i2 = cur.selEnd();
608 if (!i1.inset().asInsetMath())
611 // the easy case: do nothing if only one cell is selected
612 if (i1.idx() == i2.idx())
617 cur.top().pos() = cur.top().lastpos();
623 bool multipleCellsSelected(Cursor const & cur)
625 if (!cur.selection() || !cur.inMathed())
628 CursorSlice i1 = cur.selBegin();
629 CursorSlice i2 = cur.selEnd();
630 if (!i1.inset().asInsetMath())
633 if (i1.idx() == i2.idx())
640 void switchBetweenClasses(DocumentClass const * const oldone,
641 DocumentClass const * const newone, InsetText & in, ErrorList & errorlist)
645 LASSERT(!in.paragraphs().empty(), /**/);
646 if (oldone == newone)
649 DocumentClass const & oldtc = *oldone;
650 DocumentClass const & newtc = *newone;
653 ParIterator end = par_iterator_end(in);
654 for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
655 docstring const name = it->layout().name();
657 // the pasted text will keep their own layout name. If this layout does
658 // not exist in the new document, it will behave like a standard layout.
659 newtc.addLayoutIfNeeded(name);
661 if (in.usePlainLayout())
662 it->setLayout(newtc.plainLayout());
664 it->setLayout(newtc[name]);
668 InsetIterator const i_end = inset_iterator_end(in);
669 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
670 if (it->lyxCode() != FLEX_CODE)
671 // FIXME: Should we verify all InsetCollapsable?
673 docstring const & n = newone->insetLayout(it->name()).name();
674 bool const is_undefined = n.empty() ||
675 n == DocumentClass::plainInsetLayout().name();
678 // The flex inset is undefined in newtc
679 docstring const s = bformat(_(
680 "Flex inset %1$s is "
681 "undefined because of class "
682 "conversion from\n%2$s to %3$s"),
683 it->name(), from_utf8(oldtc.name()),
684 from_utf8(newtc.name()));
685 // To warn the user that something had to be done.
686 errorlist.push_back(ErrorItem(
687 _("Undefined flex inset"),
688 s, it.paragraph().id(), it.pos(), it.pos() + 1));
693 vector<docstring> availableSelections(Buffer const * buf)
695 vector<docstring> selList;
699 CutStack::const_iterator cit = theCuts.begin();
700 CutStack::const_iterator end = theCuts.end();
701 for (; cit != end; ++cit) {
702 // we do not use cit-> here because gcc 2.9x does not
704 ParagraphList const & pars = (*cit).first;
706 ParagraphList::const_iterator pit = pars.begin();
707 ParagraphList::const_iterator pend = pars.end();
708 for (; pit != pend; ++pit) {
709 Paragraph par(*pit, 0, 26);
710 // adapt paragraph to current buffer.
711 par.setBuffer(const_cast<Buffer &>(*buf));
712 asciiSel += par.asString(AS_STR_INSETS);
713 if (asciiSel.size() > 25) {
714 asciiSel.replace(22, docstring::npos,
720 selList.push_back(asciiSel);
727 size_type numberOfSelections()
729 return theCuts.size();
733 void cutSelection(Cursor & cur, bool doclear, bool realcut)
735 // This doesn't make sense, if there is no selection
736 if (!cur.selection())
739 // OK, we have a selection. This is always between cur.selBegin()
742 if (cur.inTexted()) {
743 Text * text = cur.text();
748 // make sure that the depth behind the selection are restored, too
749 cur.recordUndoSelection();
750 pit_type begpit = cur.selBegin().pit();
751 pit_type endpit = cur.selEnd().pit();
753 int endpos = cur.selEnd().pos();
755 BufferParams const & bp = cur.buffer()->params();
757 copySelectionHelper(*cur.buffer(),
760 cur.selBegin().pos(), endpos,
761 bp.documentClassPtr(), theCuts);
762 // Stuff what we got on the clipboard.
763 // Even if there is no selection.
764 putClipboard(theCuts[0].first, theCuts[0].second,
765 cur.selectionAsString(true));
768 if (begpit != endpit)
769 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
771 boost::tie(endpit, endpos) =
772 eraseSelectionHelper(bp,
775 cur.selBegin().pos(), endpos);
777 // cutSelection can invalidate the cursor so we need to set
779 // we prefer the end for when tracking changes
783 // sometimes necessary
785 && text->paragraphs()[begpit].stripLeadingSpaces(bp.trackChanges))
788 // need a valid cursor. (Lgb)
789 cur.clearSelection();
790 cur.forceBufferUpdate();
792 // tell tabular that a recent copy happened
793 dirtyTabularStack(false);
796 if (cur.inMathed()) {
797 if (cur.selBegin().idx() != cur.selEnd().idx()) {
798 // The current selection spans more than one cell.
800 cur.recordUndoInset();
802 // Record only the current cell to avoid a jumping
813 void copySelection(Cursor const & cur)
815 copySelection(cur, cur.selectionAsString(true));
819 void copyInset(Cursor const & cur, Inset * inset, docstring const & plaintext)
823 BufferParams const & bp = cur.buffer()->params();
824 par.setLayout(bp.documentClass().plainLayout());
825 par.insertInset(0, inset, Change(Change::UNCHANGED));
827 theCuts.push(make_pair(pars, bp.documentClassPtr()));
829 // stuff the selection onto the X clipboard, from an explicit copy request
830 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
835 void copySelectionToStack(Cursor const & cur, CutStack & cutstack)
837 // this doesn't make sense, if there is no selection
838 if (!cur.selection())
841 // copySelection can not yet handle the case of cross idx selection
842 if (cur.selBegin().idx() != cur.selEnd().idx())
845 if (cur.inTexted()) {
846 Text * text = cur.text();
848 // ok we have a selection. This is always between cur.selBegin()
849 // and sel_end cursor
851 // copy behind a space if there is one
852 ParagraphList & pars = text->paragraphs();
853 pos_type pos = cur.selBegin().pos();
854 pit_type par = cur.selBegin().pit();
855 while (pos < pars[par].size() &&
856 pars[par].isLineSeparator(pos) &&
857 (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
860 copySelectionHelper(*cur.buffer(), *text, par, cur.selEnd().pit(),
861 pos, cur.selEnd().pos(),
862 cur.buffer()->params().documentClassPtr(), cutstack);
864 // Reset the dirty_tabular_stack_ flag only when something
865 // is copied to the clipboard (not to the selectionBuffer).
866 if (&cutstack == &theCuts)
867 dirtyTabularStack(false);
870 if (cur.inMathed()) {
871 //lyxerr << "copySelection in mathed" << endl;
874 BufferParams const & bp = cur.buffer()->params();
875 // FIXME This should be the plain layout...right?
876 par.setLayout(bp.documentClass().plainLayout());
877 par.insert(0, grabSelection(cur), Font(), Change(Change::UNCHANGED));
879 cutstack.push(make_pair(pars, bp.documentClassPtr()));
886 void copySelectionToStack()
888 if (!selectionBuffer.empty())
889 theCuts.push(selectionBuffer[0]);
893 void copySelection(Cursor const & cur, docstring const & plaintext)
895 // In tablemode, because copy and paste actually use special table stack
896 // we do not attempt to get selected paragraphs under cursor. Instead, a
897 // paragraph with the plain text version is generated so that table cells
898 // can be pasted as pure text somewhere else.
899 if (cur.selBegin().idx() != cur.selEnd().idx()) {
902 BufferParams const & bp = cur.buffer()->params();
903 par.setLayout(bp.documentClass().plainLayout());
904 par.insert(0, plaintext, Font(), Change(Change::UNCHANGED));
906 theCuts.push(make_pair(pars, bp.documentClassPtr()));
908 copySelectionToStack(cur, theCuts);
911 // stuff the selection onto the X clipboard, from an explicit copy request
912 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
916 void saveSelection(Cursor const & cur)
918 // This function is called, not when a selection is formed, but when
919 // a selection is cleared. Therefore, multiple keyboard selection
920 // will not repeatively trigger this function (bug 3877).
922 && cur.selBegin() == cur.bv().cursor().selBegin()
923 && cur.selEnd() == cur.bv().cursor().selEnd()) {
924 LYXERR(Debug::SELECTION, "saveSelection: '" << cur.selectionAsString(true) << "'");
925 copySelectionToStack(cur, selectionBuffer);
932 return !selectionBuffer.empty();
936 void clearSelection()
938 selectionBuffer.clear();
948 docstring selection(size_t sel_index)
950 return sel_index < theCuts.size()
951 ? theCuts[sel_index].first.back().asString(AS_STR_INSETS | AS_STR_NEWLINES)
956 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
957 DocumentClass const * const docclass, ErrorList & errorList)
959 if (cur.inTexted()) {
960 Text * text = cur.text();
966 boost::tie(ppp, endpit) =
967 pasteSelectionHelper(cur, parlist, docclass, errorList);
968 cur.forceBufferUpdate();
969 cur.clearSelection();
970 text->setCursor(cur, ppp.first, ppp.second);
973 // mathed is handled in InsetMathNest/InsetMathGrid
974 LASSERT(!cur.inMathed(), /**/);
978 void pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
980 // this does not make sense, if there is nothing to paste
981 if (!checkPastePossible(sel_index))
985 pasteParagraphList(cur, theCuts[sel_index].first,
986 theCuts[sel_index].second, errorList);
991 void pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs)
993 // Use internal clipboard if it is the most recent one
994 if (theClipboard().isInternal()) {
995 pasteFromStack(cur, errorList, 0);
999 // First try LyX format
1000 if (theClipboard().hasLyXContents()) {
1001 string lyx = theClipboard().getAsLyX();
1003 // For some strange reason gcc 3.2 and 3.3 do not accept
1004 // Buffer buffer(string(), false);
1005 Buffer buffer("", false);
1006 buffer.setUnnamed(true);
1007 if (buffer.readString(lyx)) {
1009 pasteParagraphList(cur, buffer.paragraphs(),
1010 buffer.params().documentClassPtr(), errorList);
1017 // Then try plain text
1018 docstring const text = theClipboard().getAsText();
1023 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1025 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1029 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
1030 Clipboard::GraphicsType preferedType)
1032 LASSERT(theClipboard().hasGraphicsContents(preferedType), /**/);
1034 // get picture from clipboard
1035 FileName filename = theClipboard().getAsGraphics(cur, preferedType);
1036 if (filename.empty())
1039 // create inset for graphic
1040 InsetGraphics * inset = new InsetGraphics(cur.buffer());
1041 InsetGraphicsParams params;
1042 params.filename = support::DocFileName(filename.absFileName());
1043 inset->setParams(params);
1049 void pasteSelection(Cursor & cur, ErrorList & errorList)
1051 if (selectionBuffer.empty())
1054 pasteParagraphList(cur, selectionBuffer[0].first,
1055 selectionBuffer[0].second, errorList);
1059 void replaceSelectionWithString(Cursor & cur, docstring const & str, bool backwards)
1062 DocIterator selbeg = cur.selectionBegin();
1064 // Get font setting before we cut, we need a copy here, not a bare reference.
1066 selbeg.paragraph().getFontSettings(cur.buffer()->params(), selbeg.pos());
1068 // Insert the new string
1069 pos_type pos = cur.selEnd().pos();
1070 Paragraph & par = cur.selEnd().paragraph();
1071 docstring::const_iterator cit = str.begin();
1072 docstring::const_iterator end = str.end();
1073 for (; cit != end; ++cit, ++pos)
1074 par.insertChar(pos, *cit, font, cur.buffer()->params().trackChanges);
1076 // Cut the selection
1077 cutSelection(cur, true, false);
1079 // select the replacement
1081 selbeg.pos() += str.length();
1082 cur.setSelection(selbeg, -int(str.length()));
1084 cur.setSelection(selbeg, str.length());
1088 void replaceSelection(Cursor & cur)
1090 if (cur.selection())
1091 cutSelection(cur, true, false);
1095 void eraseSelection(Cursor & cur)
1097 //lyxerr << "cap::eraseSelection begin: " << cur << endl;
1098 CursorSlice const & i1 = cur.selBegin();
1099 CursorSlice const & i2 = cur.selEnd();
1100 if (i1.inset().asInsetMath()) {
1103 if (i1.idx() == i2.idx()) {
1104 i1.cell().erase(i1.pos(), i2.pos());
1105 // We may have deleted i1.cell(cur.pos()).
1106 // Make sure that pos is valid.
1107 if (cur.pos() > cur.lastpos())
1108 cur.pos() = cur.lastpos();
1110 InsetMath * p = i1.asInsetMath();
1111 Inset::row_type r1, r2;
1112 Inset::col_type c1, c2;
1113 region(i1, i2, r1, r2, c1, c2);
1114 for (Inset::row_type row = r1; row <= r2; ++row)
1115 for (Inset::col_type col = c1; col <= c2; ++col)
1116 p->cell(p->index(row, col)).clear();
1117 // We've deleted the whole cell. Only pos 0 is valid.
1120 // need a valid cursor. (Lgb)
1121 cur.clearSelection();
1123 lyxerr << "can't erase this selection 1" << endl;
1125 //lyxerr << "cap::eraseSelection end: " << cur << endl;
1129 void selDel(Cursor & cur)
1131 //lyxerr << "cap::selDel" << endl;
1132 if (cur.selection())
1133 eraseSelection(cur);
1137 void selClearOrDel(Cursor & cur)
1139 //lyxerr << "cap::selClearOrDel" << endl;
1140 if (lyxrc.auto_region_delete)
1143 cur.setSelection(false);
1147 docstring grabSelection(Cursor const & cur)
1149 if (!cur.selection())
1153 // grab selection by glueing multiple cells together. This is not what
1154 // we want because selections spanning multiple cells will get "&" and "\\"
1157 for (DocIterator dit = cur.selectionBegin();
1158 dit != cur.selectionEnd(); dit.forwardPos())
1159 os << asString(dit.cell());
1163 CursorSlice i1 = cur.selBegin();
1164 CursorSlice i2 = cur.selEnd();
1166 if (i1.idx() == i2.idx()) {
1167 if (i1.inset().asInsetMath()) {
1168 MathData::const_iterator it = i1.cell().begin();
1169 Buffer * buf = cur.buffer();
1170 return asString(MathData(buf, it + i1.pos(), it + i2.pos()));
1172 return from_ascii("unknown selection 1");
1176 Inset::row_type r1, r2;
1177 Inset::col_type c1, c2;
1178 region(i1, i2, r1, r2, c1, c2);
1181 if (i1.inset().asInsetMath()) {
1182 for (Inset::row_type row = r1; row <= r2; ++row) {
1185 for (Inset::col_type col = c1; col <= c2; ++col) {
1188 data += asString(i1.asInsetMath()->
1189 cell(i1.asInsetMath()->index(row, col)));
1193 data = from_ascii("unknown selection 2");
1199 void dirtyTabularStack(bool b)
1201 dirty_tabular_stack_ = b;
1205 bool tabularStackDirty()
1207 return dirty_tabular_stack_;