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"
39 #include "insets/InsetBranch.h"
40 #include "insets/InsetCommand.h"
41 #include "insets/InsetFlex.h"
42 #include "insets/InsetGraphics.h"
43 #include "insets/InsetGraphicsParams.h"
44 #include "insets/InsetInclude.h"
45 #include "insets/InsetLabel.h"
46 #include "insets/InsetTabular.h"
48 #include "mathed/MathData.h"
49 #include "mathed/InsetMath.h"
50 #include "mathed/InsetMathHull.h"
51 #include "mathed/InsetMathRef.h"
52 #include "mathed/MathSupport.h"
54 #include "support/debug.h"
55 #include "support/docstream.h"
56 #include "support/gettext.h"
57 #include "support/limited_stack.h"
58 #include "support/lstrings.h"
60 #include "frontends/alert.h"
61 #include "frontends/Clipboard.h"
62 #include "frontends/Selection.h"
64 #include <boost/tuple/tuple.hpp>
65 #include <boost/next_prior.hpp>
70 using namespace lyx::support;
71 using lyx::frontend::Clipboard;
77 typedef pair<pit_type, int> PitPosPair;
79 typedef limited_stack<pair<ParagraphList, DocumentClass const *> > CutStack;
82 // persistent selection, cleared until the next selection
83 CutStack selectionBuffer(1);
85 // store whether the tabular stack is newer than the normal copy stack
86 // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
87 // when we (hopefully) have a one-for-all paste mechanism.
88 bool dirty_tabular_stack_ = false;
91 bool checkPastePossible(int index)
93 return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
97 pair<PitPosPair, pit_type>
98 pasteSelectionHelper(Cursor & cur, ParagraphList const & parlist,
99 DocumentClass const * const oldDocClass, ErrorList & errorlist)
101 Buffer const & buffer = *cur.buffer();
102 pit_type pit = cur.pit();
103 pos_type pos = cur.pos();
104 InsetText * target_inset = cur.inset().asInsetText();
106 InsetTabular * it = cur.inset().asInsetTabular();
107 target_inset = it? it->cell(cur.idx())->asInsetText() : 0;
109 LASSERT(target_inset, return make_pair(PitPosPair(pit, pos), pit));
110 ParagraphList & pars = target_inset->paragraphs();
113 return make_pair(PitPosPair(pit, pos), pit);
115 BOOST_ASSERT (pos <= pars[pit].size());
117 // Make a copy of the CaP paragraphs.
118 ParagraphList insertion = parlist;
119 DocumentClass const * const newDocClass =
120 buffer.params().documentClassPtr();
122 // Now remove all out of the pars which is NOT allowed in the
123 // new environment and set also another font if that is required.
125 // Convert newline to paragraph break in ERT inset.
126 // This should not be here!
127 InsetCode const code = target_inset->lyxCode();
128 if (code == ERT_CODE || code == LISTINGS_CODE) {
129 for (size_t i = 0; i != insertion.size(); ++i) {
130 for (pos_type j = 0; j != insertion[i].size(); ++j) {
131 if (insertion[i].isNewline(j)) {
132 // do not track deletion of newline
133 insertion[i].eraseChar(j, false);
134 insertion[i].setInsetOwner(target_inset);
135 breakParagraphConservative(
144 // set the paragraphs to plain layout if necessary
145 if (cur.inset().usePlainLayout()) {
146 bool forcePlainLayout = cur.inset().forcePlainLayout();
147 Layout const & plainLayout = newDocClass->plainLayout();
148 Layout const & defaultLayout = newDocClass->defaultLayout();
149 ParagraphList::iterator const end = insertion.end();
150 ParagraphList::iterator par = insertion.begin();
151 for (; par != end; ++par) {
152 Layout const & parLayout = par->layout();
153 if (forcePlainLayout || parLayout == defaultLayout)
154 par->setLayout(plainLayout);
156 } else { // check if we need to reset from plain layout
157 Layout const & defaultLayout = newDocClass->defaultLayout();
158 Layout const & plainLayout = newDocClass->plainLayout();
159 ParagraphList::iterator const end = insertion.end();
160 ParagraphList::iterator par = insertion.begin();
161 for (; par != end; ++par) {
162 Layout const & parLayout = par->layout();
163 if (parLayout == plainLayout)
164 par->setLayout(defaultLayout);
168 InsetText in(cur.buffer());
169 // Make sure there is no class difference.
170 in.paragraphs().clear();
171 // This works without copying any paragraph data because we have
172 // a specialized swap method for ParagraphList. This is important
173 // since we store pointers to insets at some places and we don't
174 // want to invalidate them.
175 insertion.swap(in.paragraphs());
176 cap::switchBetweenClasses(oldDocClass, newDocClass, in, errorlist);
177 insertion.swap(in.paragraphs());
179 ParagraphList::iterator tmpbuf = insertion.begin();
180 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
182 depth_type max_depth = pars[pit].getMaxDepthAfter();
184 for (; tmpbuf != insertion.end(); ++tmpbuf) {
185 // If we have a negative jump so that the depth would
186 // go below 0 depth then we have to redo the delta to
187 // this new max depth level so that subsequent
188 // paragraphs are aligned correctly to this paragraph
190 if (int(tmpbuf->params().depth()) + depth_delta < 0)
193 // Set the right depth so that we are not too deep or shallow.
194 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
195 if (tmpbuf->params().depth() > max_depth)
196 tmpbuf->params().depth(max_depth);
198 // Only set this from the 2nd on as the 2nd depends
199 // for maxDepth still on pit.
200 if (tmpbuf != insertion.begin())
201 max_depth = tmpbuf->getMaxDepthAfter();
203 // Set the inset owner of this paragraph.
204 tmpbuf->setInsetOwner(target_inset);
205 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
206 // do not track deletion of invalid insets
207 if (Inset * inset = tmpbuf->getInset(i))
208 if (!target_inset->insetAllowed(inset->lyxCode()))
209 tmpbuf->eraseChar(i--, false);
212 tmpbuf->setChange(Change(buffer.params().trackChanges ?
213 Change::INSERTED : Change::UNCHANGED));
216 bool const empty = pars[pit].empty();
218 // Make the buf exactly the same layout as the cursor
220 insertion.begin()->makeSameLayout(pars[pit]);
223 // Prepare the paragraphs and insets for insertion.
224 insertion.swap(in.paragraphs());
226 InsetIterator const i_end = inset_iterator_end(in);
227 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
228 // Even though this will also be done later, it has to be done here
229 // since, e.g., InsetLabel::updateCommand() is going to try to access
230 // the buffer() member.
231 it->setBuffer(const_cast<Buffer &>(buffer));
232 switch (it->lyxCode()) {
234 case MATH_HULL_CODE: {
235 // check for equation labels and resolve duplicates
236 InsetMathHull & ins = static_cast<InsetMathHull &>(*it);
237 std::vector<InsetLabel *> labels = ins.getLabels();
238 for (size_t i = 0; i != labels.size(); ++i) {
241 InsetLabel * lab = labels[i];
242 docstring const oldname = lab->getParam("name");
243 lab->updateCommand(oldname, false);
244 // We need to update the buffer reference cache.
245 cur.forceBufferUpdate();
246 docstring const newname = lab->getParam("name");
247 if (oldname == newname)
249 // adapt the references
250 for (InsetIterator itt = inset_iterator_begin(in);
251 itt != i_end; ++itt) {
252 if (itt->lyxCode() == REF_CODE) {
254 static_cast<InsetCommand &>(*itt);
255 if (ref.getParam("reference") == oldname)
256 ref.setParam("reference", newname);
257 } else if (itt->lyxCode() == MATH_REF_CODE) {
259 static_cast<InsetMathHull &>(*itt);
260 // this is necessary to prevent an uninitialized
261 // buffer when the RefInset is in a MathBox.
262 // FIXME audit setBuffer calls
263 mi.setBuffer(const_cast<Buffer &>(buffer));
264 if (mi.asRefInset()->getTarget() == oldname)
265 mi.asRefInset()->changeTarget(newname);
273 // check for duplicates
274 InsetCommand & lab = static_cast<InsetCommand &>(*it);
275 docstring const oldname = lab.getParam("name");
276 lab.updateCommand(oldname, false);
277 // We need to update the buffer reference cache.
278 cur.forceBufferUpdate();
279 docstring const newname = lab.getParam("name");
280 if (oldname == newname)
282 // adapt the references
283 for (InsetIterator itt = inset_iterator_begin(in); itt != i_end; ++itt) {
284 if (itt->lyxCode() == REF_CODE) {
285 InsetCommand & ref = static_cast<InsetCommand &>(*itt);
286 if (ref.getParam("reference") == oldname)
287 ref.setParam("reference", newname);
288 } else if (itt->lyxCode() == MATH_REF_CODE) {
290 static_cast<InsetMathHull &>(*itt);
291 // this is necessary to prevent an uninitialized
292 // buffer when the RefInset is in a MathBox.
293 // FIXME audit setBuffer calls
294 mi.setBuffer(const_cast<Buffer &>(buffer));
295 if (mi.asRefInset()->getTarget() == oldname)
296 mi.asRefInset()->changeTarget(newname);
303 InsetInclude & inc = static_cast<InsetInclude &>(*it);
305 // We need to update the list of included files.
306 cur.forceBufferUpdate();
311 // check for duplicates
312 InsetCommand & bib = static_cast<InsetCommand &>(*it);
313 docstring const oldkey = bib.getParam("key");
314 bib.updateCommand(oldkey, false);
315 // We need to update the buffer reference cache.
316 cur.forceBufferUpdate();
317 docstring const newkey = bib.getParam("key");
318 if (oldkey == newkey)
320 // adapt the references
321 for (InsetIterator itt = inset_iterator_begin(in);
322 itt != i_end; ++itt) {
323 if (itt->lyxCode() == CITE_CODE) {
325 static_cast<InsetCommand &>(*itt);
326 if (ref.getParam("key") == oldkey)
327 ref.setParam("key", newkey);
334 // check if branch is known to target buffer
336 InsetBranch & br = static_cast<InsetBranch &>(*it);
337 docstring const name = br.branch();
340 bool const is_child = (&buffer != buffer.masterBuffer());
341 BranchList branchlist = buffer.params().branchlist();
342 if ((!is_child && branchlist.find(name))
343 || (is_child && (branchlist.find(name)
344 || buffer.masterBuffer()->params().branchlist().find(name))))
346 // FIXME: add an option to add the branch to the master's BranchList.
347 docstring text = bformat(
348 _("The pasted branch \"%1$s\" is undefined.\n"
349 "Do you want to add it to the document's branch list?"),
351 if (frontend::Alert::prompt(_("Unknown branch"),
352 text, 0, 1, _("&Add"), _("&Don't Add")) != 0)
354 lyx::dispatch(FuncRequest(LFUN_BRANCH_ADD, name));
355 // We need to update the list of branches.
356 cur.forceBufferUpdate();
364 insertion.swap(in.paragraphs());
366 // Split the paragraph for inserting the buf if necessary.
368 breakParagraphConservative(buffer.params(), pars, pit, pos);
372 pars.insert(boost::next(pars.begin(), pit),
376 // merge the empty par with the last par of the insertion
377 mergeParagraph(buffer.params(), pars,
378 pit + insertion.size() - 1);
380 pars.insert(boost::next(pars.begin(), pit + 1),
384 // merge the first par of the insertion with the current par
385 mergeParagraph(buffer.params(), pars, pit);
388 // Store the new cursor position.
389 pit_type last_paste = pit + insertion.size() - 1;
390 pit_type startpit = pit;
392 pos = pars[last_paste].size();
394 // FIXME Should we do it here, or should we let updateBuffer() do it?
395 // Set paragraph buffers. It's important to do this right away
396 // before something calls Inset::buffer() and causes a crash.
397 for (pit_type p = startpit; p <= pit; ++p)
398 pars[p].setBuffer(const_cast<Buffer &>(buffer));
400 // Join (conditionally) last pasted paragraph with next one, i.e.,
401 // the tail of the spliced document paragraph
402 if (!empty && last_paste + 1 != pit_type(pars.size())) {
403 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
404 mergeParagraph(buffer.params(), pars, last_paste);
405 } else if (pars[last_paste + 1].empty()) {
406 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
407 mergeParagraph(buffer.params(), pars, last_paste);
408 } else if (pars[last_paste].empty()) {
409 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
410 mergeParagraph(buffer.params(), pars, last_paste);
412 pars[last_paste + 1].stripLeadingSpaces(buffer.params().trackChanges);
417 return make_pair(PitPosPair(pit, pos), last_paste + 1);
421 PitPosPair eraseSelectionHelper(BufferParams const & params,
422 ParagraphList & pars,
423 pit_type startpit, pit_type endpit,
424 int startpos, int endpos)
426 // Start of selection is really invalid.
427 if (startpit == pit_type(pars.size()) ||
428 (startpos > pars[startpit].size()))
429 return PitPosPair(endpit, endpos);
431 // Start and end is inside same paragraph
432 if (endpit == pit_type(pars.size()) || startpit == endpit) {
433 endpos -= pars[startpit].eraseChars(startpos, endpos, params.trackChanges);
434 return PitPosPair(endpit, endpos);
437 for (pit_type pit = startpit; pit != endpit + 1;) {
438 pos_type const left = (pit == startpit ? startpos : 0);
439 pos_type right = (pit == endpit ? endpos : pars[pit].size() + 1);
440 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.trackChanges);
442 // Logically erase only, including the end-of-paragraph character
443 pars[pit].eraseChars(left, right, params.trackChanges);
445 // Separate handling of paragraph break:
446 if (merge && pit != endpit &&
448 || pars[pit].hasSameLayout(pars[endpit])
449 || pars[endpit].size() == endpos)) {
450 if (pit + 1 == endpit)
451 endpos += pars[pit].size();
452 mergeParagraph(params, pars, pit);
458 // Ensure legal cursor pos:
461 return PitPosPair(endpit, endpos);
465 void putClipboard(ParagraphList const & paragraphs,
466 DocumentClass const * const docclass, docstring const & plaintext)
468 // For some strange reason gcc 3.2 and 3.3 do not accept
469 // Buffer buffer(string(), false);
470 // This needs to be static to avoid a memory leak. When a Buffer is
471 // constructed, it constructs a BufferParams, which in turn constructs
472 // a DocumentClass, via new, that is never deleted. If we were to go to
473 // some kind of garbage collection there, or a shared_ptr, then this
474 // would not be needed.
475 static Buffer * buffer = theBufferList().newBuffer(
476 FileName::tempName().absFileName() + "_clipboard.internal");
477 buffer->setUnnamed(true);
478 buffer->paragraphs() = paragraphs;
479 buffer->inset().setBuffer(*buffer);
480 buffer->params().setDocumentClass(docclass);
482 if (buffer->write(lyx))
483 theClipboard().put(lyx.str(), plaintext);
485 theClipboard().put(string(), plaintext);
487 buffer->paragraphs().clear();
491 /// return true if the whole ParagraphList is deleted
492 static bool isFullyDeleted(ParagraphList const & pars)
494 pit_type const pars_size = static_cast<pit_type>(pars.size());
496 // check all paragraphs
497 for (pit_type pit = 0; pit < pars_size; ++pit) {
498 if (!pars[pit].empty()) // prevent assertion failure
499 if (!pars[pit].isDeleted(0, pars[pit].size()))
506 void copySelectionHelper(Buffer const & buf, Text const & text,
507 pit_type startpit, pit_type endpit,
508 int start, int end, DocumentClass const * const dc, CutStack & cutstack)
510 ParagraphList const & pars = text.paragraphs();
512 LASSERT(0 <= start && start <= pars[startpit].size(), /**/);
513 LASSERT(0 <= end && end <= pars[endpit].size(), /**/);
514 LASSERT(startpit != endpit || start <= end, /**/);
516 // Clone the paragraphs within the selection.
517 ParagraphList copy_pars(boost::next(pars.begin(), startpit),
518 boost::next(pars.begin(), endpit + 1));
520 // Remove the end of the last paragraph; afterwards, remove the
521 // beginning of the first paragraph. Keep this order - there may only
522 // be one paragraph! Do not track deletions here; this is an internal
523 // action not visible to the user
525 Paragraph & back = copy_pars.back();
526 back.eraseChars(end, back.size(), false);
527 Paragraph & front = copy_pars.front();
528 front.eraseChars(0, start, false);
530 ParagraphList::iterator it = copy_pars.begin();
531 ParagraphList::iterator it_end = copy_pars.end();
533 for (; it != it_end; it++) {
534 // Since we have a copy of the paragraphs, the insets
535 // do not have a proper buffer reference. It makes
536 // sense to add them temporarily, because the
537 // operations below depend on that (acceptChanges included).
538 it->setBuffer(const_cast<Buffer &>(buf));
539 // PassThru paragraphs have the Language
540 // latex_language. This is invalid for others, so we
541 // need to change it to the buffer language.
542 if (text.inset().getLayout().isPassThru())
543 it->changeLanguage(buf.params(),
544 latex_language, buf.language());
547 // do not copy text (also nested in insets) which is marked as
548 // deleted, unless the whole selection was deleted
549 if (!isFullyDeleted(copy_pars))
550 acceptChanges(copy_pars, buf.params());
552 rejectChanges(copy_pars, buf.params());
555 // do some final cleanup now, to make sure that the paragraphs
556 // are not linked to something else.
557 it = copy_pars.begin();
558 for (; it != it_end; it++) {
559 it->setBuffer(*static_cast<Buffer *>(0));
560 it->setInsetOwner(0);
563 DocumentClass * d = const_cast<DocumentClass *>(dc);
564 cutstack.push(make_pair(copy_pars, d));
574 void region(CursorSlice const & i1, CursorSlice const & i2,
575 Inset::row_type & r1, Inset::row_type & r2,
576 Inset::col_type & c1, Inset::col_type & c2)
578 Inset & p = i1.inset();
579 c1 = p.col(i1.idx());
580 c2 = p.col(i2.idx());
583 r1 = p.row(i1.idx());
584 r2 = p.row(i2.idx());
590 docstring grabAndEraseSelection(Cursor & cur)
592 if (!cur.selection())
594 docstring res = grabSelection(cur);
600 bool reduceSelectionToOneCell(Cursor & cur)
602 if (!cur.selection() || !cur.inMathed())
605 CursorSlice i1 = cur.selBegin();
606 CursorSlice i2 = cur.selEnd();
607 if (!i1.inset().asInsetMath())
610 // the easy case: do nothing if only one cell is selected
611 if (i1.idx() == i2.idx())
616 cur.top().pos() = cur.top().lastpos();
622 bool multipleCellsSelected(Cursor const & cur)
624 if (!cur.selection() || !cur.inMathed())
627 CursorSlice i1 = cur.selBegin();
628 CursorSlice i2 = cur.selEnd();
629 if (!i1.inset().asInsetMath())
632 if (i1.idx() == i2.idx())
639 void switchBetweenClasses(DocumentClass const * const oldone,
640 DocumentClass const * const newone, InsetText & in, ErrorList & errorlist)
644 LASSERT(!in.paragraphs().empty(), /**/);
645 if (oldone == newone)
648 DocumentClass const & oldtc = *oldone;
649 DocumentClass const & newtc = *newone;
652 ParIterator end = par_iterator_end(in);
653 for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
654 docstring const name = it->layout().name();
656 // the pasted text will keep their own layout name. If this layout does
657 // not exist in the new document, it will behave like a standard layout.
658 newtc.addLayoutIfNeeded(name);
660 if (in.usePlainLayout())
661 it->setLayout(newtc.plainLayout());
663 it->setLayout(newtc[name]);
667 InsetIterator const i_end = inset_iterator_end(in);
668 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
669 if (it->lyxCode() != FLEX_CODE)
670 // FIXME: Should we verify all InsetCollapsable?
672 docstring const & n = newone->insetLayout(it->name()).name();
673 bool const is_undefined = n.empty() ||
674 n == DocumentClass::plainInsetLayout().name();
677 // The flex inset is undefined in newtc
678 docstring const s = bformat(_(
679 "Flex inset %1$s is "
680 "undefined because of class "
681 "conversion from\n%2$s to %3$s"),
682 it->name(), from_utf8(oldtc.name()),
683 from_utf8(newtc.name()));
684 // To warn the user that something had to be done.
685 errorlist.push_back(ErrorItem(
686 _("Undefined flex inset"),
687 s, it.paragraph().id(), it.pos(), it.pos() + 1));
692 vector<docstring> availableSelections(Buffer const * buf)
694 vector<docstring> selList;
698 CutStack::const_iterator cit = theCuts.begin();
699 CutStack::const_iterator end = theCuts.end();
700 for (; cit != end; ++cit) {
701 // we do not use cit-> here because gcc 2.9x does not
703 ParagraphList const & pars = (*cit).first;
705 ParagraphList::const_iterator pit = pars.begin();
706 ParagraphList::const_iterator pend = pars.end();
707 for (; pit != pend; ++pit) {
708 Paragraph par(*pit, 0, 26);
709 // adapt paragraph to current buffer.
710 par.setBuffer(const_cast<Buffer &>(*buf));
711 asciiSel += par.asString(AS_STR_INSETS);
712 if (asciiSel.size() > 25) {
713 asciiSel.replace(22, docstring::npos,
719 selList.push_back(asciiSel);
726 size_type numberOfSelections()
728 return theCuts.size();
732 void cutSelection(Cursor & cur, bool doclear, bool realcut)
734 // This doesn't make sense, if there is no selection
735 if (!cur.selection())
738 // OK, we have a selection. This is always between cur.selBegin()
741 if (cur.inTexted()) {
742 Text * text = cur.text();
747 // make sure that the depth behind the selection are restored, too
748 cur.recordUndoSelection();
749 pit_type begpit = cur.selBegin().pit();
750 pit_type endpit = cur.selEnd().pit();
752 int endpos = cur.selEnd().pos();
754 BufferParams const & bp = cur.buffer()->params();
756 copySelectionHelper(*cur.buffer(),
759 cur.selBegin().pos(), endpos,
760 bp.documentClassPtr(), theCuts);
761 // Stuff what we got on the clipboard.
762 // Even if there is no selection.
763 putClipboard(theCuts[0].first, theCuts[0].second,
764 cur.selectionAsString(true));
767 if (begpit != endpit)
768 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
770 boost::tie(endpit, endpos) =
771 eraseSelectionHelper(bp,
774 cur.selBegin().pos(), endpos);
776 // cutSelection can invalidate the cursor so we need to set
778 // we prefer the end for when tracking changes
782 // sometimes necessary
784 && text->paragraphs()[begpit].stripLeadingSpaces(bp.trackChanges))
787 // need a valid cursor. (Lgb)
788 cur.clearSelection();
789 cur.forceBufferUpdate();
791 // tell tabular that a recent copy happened
792 dirtyTabularStack(false);
795 if (cur.inMathed()) {
796 if (cur.selBegin().idx() != cur.selEnd().idx()) {
797 // The current selection spans more than one cell.
799 cur.recordUndoInset();
801 // Record only the current cell to avoid a jumping
812 void copySelection(Cursor const & cur)
814 copySelection(cur, cur.selectionAsString(true));
818 void copyInset(Cursor const & cur, Inset * inset, docstring const & plaintext)
822 BufferParams const & bp = cur.buffer()->params();
823 par.setLayout(bp.documentClass().plainLayout());
824 par.insertInset(0, inset, Change(Change::UNCHANGED));
826 theCuts.push(make_pair(pars, bp.documentClassPtr()));
828 // stuff the selection onto the X clipboard, from an explicit copy request
829 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
834 void copySelectionToStack(Cursor const & cur, CutStack & cutstack)
836 // this doesn't make sense, if there is no selection
837 if (!cur.selection())
840 // copySelection can not yet handle the case of cross idx selection
841 if (cur.selBegin().idx() != cur.selEnd().idx())
844 if (cur.inTexted()) {
845 Text * text = cur.text();
847 // ok we have a selection. This is always between cur.selBegin()
848 // and sel_end cursor
850 // copy behind a space if there is one
851 ParagraphList & pars = text->paragraphs();
852 pos_type pos = cur.selBegin().pos();
853 pit_type par = cur.selBegin().pit();
854 while (pos < pars[par].size() &&
855 pars[par].isLineSeparator(pos) &&
856 (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
859 copySelectionHelper(*cur.buffer(), *text, par, cur.selEnd().pit(),
860 pos, cur.selEnd().pos(),
861 cur.buffer()->params().documentClassPtr(), cutstack);
863 // Reset the dirty_tabular_stack_ flag only when something
864 // is copied to the clipboard (not to the selectionBuffer).
865 if (&cutstack == &theCuts)
866 dirtyTabularStack(false);
869 if (cur.inMathed()) {
870 //lyxerr << "copySelection in mathed" << endl;
873 BufferParams const & bp = cur.buffer()->params();
874 // FIXME This should be the plain layout...right?
875 par.setLayout(bp.documentClass().plainLayout());
876 par.insert(0, grabSelection(cur), Font(), Change(Change::UNCHANGED));
878 cutstack.push(make_pair(pars, bp.documentClassPtr()));
885 void copySelectionToStack()
887 if (!selectionBuffer.empty())
888 theCuts.push(selectionBuffer[0]);
892 void copySelection(Cursor const & cur, docstring const & plaintext)
894 // In tablemode, because copy and paste actually use special table stack
895 // we do not attempt to get selected paragraphs under cursor. Instead, a
896 // paragraph with the plain text version is generated so that table cells
897 // can be pasted as pure text somewhere else.
898 if (cur.selBegin().idx() != cur.selEnd().idx()) {
901 BufferParams const & bp = cur.buffer()->params();
902 par.setLayout(bp.documentClass().plainLayout());
903 par.insert(0, plaintext, Font(), Change(Change::UNCHANGED));
905 theCuts.push(make_pair(pars, bp.documentClassPtr()));
907 copySelectionToStack(cur, theCuts);
910 // stuff the selection onto the X clipboard, from an explicit copy request
911 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
915 void saveSelection(Cursor const & cur)
917 // This function is called, not when a selection is formed, but when
918 // a selection is cleared. Therefore, multiple keyboard selection
919 // will not repeatively trigger this function (bug 3877).
921 && cur.selBegin() == cur.bv().cursor().selBegin()
922 && cur.selEnd() == cur.bv().cursor().selEnd()) {
923 LYXERR(Debug::SELECTION, "saveSelection: '" << cur.selectionAsString(true) << "'");
924 copySelectionToStack(cur, selectionBuffer);
931 return !selectionBuffer.empty();
935 void clearSelection()
937 selectionBuffer.clear();
947 docstring selection(size_t sel_index)
949 return sel_index < theCuts.size()
950 ? theCuts[sel_index].first.back().asString(AS_STR_INSETS | AS_STR_NEWLINES)
955 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
956 DocumentClass const * const docclass, ErrorList & errorList)
958 if (cur.inTexted()) {
959 Text * text = cur.text();
965 boost::tie(ppp, endpit) =
966 pasteSelectionHelper(cur, parlist, docclass, errorList);
967 cur.forceBufferUpdate();
968 cur.clearSelection();
969 text->setCursor(cur, ppp.first, ppp.second);
972 // mathed is handled in InsetMathNest/InsetMathGrid
973 LASSERT(!cur.inMathed(), /**/);
977 void pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
979 // this does not make sense, if there is nothing to paste
980 if (!checkPastePossible(sel_index))
984 pasteParagraphList(cur, theCuts[sel_index].first,
985 theCuts[sel_index].second, errorList);
990 void pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs)
992 // Use internal clipboard if it is the most recent one
993 if (theClipboard().isInternal()) {
994 pasteFromStack(cur, errorList, 0);
998 // First try LyX format
999 if (theClipboard().hasLyXContents()) {
1000 string lyx = theClipboard().getAsLyX();
1002 // For some strange reason gcc 3.2 and 3.3 do not accept
1003 // Buffer buffer(string(), false);
1004 Buffer buffer("", false);
1005 buffer.setUnnamed(true);
1006 if (buffer.readString(lyx)) {
1008 pasteParagraphList(cur, buffer.paragraphs(),
1009 buffer.params().documentClassPtr(), errorList);
1016 // Then try plain text
1017 docstring const text = theClipboard().getAsText();
1022 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1024 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1028 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
1029 Clipboard::GraphicsType preferedType)
1031 LASSERT(theClipboard().hasGraphicsContents(preferedType), /**/);
1033 // get picture from clipboard
1034 FileName filename = theClipboard().getAsGraphics(cur, preferedType);
1035 if (filename.empty())
1038 // create inset for graphic
1039 InsetGraphics * inset = new InsetGraphics(cur.buffer());
1040 InsetGraphicsParams params;
1041 params.filename = support::DocFileName(filename.absFileName());
1042 inset->setParams(params);
1048 void pasteSelection(Cursor & cur, ErrorList & errorList)
1050 if (selectionBuffer.empty())
1053 pasteParagraphList(cur, selectionBuffer[0].first,
1054 selectionBuffer[0].second, errorList);
1058 void replaceSelectionWithString(Cursor & cur, docstring const & str, bool backwards)
1061 DocIterator selbeg = cur.selectionBegin();
1063 // Get font setting before we cut, we need a copy here, not a bare reference.
1065 selbeg.paragraph().getFontSettings(cur.buffer()->params(), selbeg.pos());
1067 // Insert the new string
1068 pos_type pos = cur.selEnd().pos();
1069 Paragraph & par = cur.selEnd().paragraph();
1070 docstring::const_iterator cit = str.begin();
1071 docstring::const_iterator end = str.end();
1072 for (; cit != end; ++cit, ++pos)
1073 par.insertChar(pos, *cit, font, cur.buffer()->params().trackChanges);
1075 // Cut the selection
1076 cutSelection(cur, true, false);
1078 // select the replacement
1080 selbeg.pos() += str.length();
1081 cur.setSelection(selbeg, -int(str.length()));
1083 cur.setSelection(selbeg, str.length());
1087 void replaceSelection(Cursor & cur)
1089 if (cur.selection())
1090 cutSelection(cur, true, false);
1094 void eraseSelection(Cursor & cur)
1096 //lyxerr << "cap::eraseSelection begin: " << cur << endl;
1097 CursorSlice const & i1 = cur.selBegin();
1098 CursorSlice const & i2 = cur.selEnd();
1099 if (i1.inset().asInsetMath()) {
1102 if (i1.idx() == i2.idx()) {
1103 i1.cell().erase(i1.pos(), i2.pos());
1104 // We may have deleted i1.cell(cur.pos()).
1105 // Make sure that pos is valid.
1106 if (cur.pos() > cur.lastpos())
1107 cur.pos() = cur.lastpos();
1109 InsetMath * p = i1.asInsetMath();
1110 Inset::row_type r1, r2;
1111 Inset::col_type c1, c2;
1112 region(i1, i2, r1, r2, c1, c2);
1113 for (Inset::row_type row = r1; row <= r2; ++row)
1114 for (Inset::col_type col = c1; col <= c2; ++col)
1115 p->cell(p->index(row, col)).clear();
1116 // We've deleted the whole cell. Only pos 0 is valid.
1119 // need a valid cursor. (Lgb)
1120 cur.clearSelection();
1122 lyxerr << "can't erase this selection 1" << endl;
1124 //lyxerr << "cap::eraseSelection end: " << cur << endl;
1128 void selDel(Cursor & cur)
1130 //lyxerr << "cap::selDel" << endl;
1131 if (cur.selection())
1132 eraseSelection(cur);
1136 void selClearOrDel(Cursor & cur)
1138 //lyxerr << "cap::selClearOrDel" << endl;
1139 if (lyxrc.auto_region_delete)
1142 cur.setSelection(false);
1146 docstring grabSelection(Cursor const & cur)
1148 if (!cur.selection())
1152 // grab selection by glueing multiple cells together. This is not what
1153 // we want because selections spanning multiple cells will get "&" and "\\"
1156 for (DocIterator dit = cur.selectionBegin();
1157 dit != cur.selectionEnd(); dit.forwardPos())
1158 os << asString(dit.cell());
1162 CursorSlice i1 = cur.selBegin();
1163 CursorSlice i2 = cur.selEnd();
1165 if (i1.idx() == i2.idx()) {
1166 if (i1.inset().asInsetMath()) {
1167 MathData::const_iterator it = i1.cell().begin();
1168 Buffer * buf = cur.buffer();
1169 return asString(MathData(buf, it + i1.pos(), it + i2.pos()));
1171 return from_ascii("unknown selection 1");
1175 Inset::row_type r1, r2;
1176 Inset::col_type c1, c2;
1177 region(i1, i2, r1, r2, c1, c2);
1180 if (i1.inset().asInsetMath()) {
1181 for (Inset::row_type row = r1; row <= r2; ++row) {
1184 for (Inset::col_type col = c1; col <= c2; ++col) {
1187 data += asString(i1.asInsetMath()->
1188 cell(i1.asInsetMath()->index(row, col)));
1192 data = from_ascii("unknown selection 2");
1198 void dirtyTabularStack(bool b)
1200 dirty_tabular_stack_ = b;
1204 bool tabularStackDirty()
1206 return dirty_tabular_stack_;