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 docstring const newname = lab->getParam("name");
246 if (oldname == newname)
248 // adapt the references
249 for (InsetIterator itt = inset_iterator_begin(in);
250 itt != i_end; ++itt) {
251 if (itt->lyxCode() == REF_CODE) {
253 static_cast<InsetCommand &>(*itt);
254 if (ref.getParam("reference") == oldname)
255 ref.setParam("reference", newname);
256 } else if (itt->lyxCode() == MATH_REF_CODE) {
258 static_cast<InsetMathHull &>(*itt);
259 // this is necessary to prevent an uninitialized
260 // buffer when the RefInset is in a MathBox.
261 // FIXME audit setBuffer/updateBuffer calls
262 mi.setBuffer(const_cast<Buffer &>(buffer));
263 if (mi.asRefInset()->getTarget() == oldname)
264 mi.asRefInset()->changeTarget(newname);
272 // check for duplicates
273 InsetCommand & lab = static_cast<InsetCommand &>(*it);
274 docstring const oldname = lab.getParam("name");
275 lab.updateCommand(oldname, false);
276 docstring const newname = lab.getParam("name");
277 if (oldname == newname)
279 // adapt the references
280 for (InsetIterator itt = inset_iterator_begin(in); itt != i_end; ++itt) {
281 if (itt->lyxCode() == REF_CODE) {
282 InsetCommand & ref = static_cast<InsetCommand &>(*itt);
283 if (ref.getParam("reference") == oldname)
284 ref.setParam("reference", newname);
285 } else if (itt->lyxCode() == MATH_REF_CODE) {
287 static_cast<InsetMathHull &>(*itt);
288 // this is necessary to prevent an uninitialized
289 // buffer when the RefInset is in a MathBox.
290 // FIXME audit setBuffer/updateBuffer calls
291 mi.setBuffer(const_cast<Buffer &>(buffer));
292 if (mi.asRefInset()->getTarget() == oldname)
293 mi.asRefInset()->changeTarget(newname);
300 InsetInclude & inc = static_cast<InsetInclude &>(*it);
306 // check for duplicates
307 InsetCommand & bib = static_cast<InsetCommand &>(*it);
308 docstring const oldkey = bib.getParam("key");
309 bib.updateCommand(oldkey, false);
310 docstring const newkey = bib.getParam("key");
311 if (oldkey == newkey)
313 // adapt the references
314 for (InsetIterator itt = inset_iterator_begin(in);
315 itt != i_end; ++itt) {
316 if (itt->lyxCode() == CITE_CODE) {
318 static_cast<InsetCommand &>(*itt);
319 if (ref.getParam("key") == oldkey)
320 ref.setParam("key", newkey);
327 // check if branch is known to target buffer
329 InsetBranch & br = static_cast<InsetBranch &>(*it);
330 docstring const name = br.branch();
333 bool const is_child = (&buffer != buffer.masterBuffer());
334 BranchList branchlist = buffer.params().branchlist();
335 if ((!is_child && branchlist.find(name))
336 || (is_child && (branchlist.find(name)
337 || buffer.masterBuffer()->params().branchlist().find(name))))
339 // FIXME: add an option to add the branch to the master's BranchList.
340 docstring text = bformat(
341 _("The pasted branch \"%1$s\" is undefined.\n"
342 "Do you want to add it to the document's branch list?"),
344 if (frontend::Alert::prompt(_("Unknown branch"),
345 text, 0, 1, _("&Add"), _("&Don't Add")) != 0)
347 lyx::dispatch(FuncRequest(LFUN_BRANCH_ADD, name));
355 insertion.swap(in.paragraphs());
357 // Split the paragraph for inserting the buf if necessary.
359 breakParagraphConservative(buffer.params(), pars, pit, pos);
363 pars.insert(boost::next(pars.begin(), pit),
367 // merge the empty par with the last par of the insertion
368 mergeParagraph(buffer.params(), pars,
369 pit + insertion.size() - 1);
371 pars.insert(boost::next(pars.begin(), pit + 1),
375 // merge the first par of the insertion with the current par
376 mergeParagraph(buffer.params(), pars, pit);
379 // Store the new cursor position.
380 pit_type last_paste = pit + insertion.size() - 1;
381 pit_type startpit = pit;
383 pos = pars[last_paste].size();
385 // FIXME Should we do it here, or should we let updateBuffer() do it?
386 // Set paragraph buffers. It's important to do this right away
387 // before something calls Inset::buffer() and causes a crash.
388 for (pit_type p = startpit; p <= pit; ++p)
389 pars[p].setBuffer(const_cast<Buffer &>(buffer));
391 // Join (conditionally) last pasted paragraph with next one, i.e.,
392 // the tail of the spliced document paragraph
393 if (!empty && last_paste + 1 != pit_type(pars.size())) {
394 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
395 mergeParagraph(buffer.params(), pars, last_paste);
396 } else if (pars[last_paste + 1].empty()) {
397 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
398 mergeParagraph(buffer.params(), pars, last_paste);
399 } else if (pars[last_paste].empty()) {
400 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
401 mergeParagraph(buffer.params(), pars, last_paste);
403 pars[last_paste + 1].stripLeadingSpaces(buffer.params().trackChanges);
408 return make_pair(PitPosPair(pit, pos), last_paste + 1);
412 PitPosPair eraseSelectionHelper(BufferParams const & params,
413 ParagraphList & pars,
414 pit_type startpit, pit_type endpit,
415 int startpos, int endpos)
417 // Start of selection is really invalid.
418 if (startpit == pit_type(pars.size()) ||
419 (startpos > pars[startpit].size()))
420 return PitPosPair(endpit, endpos);
422 // Start and end is inside same paragraph
423 if (endpit == pit_type(pars.size()) || startpit == endpit) {
424 endpos -= pars[startpit].eraseChars(startpos, endpos, params.trackChanges);
425 return PitPosPair(endpit, endpos);
428 for (pit_type pit = startpit; pit != endpit + 1;) {
429 pos_type const left = (pit == startpit ? startpos : 0);
430 pos_type right = (pit == endpit ? endpos : pars[pit].size() + 1);
431 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.trackChanges);
433 // Logically erase only, including the end-of-paragraph character
434 pars[pit].eraseChars(left, right, params.trackChanges);
436 // Separate handling of paragraph break:
437 if (merge && pit != endpit &&
439 || pars[pit].hasSameLayout(pars[endpit])
440 || pars[endpit].size() == endpos)) {
441 if (pit + 1 == endpit)
442 endpos += pars[pit].size();
443 mergeParagraph(params, pars, pit);
449 // Ensure legal cursor pos:
452 return PitPosPair(endpit, endpos);
456 void putClipboard(ParagraphList const & paragraphs,
457 DocumentClass const * const docclass, docstring const & plaintext)
459 // For some strange reason gcc 3.2 and 3.3 do not accept
460 // Buffer buffer(string(), false);
461 // This needs to be static to avoid a memory leak. When a Buffer is
462 // constructed, it constructs a BufferParams, which in turn constructs
463 // a DocumentClass, via new, that is never deleted. If we were to go to
464 // some kind of garbage collection there, or a shared_ptr, then this
465 // would not be needed.
466 static Buffer * buffer = theBufferList().newBuffer(
467 FileName::tempName().absFileName() + "_clipboard.internal");
468 buffer->setUnnamed(true);
469 buffer->paragraphs() = paragraphs;
470 buffer->inset().setBuffer(*buffer);
471 buffer->params().setDocumentClass(docclass);
473 if (buffer->write(lyx))
474 theClipboard().put(lyx.str(), plaintext);
476 theClipboard().put(string(), plaintext);
478 buffer->paragraphs().clear();
482 /// return true if the whole ParagraphList is deleted
483 static bool isFullyDeleted(ParagraphList const & pars)
485 pit_type const pars_size = static_cast<pit_type>(pars.size());
487 // check all paragraphs
488 for (pit_type pit = 0; pit < pars_size; ++pit) {
489 if (!pars[pit].empty()) // prevent assertion failure
490 if (!pars[pit].isDeleted(0, pars[pit].size()))
497 void copySelectionHelper(Buffer const & buf, Text const & text,
498 pit_type startpit, pit_type endpit,
499 int start, int end, DocumentClass const * const dc, CutStack & cutstack)
501 ParagraphList const & pars = text.paragraphs();
503 LASSERT(0 <= start && start <= pars[startpit].size(), /**/);
504 LASSERT(0 <= end && end <= pars[endpit].size(), /**/);
505 LASSERT(startpit != endpit || start <= end, /**/);
507 // Clone the paragraphs within the selection.
508 ParagraphList copy_pars(boost::next(pars.begin(), startpit),
509 boost::next(pars.begin(), endpit + 1));
511 // Remove the end of the last paragraph; afterwards, remove the
512 // beginning of the first paragraph. Keep this order - there may only
513 // be one paragraph! Do not track deletions here; this is an internal
514 // action not visible to the user
516 Paragraph & back = copy_pars.back();
517 back.eraseChars(end, back.size(), false);
518 Paragraph & front = copy_pars.front();
519 front.eraseChars(0, start, false);
521 ParagraphList::iterator it = copy_pars.begin();
522 ParagraphList::iterator it_end = copy_pars.end();
524 for (; it != it_end; it++) {
525 // Since we have a copy of the paragraphs, the insets
526 // do not have a proper buffer reference. It makes
527 // sense to add them temporarily, because the
528 // operations below depend on that (acceptChanges included).
529 it->setBuffer(const_cast<Buffer &>(buf));
530 // PassThru paragraphs have the Language
531 // latex_language. This is invalid for others, so we
532 // need to change it to the buffer language.
533 if (text.inset().getLayout().isPassThru())
534 it->changeLanguage(buf.params(),
535 latex_language, buf.language());
538 // do not copy text (also nested in insets) which is marked as
539 // deleted, unless the whole selection was deleted
540 if (!isFullyDeleted(copy_pars))
541 acceptChanges(copy_pars, buf.params());
543 rejectChanges(copy_pars, buf.params());
546 // do some final cleanup now, to make sure that the paragraphs
547 // are not linked to something else.
548 it = copy_pars.begin();
549 for (; it != it_end; it++) {
550 it->setBuffer(*static_cast<Buffer *>(0));
551 it->setInsetOwner(0);
554 DocumentClass * d = const_cast<DocumentClass *>(dc);
555 cutstack.push(make_pair(copy_pars, d));
565 void region(CursorSlice const & i1, CursorSlice const & i2,
566 Inset::row_type & r1, Inset::row_type & r2,
567 Inset::col_type & c1, Inset::col_type & c2)
569 Inset & p = i1.inset();
570 c1 = p.col(i1.idx());
571 c2 = p.col(i2.idx());
574 r1 = p.row(i1.idx());
575 r2 = p.row(i2.idx());
581 docstring grabAndEraseSelection(Cursor & cur)
583 if (!cur.selection())
585 docstring res = grabSelection(cur);
591 bool reduceSelectionToOneCell(Cursor & cur)
593 if (!cur.selection() || !cur.inMathed())
596 CursorSlice i1 = cur.selBegin();
597 CursorSlice i2 = cur.selEnd();
598 if (!i1.inset().asInsetMath())
601 // the easy case: do nothing if only one cell is selected
602 if (i1.idx() == i2.idx())
607 cur.top().pos() = cur.top().lastpos();
613 bool multipleCellsSelected(Cursor const & cur)
615 if (!cur.selection() || !cur.inMathed())
618 CursorSlice i1 = cur.selBegin();
619 CursorSlice i2 = cur.selEnd();
620 if (!i1.inset().asInsetMath())
623 if (i1.idx() == i2.idx())
630 void switchBetweenClasses(DocumentClass const * const oldone,
631 DocumentClass const * const newone, InsetText & in, ErrorList & errorlist)
635 LASSERT(!in.paragraphs().empty(), /**/);
636 if (oldone == newone)
639 DocumentClass const & oldtc = *oldone;
640 DocumentClass const & newtc = *newone;
643 ParIterator end = par_iterator_end(in);
644 for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
645 docstring const name = it->layout().name();
647 // the pasted text will keep their own layout name. If this layout does
648 // not exist in the new document, it will behave like a standard layout.
649 newtc.addLayoutIfNeeded(name);
651 if (in.usePlainLayout())
652 it->setLayout(newtc.plainLayout());
654 it->setLayout(newtc[name]);
658 InsetIterator const i_end = inset_iterator_end(in);
659 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
660 if (it->lyxCode() != FLEX_CODE)
661 // FIXME: Should we verify all InsetCollapsable?
663 docstring const & n = newone->insetLayout(it->name()).name();
664 bool const is_undefined = n.empty() ||
665 n == DocumentClass::plainInsetLayout().name();
668 // The flex inset is undefined in newtc
669 docstring const s = bformat(_(
670 "Flex inset %1$s is "
671 "undefined because of class "
672 "conversion from\n%2$s to %3$s"),
673 it->name(), from_utf8(oldtc.name()),
674 from_utf8(newtc.name()));
675 // To warn the user that something had to be done.
676 errorlist.push_back(ErrorItem(
677 _("Undefined flex inset"),
678 s, it.paragraph().id(), it.pos(), it.pos() + 1));
683 vector<docstring> availableSelections(Buffer const * buf)
685 vector<docstring> selList;
689 CutStack::const_iterator cit = theCuts.begin();
690 CutStack::const_iterator end = theCuts.end();
691 for (; cit != end; ++cit) {
692 // we do not use cit-> here because gcc 2.9x does not
694 ParagraphList const & pars = (*cit).first;
696 ParagraphList::const_iterator pit = pars.begin();
697 ParagraphList::const_iterator pend = pars.end();
698 for (; pit != pend; ++pit) {
699 Paragraph par(*pit, 0, 26);
700 // adapt paragraph to current buffer.
701 par.setBuffer(const_cast<Buffer &>(*buf));
702 asciiSel += par.asString(AS_STR_INSETS);
703 if (asciiSel.size() > 25) {
704 asciiSel.replace(22, docstring::npos,
710 selList.push_back(asciiSel);
717 size_type numberOfSelections()
719 return theCuts.size();
723 void cutSelection(Cursor & cur, bool doclear, bool realcut)
725 // This doesn't make sense, if there is no selection
726 if (!cur.selection())
729 // OK, we have a selection. This is always between cur.selBegin()
732 if (cur.inTexted()) {
733 Text * text = cur.text();
738 // make sure that the depth behind the selection are restored, too
739 cur.recordUndoSelection();
740 pit_type begpit = cur.selBegin().pit();
741 pit_type endpit = cur.selEnd().pit();
743 int endpos = cur.selEnd().pos();
745 BufferParams const & bp = cur.buffer()->params();
747 copySelectionHelper(*cur.buffer(),
750 cur.selBegin().pos(), endpos,
751 bp.documentClassPtr(), theCuts);
752 // Stuff what we got on the clipboard.
753 // Even if there is no selection.
754 putClipboard(theCuts[0].first, theCuts[0].second,
755 cur.selectionAsString(true));
758 if (begpit != endpit)
759 cur.updateFlags(Update::Force | Update::FitCursor);
761 boost::tie(endpit, endpos) =
762 eraseSelectionHelper(bp,
765 cur.selBegin().pos(), endpos);
767 // cutSelection can invalidate the cursor so we need to set
769 // we prefer the end for when tracking changes
773 // sometimes necessary
775 && text->paragraphs()[begpit].stripLeadingSpaces(bp.trackChanges))
778 // need a valid cursor. (Lgb)
779 cur.clearSelection();
780 cur.buffer()->updateBuffer();
782 // tell tabular that a recent copy happened
783 dirtyTabularStack(false);
786 if (cur.inMathed()) {
787 if (cur.selBegin().idx() != cur.selEnd().idx()) {
788 // The current selection spans more than one cell.
790 cur.recordUndoInset();
792 // Record only the current cell to avoid a jumping
803 void copySelection(Cursor const & cur)
805 copySelection(cur, cur.selectionAsString(true));
809 void copyInset(Cursor const & cur, Inset * inset, docstring const & plaintext)
813 BufferParams const & bp = cur.buffer()->params();
814 par.setLayout(bp.documentClass().plainLayout());
815 par.insertInset(0, inset, Change(Change::UNCHANGED));
817 theCuts.push(make_pair(pars, bp.documentClassPtr()));
819 // stuff the selection onto the X clipboard, from an explicit copy request
820 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
825 void copySelectionToStack(Cursor const & cur, CutStack & cutstack)
827 // this doesn't make sense, if there is no selection
828 if (!cur.selection())
831 // copySelection can not yet handle the case of cross idx selection
832 if (cur.selBegin().idx() != cur.selEnd().idx())
835 if (cur.inTexted()) {
836 Text * text = cur.text();
838 // ok we have a selection. This is always between cur.selBegin()
839 // and sel_end cursor
841 // copy behind a space if there is one
842 ParagraphList & pars = text->paragraphs();
843 pos_type pos = cur.selBegin().pos();
844 pit_type par = cur.selBegin().pit();
845 while (pos < pars[par].size() &&
846 pars[par].isLineSeparator(pos) &&
847 (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
850 copySelectionHelper(*cur.buffer(), *text, par, cur.selEnd().pit(),
851 pos, cur.selEnd().pos(),
852 cur.buffer()->params().documentClassPtr(), cutstack);
854 // Reset the dirty_tabular_stack_ flag only when something
855 // is copied to the clipboard (not to the selectionBuffer).
856 if (&cutstack == &theCuts)
857 dirtyTabularStack(false);
860 if (cur.inMathed()) {
861 //lyxerr << "copySelection in mathed" << endl;
864 BufferParams const & bp = cur.buffer()->params();
865 // FIXME This should be the plain layout...right?
866 par.setLayout(bp.documentClass().plainLayout());
867 par.insert(0, grabSelection(cur), Font(), Change(Change::UNCHANGED));
869 cutstack.push(make_pair(pars, bp.documentClassPtr()));
876 void copySelectionToStack()
878 if (!selectionBuffer.empty())
879 theCuts.push(selectionBuffer[0]);
883 void copySelection(Cursor const & cur, docstring const & plaintext)
885 // In tablemode, because copy and paste actually use special table stack
886 // we do not attempt to get selected paragraphs under cursor. Instead, a
887 // paragraph with the plain text version is generated so that table cells
888 // can be pasted as pure text somewhere else.
889 if (cur.selBegin().idx() != cur.selEnd().idx()) {
892 BufferParams const & bp = cur.buffer()->params();
893 par.setLayout(bp.documentClass().plainLayout());
894 par.insert(0, plaintext, Font(), Change(Change::UNCHANGED));
896 theCuts.push(make_pair(pars, bp.documentClassPtr()));
898 copySelectionToStack(cur, theCuts);
901 // stuff the selection onto the X clipboard, from an explicit copy request
902 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
906 void saveSelection(Cursor const & cur)
908 // This function is called, not when a selection is formed, but when
909 // a selection is cleared. Therefore, multiple keyboard selection
910 // will not repeatively trigger this function (bug 3877).
912 && cur.selBegin() == cur.bv().cursor().selBegin()
913 && cur.selEnd() == cur.bv().cursor().selEnd()) {
914 LYXERR(Debug::SELECTION, "saveSelection: '" << cur.selectionAsString(true) << "'");
915 copySelectionToStack(cur, selectionBuffer);
922 return !selectionBuffer.empty();
926 void clearSelection()
928 selectionBuffer.clear();
938 docstring selection(size_t sel_index)
940 return sel_index < theCuts.size()
941 ? theCuts[sel_index].first.back().asString(AS_STR_INSETS | AS_STR_NEWLINES)
946 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
947 DocumentClass const * const docclass, ErrorList & errorList)
949 if (cur.inTexted()) {
950 Text * text = cur.text();
956 boost::tie(ppp, endpit) =
957 pasteSelectionHelper(cur, parlist, docclass, errorList);
958 cur.buffer()->updateBuffer();
959 cur.clearSelection();
960 text->setCursor(cur, ppp.first, ppp.second);
963 // mathed is handled in InsetMathNest/InsetMathGrid
964 LASSERT(!cur.inMathed(), /**/);
968 void pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
970 // this does not make sense, if there is nothing to paste
971 if (!checkPastePossible(sel_index))
975 pasteParagraphList(cur, theCuts[sel_index].first,
976 theCuts[sel_index].second, errorList);
981 void pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs)
983 // Use internal clipboard if it is the most recent one
984 if (theClipboard().isInternal()) {
985 pasteFromStack(cur, errorList, 0);
989 // First try LyX format
990 if (theClipboard().hasLyXContents()) {
991 string lyx = theClipboard().getAsLyX();
993 // For some strange reason gcc 3.2 and 3.3 do not accept
994 // Buffer buffer(string(), false);
995 Buffer buffer("", false);
996 buffer.setUnnamed(true);
997 if (buffer.readString(lyx)) {
999 pasteParagraphList(cur, buffer.paragraphs(),
1000 buffer.params().documentClassPtr(), errorList);
1007 // Then try plain text
1008 docstring const text = theClipboard().getAsText();
1013 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1015 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1019 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
1020 Clipboard::GraphicsType preferedType)
1022 LASSERT(theClipboard().hasGraphicsContents(preferedType), /**/);
1024 // get picture from clipboard
1025 FileName filename = theClipboard().getAsGraphics(cur, preferedType);
1026 if (filename.empty())
1029 // create inset for graphic
1030 InsetGraphics * inset = new InsetGraphics(cur.buffer());
1031 InsetGraphicsParams params;
1032 params.filename = support::DocFileName(filename.absFileName());
1033 inset->setParams(params);
1039 void pasteSelection(Cursor & cur, ErrorList & errorList)
1041 if (selectionBuffer.empty())
1044 pasteParagraphList(cur, selectionBuffer[0].first,
1045 selectionBuffer[0].second, errorList);
1049 void replaceSelectionWithString(Cursor & cur, docstring const & str, bool backwards)
1052 DocIterator selbeg = cur.selectionBegin();
1054 // Get font setting before we cut, we need a copy here, not a bare reference.
1056 selbeg.paragraph().getFontSettings(cur.buffer()->params(), selbeg.pos());
1058 // Insert the new string
1059 pos_type pos = cur.selEnd().pos();
1060 Paragraph & par = cur.selEnd().paragraph();
1061 docstring::const_iterator cit = str.begin();
1062 docstring::const_iterator end = str.end();
1063 for (; cit != end; ++cit, ++pos)
1064 par.insertChar(pos, *cit, font, cur.buffer()->params().trackChanges);
1066 // Cut the selection
1067 cutSelection(cur, true, false);
1069 // select the replacement
1071 selbeg.pos() += str.length();
1072 cur.setSelection(selbeg, -int(str.length()));
1074 cur.setSelection(selbeg, str.length());
1078 void replaceSelection(Cursor & cur)
1080 if (cur.selection())
1081 cutSelection(cur, true, false);
1085 void eraseSelection(Cursor & cur)
1087 //lyxerr << "cap::eraseSelection begin: " << cur << endl;
1088 CursorSlice const & i1 = cur.selBegin();
1089 CursorSlice const & i2 = cur.selEnd();
1090 if (i1.inset().asInsetMath()) {
1093 if (i1.idx() == i2.idx()) {
1094 i1.cell().erase(i1.pos(), i2.pos());
1095 // We may have deleted i1.cell(cur.pos()).
1096 // Make sure that pos is valid.
1097 if (cur.pos() > cur.lastpos())
1098 cur.pos() = cur.lastpos();
1100 InsetMath * p = i1.asInsetMath();
1101 Inset::row_type r1, r2;
1102 Inset::col_type c1, c2;
1103 region(i1, i2, r1, r2, c1, c2);
1104 for (Inset::row_type row = r1; row <= r2; ++row)
1105 for (Inset::col_type col = c1; col <= c2; ++col)
1106 p->cell(p->index(row, col)).clear();
1107 // We've deleted the whole cell. Only pos 0 is valid.
1110 // need a valid cursor. (Lgb)
1111 cur.clearSelection();
1113 lyxerr << "can't erase this selection 1" << endl;
1115 //lyxerr << "cap::eraseSelection end: " << cur << endl;
1119 void selDel(Cursor & cur)
1121 //lyxerr << "cap::selDel" << endl;
1122 if (cur.selection())
1123 eraseSelection(cur);
1127 void selClearOrDel(Cursor & cur)
1129 //lyxerr << "cap::selClearOrDel" << endl;
1130 if (lyxrc.auto_region_delete)
1133 cur.setSelection(false);
1137 docstring grabSelection(Cursor const & cur)
1139 if (!cur.selection())
1143 // grab selection by glueing multiple cells together. This is not what
1144 // we want because selections spanning multiple cells will get "&" and "\\"
1147 for (DocIterator dit = cur.selectionBegin();
1148 dit != cur.selectionEnd(); dit.forwardPos())
1149 os << asString(dit.cell());
1153 CursorSlice i1 = cur.selBegin();
1154 CursorSlice i2 = cur.selEnd();
1156 if (i1.idx() == i2.idx()) {
1157 if (i1.inset().asInsetMath()) {
1158 MathData::const_iterator it = i1.cell().begin();
1159 Buffer * buf = cur.buffer();
1160 return asString(MathData(buf, it + i1.pos(), it + i2.pos()));
1162 return from_ascii("unknown selection 1");
1166 Inset::row_type r1, r2;
1167 Inset::col_type c1, c2;
1168 region(i1, i2, r1, r2, c1, c2);
1171 if (i1.inset().asInsetMath()) {
1172 for (Inset::row_type row = r1; row <= r2; ++row) {
1175 for (Inset::col_type col = c1; col <= c2; ++col) {
1178 data += asString(i1.asInsetMath()->
1179 cell(i1.asInsetMath()->index(row, col)));
1183 data = from_ascii("unknown selection 2");
1189 void dirtyTabularStack(bool b)
1191 dirty_tabular_stack_ = b;
1195 bool tabularStackDirty()
1197 return dirty_tabular_stack_;