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/updateLabels 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/updateLabels 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 updateLabels() 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());
544 // do some final cleanup now, to make sure that the paragraphs
545 // are not linked to something else.
546 it = copy_pars.begin();
547 for (; it != it_end; it++) {
548 it->setBuffer(*static_cast<Buffer *>(0));
549 it->setInsetOwner(0);
552 DocumentClass * d = const_cast<DocumentClass *>(dc);
553 cutstack.push(make_pair(copy_pars, d));
563 void region(CursorSlice const & i1, CursorSlice const & i2,
564 Inset::row_type & r1, Inset::row_type & r2,
565 Inset::col_type & c1, Inset::col_type & c2)
567 Inset & p = i1.inset();
568 c1 = p.col(i1.idx());
569 c2 = p.col(i2.idx());
572 r1 = p.row(i1.idx());
573 r2 = p.row(i2.idx());
579 docstring grabAndEraseSelection(Cursor & cur)
581 if (!cur.selection())
583 docstring res = grabSelection(cur);
589 bool reduceSelectionToOneCell(Cursor & cur)
591 if (!cur.selection() || !cur.inMathed())
594 CursorSlice i1 = cur.selBegin();
595 CursorSlice i2 = cur.selEnd();
596 if (!i1.inset().asInsetMath())
599 // the easy case: do nothing if only one cell is selected
600 if (i1.idx() == i2.idx())
605 cur.top().pos() = cur.top().lastpos();
611 bool multipleCellsSelected(Cursor const & cur)
613 if (!cur.selection() || !cur.inMathed())
616 CursorSlice i1 = cur.selBegin();
617 CursorSlice i2 = cur.selEnd();
618 if (!i1.inset().asInsetMath())
621 if (i1.idx() == i2.idx())
628 void switchBetweenClasses(DocumentClass const * const oldone,
629 DocumentClass const * const newone, InsetText & in, ErrorList & errorlist)
633 LASSERT(!in.paragraphs().empty(), /**/);
634 if (oldone == newone)
637 DocumentClass const & oldtc = *oldone;
638 DocumentClass const & newtc = *newone;
641 ParIterator end = par_iterator_end(in);
642 for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
643 docstring const name = it->layout().name();
645 // the pasted text will keep their own layout name. If this layout does
646 // not exist in the new document, it will behave like a standard layout.
647 newtc.addLayoutIfNeeded(name);
649 if (in.usePlainLayout())
650 it->setLayout(newtc.plainLayout());
652 it->setLayout(newtc[name]);
656 InsetIterator const i_end = inset_iterator_end(in);
657 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
658 if (it->lyxCode() != FLEX_CODE)
659 // FIXME: Should we verify all InsetCollapsable?
661 docstring const & n = newone->insetLayout(it->name()).name();
662 bool const is_undefined = n.empty() ||
663 n == DocumentClass::plainInsetLayout().name();
666 // The flex inset is undefined in newtc
667 docstring const s = bformat(_(
668 "Flex inset %1$s is "
669 "undefined because of class "
670 "conversion from\n%2$s to %3$s"),
671 it->name(), from_utf8(oldtc.name()),
672 from_utf8(newtc.name()));
673 // To warn the user that something had to be done.
674 errorlist.push_back(ErrorItem(
675 _("Undefined flex inset"),
676 s, it.paragraph().id(), it.pos(), it.pos() + 1));
681 vector<docstring> availableSelections(Buffer const * buf)
683 vector<docstring> selList;
687 CutStack::const_iterator cit = theCuts.begin();
688 CutStack::const_iterator end = theCuts.end();
689 for (; cit != end; ++cit) {
690 // we do not use cit-> here because gcc 2.9x does not
692 ParagraphList const & pars = (*cit).first;
694 ParagraphList::const_iterator pit = pars.begin();
695 ParagraphList::const_iterator pend = pars.end();
696 for (; pit != pend; ++pit) {
697 Paragraph par(*pit, 0, 26);
698 // adapt paragraph to current buffer.
699 par.setBuffer(const_cast<Buffer &>(*buf));
700 asciiSel += par.asString(AS_STR_INSETS);
701 if (asciiSel.size() > 25) {
702 asciiSel.replace(22, docstring::npos,
708 selList.push_back(asciiSel);
715 size_type numberOfSelections()
717 return theCuts.size();
721 void cutSelection(Cursor & cur, bool doclear, bool realcut)
723 // This doesn't make sense, if there is no selection
724 if (!cur.selection())
727 // OK, we have a selection. This is always between cur.selBegin()
730 if (cur.inTexted()) {
731 Text * text = cur.text();
736 // make sure that the depth behind the selection are restored, too
737 cur.recordUndoSelection();
738 pit_type begpit = cur.selBegin().pit();
739 pit_type endpit = cur.selEnd().pit();
741 int endpos = cur.selEnd().pos();
743 BufferParams const & bp = cur.buffer()->params();
745 copySelectionHelper(*cur.buffer(),
748 cur.selBegin().pos(), endpos,
749 bp.documentClassPtr(), theCuts);
750 // Stuff what we got on the clipboard.
751 // Even if there is no selection.
752 putClipboard(theCuts[0].first, theCuts[0].second,
753 cur.selectionAsString(true));
756 if (begpit != endpit)
757 cur.updateFlags(Update::Force | Update::FitCursor);
759 boost::tie(endpit, endpos) =
760 eraseSelectionHelper(bp,
763 cur.selBegin().pos(), endpos);
765 // cutSelection can invalidate the cursor so we need to set
767 // we prefer the end for when tracking changes
771 // sometimes necessary
773 && text->paragraphs()[begpit].stripLeadingSpaces(bp.trackChanges))
776 // need a valid cursor. (Lgb)
777 cur.clearSelection();
778 cur.buffer()->updateLabels();
780 // tell tabular that a recent copy happened
781 dirtyTabularStack(false);
784 if (cur.inMathed()) {
785 if (cur.selBegin().idx() != cur.selEnd().idx()) {
786 // The current selection spans more than one cell.
788 cur.recordUndoInset();
790 // Record only the current cell to avoid a jumping
801 void copySelection(Cursor const & cur)
803 copySelection(cur, cur.selectionAsString(true));
807 void copyInset(Cursor const & cur, Inset * inset, docstring const & plaintext)
811 BufferParams const & bp = cur.buffer()->params();
812 par.setLayout(bp.documentClass().plainLayout());
813 par.insertInset(0, inset, Change(Change::UNCHANGED));
815 theCuts.push(make_pair(pars, bp.documentClassPtr()));
817 // stuff the selection onto the X clipboard, from an explicit copy request
818 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
823 void copySelectionToStack(Cursor const & cur, CutStack & cutstack)
825 // this doesn't make sense, if there is no selection
826 if (!cur.selection())
829 // copySelection can not yet handle the case of cross idx selection
830 if (cur.selBegin().idx() != cur.selEnd().idx())
833 if (cur.inTexted()) {
834 Text * text = cur.text();
836 // ok we have a selection. This is always between cur.selBegin()
837 // and sel_end cursor
839 // copy behind a space if there is one
840 ParagraphList & pars = text->paragraphs();
841 pos_type pos = cur.selBegin().pos();
842 pit_type par = cur.selBegin().pit();
843 while (pos < pars[par].size() &&
844 pars[par].isLineSeparator(pos) &&
845 (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
848 copySelectionHelper(*cur.buffer(), *text, par, cur.selEnd().pit(),
849 pos, cur.selEnd().pos(),
850 cur.buffer()->params().documentClassPtr(), cutstack);
852 // Reset the dirty_tabular_stack_ flag only when something
853 // is copied to the clipboard (not to the selectionBuffer).
854 if (&cutstack == &theCuts)
855 dirtyTabularStack(false);
858 if (cur.inMathed()) {
859 //lyxerr << "copySelection in mathed" << endl;
862 BufferParams const & bp = cur.buffer()->params();
863 // FIXME This should be the plain layout...right?
864 par.setLayout(bp.documentClass().plainLayout());
865 par.insert(0, grabSelection(cur), Font(), Change(Change::UNCHANGED));
867 cutstack.push(make_pair(pars, bp.documentClassPtr()));
874 void copySelectionToStack()
876 if (!selectionBuffer.empty())
877 theCuts.push(selectionBuffer[0]);
881 void copySelection(Cursor const & cur, docstring const & plaintext)
883 // In tablemode, because copy and paste actually use special table stack
884 // we do not attempt to get selected paragraphs under cursor. Instead, a
885 // paragraph with the plain text version is generated so that table cells
886 // can be pasted as pure text somewhere else.
887 if (cur.selBegin().idx() != cur.selEnd().idx()) {
890 BufferParams const & bp = cur.buffer()->params();
891 par.setLayout(bp.documentClass().plainLayout());
892 par.insert(0, plaintext, Font(), Change(Change::UNCHANGED));
894 theCuts.push(make_pair(pars, bp.documentClassPtr()));
896 copySelectionToStack(cur, theCuts);
899 // stuff the selection onto the X clipboard, from an explicit copy request
900 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
904 void saveSelection(Cursor const & cur)
906 // This function is called, not when a selection is formed, but when
907 // a selection is cleared. Therefore, multiple keyboard selection
908 // will not repeatively trigger this function (bug 3877).
910 && cur.selBegin() == cur.bv().cursor().selBegin()
911 && cur.selEnd() == cur.bv().cursor().selEnd()) {
912 LYXERR(Debug::SELECTION, "saveSelection: '" << cur.selectionAsString(true) << "'");
913 copySelectionToStack(cur, selectionBuffer);
920 return !selectionBuffer.empty();
924 void clearSelection()
926 selectionBuffer.clear();
936 docstring selection(size_t sel_index)
938 return sel_index < theCuts.size()
939 ? theCuts[sel_index].first.back().asString(AS_STR_INSETS | AS_STR_NEWLINES)
944 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
945 DocumentClass const * const docclass, ErrorList & errorList)
947 if (cur.inTexted()) {
948 Text * text = cur.text();
954 boost::tie(ppp, endpit) =
955 pasteSelectionHelper(cur, parlist, docclass, errorList);
956 cur.buffer()->updateLabels();
957 cur.clearSelection();
958 text->setCursor(cur, ppp.first, ppp.second);
961 // mathed is handled in InsetMathNest/InsetMathGrid
962 LASSERT(!cur.inMathed(), /**/);
966 void pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
968 // this does not make sense, if there is nothing to paste
969 if (!checkPastePossible(sel_index))
973 pasteParagraphList(cur, theCuts[sel_index].first,
974 theCuts[sel_index].second, errorList);
979 void pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs)
981 // Use internal clipboard if it is the most recent one
982 if (theClipboard().isInternal()) {
983 pasteFromStack(cur, errorList, 0);
987 // First try LyX format
988 if (theClipboard().hasLyXContents()) {
989 string lyx = theClipboard().getAsLyX();
991 // For some strange reason gcc 3.2 and 3.3 do not accept
992 // Buffer buffer(string(), false);
993 Buffer buffer("", false);
994 buffer.setUnnamed(true);
995 if (buffer.readString(lyx)) {
997 pasteParagraphList(cur, buffer.paragraphs(),
998 buffer.params().documentClassPtr(), errorList);
1005 // Then try plain text
1006 docstring const text = theClipboard().getAsText();
1011 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1013 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1017 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
1018 Clipboard::GraphicsType preferedType)
1020 LASSERT(theClipboard().hasGraphicsContents(preferedType), /**/);
1022 // get picture from clipboard
1023 FileName filename = theClipboard().getAsGraphics(cur, preferedType);
1024 if (filename.empty())
1027 // create inset for graphic
1028 InsetGraphics * inset = new InsetGraphics(cur.buffer());
1029 InsetGraphicsParams params;
1030 params.filename = support::DocFileName(filename.absFilename());
1031 inset->setParams(params);
1037 void pasteSelection(Cursor & cur, ErrorList & errorList)
1039 if (selectionBuffer.empty())
1042 pasteParagraphList(cur, selectionBuffer[0].first,
1043 selectionBuffer[0].second, errorList);
1047 void replaceSelectionWithString(Cursor & cur, docstring const & str, bool backwards)
1050 DocIterator selbeg = cur.selectionBegin();
1052 // Get font setting before we cut, we need a copy here, not a bare reference.
1054 selbeg.paragraph().getFontSettings(cur.buffer()->params(), selbeg.pos());
1056 // Insert the new string
1057 pos_type pos = cur.selEnd().pos();
1058 Paragraph & par = cur.selEnd().paragraph();
1059 docstring::const_iterator cit = str.begin();
1060 docstring::const_iterator end = str.end();
1061 for (; cit != end; ++cit, ++pos)
1062 par.insertChar(pos, *cit, font, cur.buffer()->params().trackChanges);
1064 // Cut the selection
1065 cutSelection(cur, true, false);
1067 // select the replacement
1069 selbeg.pos() += str.length();
1070 cur.setSelection(selbeg, -int(str.length()));
1072 cur.setSelection(selbeg, str.length());
1076 void replaceSelection(Cursor & cur)
1078 if (cur.selection())
1079 cutSelection(cur, true, false);
1083 void eraseSelection(Cursor & cur)
1085 //lyxerr << "cap::eraseSelection begin: " << cur << endl;
1086 CursorSlice const & i1 = cur.selBegin();
1087 CursorSlice const & i2 = cur.selEnd();
1088 if (i1.inset().asInsetMath()) {
1091 if (i1.idx() == i2.idx()) {
1092 i1.cell().erase(i1.pos(), i2.pos());
1093 // We may have deleted i1.cell(cur.pos()).
1094 // Make sure that pos is valid.
1095 if (cur.pos() > cur.lastpos())
1096 cur.pos() = cur.lastpos();
1098 InsetMath * p = i1.asInsetMath();
1099 Inset::row_type r1, r2;
1100 Inset::col_type c1, c2;
1101 region(i1, i2, r1, r2, c1, c2);
1102 for (Inset::row_type row = r1; row <= r2; ++row)
1103 for (Inset::col_type col = c1; col <= c2; ++col)
1104 p->cell(p->index(row, col)).clear();
1105 // We've deleted the whole cell. Only pos 0 is valid.
1108 // need a valid cursor. (Lgb)
1109 cur.clearSelection();
1111 lyxerr << "can't erase this selection 1" << endl;
1113 //lyxerr << "cap::eraseSelection end: " << cur << endl;
1117 void selDel(Cursor & cur)
1119 //lyxerr << "cap::selDel" << endl;
1120 if (cur.selection())
1121 eraseSelection(cur);
1125 void selClearOrDel(Cursor & cur)
1127 //lyxerr << "cap::selClearOrDel" << endl;
1128 if (lyxrc.auto_region_delete)
1131 cur.setSelection(false);
1135 docstring grabSelection(Cursor const & cur)
1137 if (!cur.selection())
1141 // grab selection by glueing multiple cells together. This is not what
1142 // we want because selections spanning multiple cells will get "&" and "\\"
1145 for (DocIterator dit = cur.selectionBegin();
1146 dit != cur.selectionEnd(); dit.forwardPos())
1147 os << asString(dit.cell());
1151 CursorSlice i1 = cur.selBegin();
1152 CursorSlice i2 = cur.selEnd();
1154 if (i1.idx() == i2.idx()) {
1155 if (i1.inset().asInsetMath()) {
1156 MathData::const_iterator it = i1.cell().begin();
1157 Buffer * buf = cur.buffer();
1158 return asString(MathData(buf, it + i1.pos(), it + i2.pos()));
1160 return from_ascii("unknown selection 1");
1164 Inset::row_type r1, r2;
1165 Inset::col_type c1, c2;
1166 region(i1, i2, r1, r2, c1, c2);
1169 if (i1.inset().asInsetMath()) {
1170 for (Inset::row_type row = r1; row <= r2; ++row) {
1173 for (Inset::col_type col = c1; col <= c2; ++col) {
1176 data += asString(i1.asInsetMath()->
1177 cell(i1.asInsetMath()->index(row, col)));
1181 data = from_ascii("unknown selection 2");
1187 void dirtyTabularStack(bool b)
1189 dirty_tabular_stack_ = b;
1193 bool tabularStackDirty()
1195 return dirty_tabular_stack_;