2 * \file CutAndPaste.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Lars Gullik Bjønnes
8 * \author Alfredo Braunstein
11 * Full author contact details are available in file CREDITS.
16 #include "CutAndPaste.h"
18 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "BufferView.h"
26 #include "ErrorList.h"
28 #include "FuncRequest.h"
29 #include "InsetIterator.h"
30 #include "InsetList.h"
35 #include "Paragraph.h"
36 #include "ParagraphParameters.h"
37 #include "ParIterator.h"
38 #include "TextClass.h"
40 #include "insets/InsetBibitem.h"
41 #include "insets/InsetBranch.h"
42 #include "insets/InsetCommand.h"
43 #include "insets/InsetFlex.h"
44 #include "insets/InsetGraphics.h"
45 #include "insets/InsetGraphicsParams.h"
46 #include "insets/InsetInclude.h"
47 #include "insets/InsetLabel.h"
48 #include "insets/InsetTabular.h"
50 #include "mathed/MathData.h"
51 #include "mathed/InsetMath.h"
52 #include "mathed/InsetMathHull.h"
53 #include "mathed/InsetMathRef.h"
54 #include "mathed/MathSupport.h"
56 #include "support/debug.h"
57 #include "support/docstream.h"
58 #include "support/gettext.h"
59 #include "support/lassert.h"
60 #include "support/limited_stack.h"
61 #include "support/lstrings.h"
63 #include "frontends/alert.h"
64 #include "frontends/Clipboard.h"
65 #include "frontends/Selection.h"
67 #include <boost/tuple/tuple.hpp>
68 #include <boost/next_prior.hpp>
73 using namespace lyx::support;
74 using lyx::frontend::Clipboard;
80 typedef pair<pit_type, int> PitPosPair;
82 typedef limited_stack<pair<ParagraphList, DocumentClass const *> > CutStack;
85 // persistent selection, cleared until the next selection
86 CutStack selectionBuffer(1);
88 // store whether the tabular stack is newer than the normal copy stack
89 // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
90 // when we (hopefully) have a one-for-all paste mechanism.
91 bool dirty_tabular_stack_ = false;
94 bool checkPastePossible(int index)
96 return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
100 pair<PitPosPair, pit_type>
101 pasteSelectionHelper(Cursor const & cur, ParagraphList const & parlist,
102 DocumentClass const * const oldDocClass, ErrorList & errorlist)
104 Buffer const & buffer = *cur.buffer();
105 pit_type pit = cur.pit();
106 pos_type pos = cur.pos();
107 InsetText * target_inset = cur.inset().asInsetText();
109 InsetTabular * it = cur.inset().asInsetTabular();
110 target_inset = it? it->cell(cur.idx())->asInsetText() : 0;
112 LASSERT(target_inset, return make_pair(PitPosPair(pit, pos), pit));
113 ParagraphList & pars = target_inset->paragraphs();
116 return make_pair(PitPosPair(pit, pos), pit);
118 BOOST_ASSERT (pos <= pars[pit].size());
120 // Make a copy of the CaP paragraphs.
121 ParagraphList insertion = parlist;
122 DocumentClass const * const newDocClass =
123 buffer.params().documentClassPtr();
125 // Now remove all out of the pars which is NOT allowed in the
126 // new environment and set also another font if that is required.
128 // Convert newline to paragraph break in ParbreakIsNewline
129 if (target_inset->getLayout().parbreakIsNewline()
130 || pars[pit].layout().parbreak_is_newline) {
131 for (size_t i = 0; i != insertion.size(); ++i) {
132 for (pos_type j = 0; j != insertion[i].size(); ++j) {
133 if (insertion[i].isNewline(j)) {
134 // do not track deletion of newline
135 insertion[i].eraseChar(j, false);
136 insertion[i].setInsetOwner(target_inset);
137 breakParagraphConservative(
146 // set the paragraphs to plain layout if necessary
147 if (cur.inset().usePlainLayout()) {
148 bool forcePlainLayout = cur.inset().forcePlainLayout();
149 Layout const & plainLayout = newDocClass->plainLayout();
150 Layout const & defaultLayout = newDocClass->defaultLayout();
151 ParagraphList::iterator const end = insertion.end();
152 ParagraphList::iterator par = insertion.begin();
153 for (; par != end; ++par) {
154 Layout const & parLayout = par->layout();
155 if (forcePlainLayout || parLayout == defaultLayout)
156 par->setLayout(plainLayout);
158 } else { // check if we need to reset from plain layout
159 Layout const & defaultLayout = newDocClass->defaultLayout();
160 Layout const & plainLayout = newDocClass->plainLayout();
161 ParagraphList::iterator const end = insertion.end();
162 ParagraphList::iterator par = insertion.begin();
163 for (; par != end; ++par) {
164 Layout const & parLayout = par->layout();
165 if (parLayout == plainLayout)
166 par->setLayout(defaultLayout);
170 InsetText in(cur.buffer());
171 // Make sure there is no class difference.
172 in.paragraphs().clear();
173 // This works without copying any paragraph data because we have
174 // a specialized swap method for ParagraphList. This is important
175 // since we store pointers to insets at some places and we don't
176 // want to invalidate them.
177 insertion.swap(in.paragraphs());
178 cap::switchBetweenClasses(oldDocClass, newDocClass, in, errorlist);
179 insertion.swap(in.paragraphs());
181 ParagraphList::iterator tmpbuf = insertion.begin();
182 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
184 depth_type max_depth = pars[pit].getMaxDepthAfter();
186 for (; tmpbuf != insertion.end(); ++tmpbuf) {
187 // If we have a negative jump so that the depth would
188 // go below 0 depth then we have to redo the delta to
189 // this new max depth level so that subsequent
190 // paragraphs are aligned correctly to this paragraph
192 if (int(tmpbuf->params().depth()) + depth_delta < 0)
195 // Set the right depth so that we are not too deep or shallow.
196 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
197 if (tmpbuf->params().depth() > max_depth)
198 tmpbuf->params().depth(max_depth);
200 // Only set this from the 2nd on as the 2nd depends
201 // for maxDepth still on pit.
202 if (tmpbuf != insertion.begin())
203 max_depth = tmpbuf->getMaxDepthAfter();
205 // Set the inset owner of this paragraph.
206 tmpbuf->setInsetOwner(target_inset);
207 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
208 // do not track deletion of invalid insets
209 if (Inset * inset = tmpbuf->getInset(i))
210 if (!target_inset->insetAllowed(inset->lyxCode()))
211 tmpbuf->eraseChar(i--, false);
214 tmpbuf->setChange(Change(buffer.params().trackChanges ?
215 Change::INSERTED : Change::UNCHANGED));
218 bool const empty = pars[pit].empty();
220 // Make the buf exactly the same layout as the cursor
222 insertion.begin()->makeSameLayout(pars[pit]);
225 // Prepare the paragraphs and insets for insertion.
226 insertion.swap(in.paragraphs());
228 InsetIterator const i_end = inset_iterator_end(in);
229 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
230 // Even though this will also be done later, it has to be done here
231 // since some inset might going to try to access
232 // the buffer() member.
233 it->setBuffer(const_cast<Buffer &>(buffer));
234 switch (it->lyxCode()) {
236 case MATH_HULL_CODE: {
237 // check for equation labels and resolve duplicates
238 InsetMathHull * ins = it->asInsetMath()->asHullInset();
239 std::vector<InsetLabel *> labels = ins->getLabels();
240 for (size_t i = 0; i != labels.size(); ++i) {
243 InsetLabel * lab = labels[i];
244 docstring const oldname = lab->getParam("name");
245 lab->updateLabel(oldname);
246 // We need to update the buffer reference cache.
247 cur.forceBufferUpdate();
248 docstring const newname = lab->getParam("name");
249 if (oldname == newname)
251 // adapt the references
252 for (InsetIterator itt = inset_iterator_begin(in);
253 itt != i_end; ++itt) {
254 if (itt->lyxCode() == REF_CODE) {
255 InsetCommand * ref = itt->asInsetCommand();
256 if (ref->getParam("reference") == oldname)
257 ref->setParam("reference", newname);
258 } else if (itt->lyxCode() == MATH_REF_CODE) {
259 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
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->getTarget() == oldname)
265 mi->changeTarget(newname);
273 // check for duplicates
274 InsetLabel & lab = static_cast<InsetLabel &>(*it);
275 docstring const oldname = lab.getParam("name");
276 lab.updateLabel(oldname);
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) {
289 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
290 // this is necessary to prevent an uninitialized
291 // buffer when the RefInset is in a MathBox.
292 // FIXME audit setBuffer calls
293 mi->setBuffer(const_cast<Buffer &>(buffer));
294 if (mi->getTarget() == oldname)
295 mi->changeTarget(newname);
302 InsetInclude & inc = static_cast<InsetInclude &>(*it);
304 // We need to update the list of included files.
305 cur.forceBufferUpdate();
310 // check for duplicates
311 InsetBibitem & bib = static_cast<InsetBibitem &>(*it);
312 docstring const oldkey = bib.getParam("key");
313 bib.updateCommand(oldkey, false);
314 // We need to update the buffer reference cache.
315 cur.forceBufferUpdate();
316 docstring const newkey = bib.getParam("key");
317 if (oldkey == newkey)
319 // adapt the references
320 for (InsetIterator itt = inset_iterator_begin(in);
321 itt != i_end; ++itt) {
322 if (itt->lyxCode() == CITE_CODE) {
323 InsetCommand * ref = itt->asInsetCommand();
324 if (ref->getParam("key") == oldkey)
325 ref->setParam("key", newkey);
332 // check if branch is known to target buffer
334 InsetBranch & br = static_cast<InsetBranch &>(*it);
335 docstring const name = br.branch();
338 bool const is_child = (&buffer != buffer.masterBuffer());
339 BranchList branchlist = buffer.params().branchlist();
340 if ((!is_child && branchlist.find(name))
341 || (is_child && (branchlist.find(name)
342 || buffer.masterBuffer()->params().branchlist().find(name))))
344 // FIXME: add an option to add the branch to the master's BranchList.
345 docstring text = bformat(
346 _("The pasted branch \"%1$s\" is undefined.\n"
347 "Do you want to add it to the document's branch list?"),
349 if (frontend::Alert::prompt(_("Unknown branch"),
350 text, 0, 1, _("&Add"), _("&Don't Add")) != 0)
352 lyx::dispatch(FuncRequest(LFUN_BRANCH_ADD, name));
353 // We need to update the list of branches.
354 cur.forceBufferUpdate();
362 insertion.swap(in.paragraphs());
364 // Split the paragraph for inserting the buf if necessary.
366 breakParagraphConservative(buffer.params(), pars, pit, pos);
370 pars.insert(boost::next(pars.begin(), pit),
374 // merge the empty par with the last par of the insertion
375 mergeParagraph(buffer.params(), pars,
376 pit + insertion.size() - 1);
378 pars.insert(boost::next(pars.begin(), pit + 1),
382 // merge the first par of the insertion with the current par
383 mergeParagraph(buffer.params(), pars, pit);
386 // Store the new cursor position.
387 pit_type last_paste = pit + insertion.size() - 1;
388 pit_type startpit = pit;
390 pos = pars[last_paste].size();
392 // FIXME Should we do it here, or should we let updateBuffer() do it?
393 // Set paragraph buffers. It's important to do this right away
394 // before something calls Inset::buffer() and causes a crash.
395 for (pit_type p = startpit; p <= pit; ++p)
396 pars[p].setBuffer(const_cast<Buffer &>(buffer));
398 // Join (conditionally) last pasted paragraph with next one, i.e.,
399 // the tail of the spliced document paragraph
400 if (!empty && last_paste + 1 != pit_type(pars.size())) {
401 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
402 mergeParagraph(buffer.params(), pars, last_paste);
403 } else if (pars[last_paste + 1].empty()) {
404 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
405 mergeParagraph(buffer.params(), pars, last_paste);
406 } else if (pars[last_paste].empty()) {
407 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
408 mergeParagraph(buffer.params(), pars, last_paste);
410 pars[last_paste + 1].stripLeadingSpaces(buffer.params().trackChanges);
415 return make_pair(PitPosPair(pit, pos), last_paste + 1);
419 PitPosPair eraseSelectionHelper(BufferParams const & params,
420 ParagraphList & pars,
421 pit_type startpit, pit_type endpit,
422 int startpos, int endpos)
424 // Start of selection is really invalid.
425 if (startpit == pit_type(pars.size()) ||
426 (startpos > pars[startpit].size()))
427 return PitPosPair(endpit, endpos);
429 // Start and end is inside same paragraph
430 if (endpit == pit_type(pars.size()) || startpit == endpit) {
431 endpos -= pars[startpit].eraseChars(startpos, endpos, params.trackChanges);
432 return PitPosPair(endpit, endpos);
435 for (pit_type pit = startpit; pit != endpit + 1;) {
436 pos_type const left = (pit == startpit ? startpos : 0);
437 pos_type right = (pit == endpit ? endpos : pars[pit].size() + 1);
438 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.trackChanges);
440 // Logically erase only, including the end-of-paragraph character
441 pars[pit].eraseChars(left, right, params.trackChanges);
443 // Separate handling of paragraph break:
444 if (merge && pit != endpit &&
446 || pars[pit].hasSameLayout(pars[endpit])
447 || pars[endpit].size() == endpos)) {
448 if (pit + 1 == endpit)
449 endpos += pars[pit].size();
450 mergeParagraph(params, pars, pit);
456 // Ensure legal cursor pos:
459 return PitPosPair(endpit, endpos);
463 void putClipboard(ParagraphList const & paragraphs,
464 DocumentClass const * const docclass, docstring const & plaintext)
466 // For some strange reason gcc 3.2 and 3.3 do not accept
467 // Buffer buffer(string(), false);
468 // This needs to be static to avoid a memory leak. When a Buffer is
469 // constructed, it constructs a BufferParams, which in turn constructs
470 // a DocumentClass, via new, that is never deleted. If we were to go to
471 // some kind of garbage collection there, or a shared_ptr, then this
472 // would not be needed.
473 static Buffer * buffer = theBufferList().newBuffer(
474 FileName::tempName().absFileName() + "_clipboard.internal");
475 buffer->setUnnamed(true);
476 buffer->paragraphs() = paragraphs;
477 buffer->inset().setBuffer(*buffer);
478 buffer->params().setDocumentClass(docclass);
480 if (buffer->write(lyx))
481 theClipboard().put(lyx.str(), plaintext);
483 theClipboard().put(string(), plaintext);
485 buffer->paragraphs().clear();
489 /// return true if the whole ParagraphList is deleted
490 static bool isFullyDeleted(ParagraphList const & pars)
492 pit_type const pars_size = static_cast<pit_type>(pars.size());
494 // check all paragraphs
495 for (pit_type pit = 0; pit < pars_size; ++pit) {
496 if (!pars[pit].empty()) // prevent assertion failure
497 if (!pars[pit].isDeleted(0, pars[pit].size()))
504 void copySelectionHelper(Buffer const & buf, Text const & text,
505 pit_type startpit, pit_type endpit,
506 int start, int end, DocumentClass const * const dc, CutStack & cutstack)
508 ParagraphList const & pars = text.paragraphs();
510 LASSERT(0 <= start && start <= pars[startpit].size(), /**/);
511 LASSERT(0 <= end && end <= pars[endpit].size(), /**/);
512 LASSERT(startpit != endpit || start <= end, /**/);
514 // Clone the paragraphs within the selection.
515 ParagraphList copy_pars(boost::next(pars.begin(), startpit),
516 boost::next(pars.begin(), endpit + 1));
518 // Remove the end of the last paragraph; afterwards, remove the
519 // beginning of the first paragraph. Keep this order - there may only
520 // be one paragraph! Do not track deletions here; this is an internal
521 // action not visible to the user
523 Paragraph & back = copy_pars.back();
524 back.eraseChars(end, back.size(), false);
525 Paragraph & front = copy_pars.front();
526 front.eraseChars(0, start, false);
528 ParagraphList::iterator it = copy_pars.begin();
529 ParagraphList::iterator it_end = copy_pars.end();
531 for (; it != it_end; it++) {
532 // Since we have a copy of the paragraphs, the insets
533 // do not have a proper buffer reference. It makes
534 // sense to add them temporarily, because the
535 // operations below depend on that (acceptChanges included).
536 it->setBuffer(const_cast<Buffer &>(buf));
537 // PassThru paragraphs have the Language
538 // latex_language. This is invalid for others, so we
539 // need to change it to the buffer language.
540 if (it->isPassThru())
541 it->changeLanguage(buf.params(),
542 latex_language, buf.language());
545 // do not copy text (also nested in insets) which is marked as
546 // deleted, unless the whole selection was deleted
547 if (!isFullyDeleted(copy_pars))
548 acceptChanges(copy_pars, buf.params());
550 rejectChanges(copy_pars, buf.params());
553 // do some final cleanup now, to make sure that the paragraphs
554 // are not linked to something else.
555 it = copy_pars.begin();
556 for (; it != it_end; it++) {
557 it->setBuffer(*static_cast<Buffer *>(0));
558 it->setInsetOwner(0);
561 DocumentClass * d = const_cast<DocumentClass *>(dc);
562 cutstack.push(make_pair(copy_pars, d));
572 void region(CursorSlice const & i1, CursorSlice const & i2,
573 Inset::row_type & r1, Inset::row_type & r2,
574 Inset::col_type & c1, Inset::col_type & c2)
576 Inset & p = i1.inset();
577 c1 = p.col(i1.idx());
578 c2 = p.col(i2.idx());
581 r1 = p.row(i1.idx());
582 r2 = p.row(i2.idx());
588 docstring grabAndEraseSelection(Cursor & cur)
590 if (!cur.selection())
592 docstring res = grabSelection(cur);
598 bool reduceSelectionToOneCell(Cursor & cur)
600 if (!cur.selection() || !cur.inMathed())
603 CursorSlice i1 = cur.selBegin();
604 CursorSlice i2 = cur.selEnd();
605 if (!i1.inset().asInsetMath())
608 // the easy case: do nothing if only one cell is selected
609 if (i1.idx() == i2.idx())
614 cur.top().pos() = cur.top().lastpos();
620 bool multipleCellsSelected(Cursor const & cur)
622 if (!cur.selection() || !cur.inMathed())
625 CursorSlice i1 = cur.selBegin();
626 CursorSlice i2 = cur.selEnd();
627 if (!i1.inset().asInsetMath())
630 if (i1.idx() == i2.idx())
637 void switchBetweenClasses(DocumentClass const * const oldone,
638 DocumentClass const * const newone, InsetText & in, ErrorList & errorlist)
642 LASSERT(!in.paragraphs().empty(), /**/);
643 if (oldone == newone)
646 DocumentClass const & oldtc = *oldone;
647 DocumentClass const & newtc = *newone;
650 ParIterator it = par_iterator_begin(in);
651 ParIterator end = par_iterator_end(in);
652 // for remembering which layouts we've had to add
653 set<docstring> newlayouts;
654 for (; it != end; ++it) {
655 docstring const name = it->layout().name();
657 // the pasted text will keep their own layout name. If this layout does
658 // not exist in the new document, it will behave like a standard layout.
659 bool const added_one = newtc.addLayoutIfNeeded(name);
661 newlayouts.insert(name);
663 if (added_one || newlayouts.find(name) != newlayouts.end()) {
665 docstring const s = bformat(_("Layout `%1$s' was not found."), name);
667 ErrorItem(_("Layout Not Found"), s, it->id(), 0, it->size()));
670 if (in.usePlainLayout())
671 it->setLayout(newtc.plainLayout());
673 it->setLayout(newtc[name]);
677 InsetIterator const i_end = inset_iterator_end(in);
678 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
679 if (it->lyxCode() != FLEX_CODE)
680 // FIXME: Should we verify all InsetCollapsable?
683 docstring const layoutName = it->layoutName();
684 docstring const & n = newone->insetLayout(layoutName).name();
685 bool const is_undefined = n.empty() ||
686 n == DocumentClass::plainInsetLayout().name();
690 // The flex inset is undefined in newtc
691 docstring const oldname = from_utf8(oldtc.name());
692 docstring const newname = from_utf8(newtc.name());
694 if (oldname == newname)
695 s = bformat(_("Flex inset %1$s is undefined after "
696 "reloading `%2$s' layout."), layoutName, oldname);
698 s = bformat(_("Flex inset %1$s is undefined because of "
699 "conversion from `%2$s' layout to `%3$s'."),
700 layoutName, oldname, newname);
701 // To warn the user that something had to be done.
702 errorlist.push_back(ErrorItem(
703 _("Undefined flex inset"),
704 s, it.paragraph().id(), it.pos(), it.pos() + 1));
709 vector<docstring> availableSelections(Buffer const * buf)
711 vector<docstring> selList;
715 CutStack::const_iterator cit = theCuts.begin();
716 CutStack::const_iterator end = theCuts.end();
717 for (; cit != end; ++cit) {
718 // we do not use cit-> here because gcc 2.9x does not
720 ParagraphList const & pars = (*cit).first;
722 ParagraphList::const_iterator pit = pars.begin();
723 ParagraphList::const_iterator pend = pars.end();
724 for (; pit != pend; ++pit) {
725 Paragraph par(*pit, 0, 26);
726 // adapt paragraph to current buffer.
727 par.setBuffer(const_cast<Buffer &>(*buf));
728 asciiSel += par.asString(AS_STR_INSETS);
729 if (asciiSel.size() > 25) {
730 asciiSel.replace(22, docstring::npos,
736 selList.push_back(asciiSel);
743 size_type numberOfSelections()
745 return theCuts.size();
749 void cutSelection(Cursor & cur, bool doclear, bool realcut)
751 // This doesn't make sense, if there is no selection
752 if (!cur.selection())
755 // OK, we have a selection. This is always between cur.selBegin()
758 if (cur.inTexted()) {
759 Text * text = cur.text();
764 // make sure that the depth behind the selection are restored, too
765 cur.recordUndoSelection();
766 pit_type begpit = cur.selBegin().pit();
767 pit_type endpit = cur.selEnd().pit();
769 int endpos = cur.selEnd().pos();
771 BufferParams const & bp = cur.buffer()->params();
773 copySelectionHelper(*cur.buffer(),
776 cur.selBegin().pos(), endpos,
777 bp.documentClassPtr(), theCuts);
778 // Stuff what we got on the clipboard.
779 // Even if there is no selection.
780 putClipboard(theCuts[0].first, theCuts[0].second,
781 cur.selectionAsString(true));
784 if (begpit != endpit)
785 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
787 boost::tie(endpit, endpos) =
788 eraseSelectionHelper(bp,
791 cur.selBegin().pos(), endpos);
793 // cutSelection can invalidate the cursor so we need to set
795 // we prefer the end for when tracking changes
799 // sometimes necessary
801 && text->paragraphs()[begpit].stripLeadingSpaces(bp.trackChanges))
804 // need a valid cursor. (Lgb)
805 cur.clearSelection();
807 // After a cut operation, we must make sure that the Buffer is updated
808 // because some further operation might need updated label information for
809 // example. So we cannot just use "cur.forceBufferUpdate()" here.
811 cur.buffer()->updateBuffer();
813 // tell tabular that a recent copy happened
814 dirtyTabularStack(false);
817 if (cur.inMathed()) {
818 if (cur.selBegin().idx() != cur.selEnd().idx()) {
819 // The current selection spans more than one cell.
821 cur.recordUndoInset();
823 // Record only the current cell to avoid a jumping
834 void copySelection(Cursor const & cur)
836 copySelection(cur, cur.selectionAsString(true));
840 void copyInset(Cursor const & cur, Inset * inset, docstring const & plaintext)
844 BufferParams const & bp = cur.buffer()->params();
845 par.setLayout(bp.documentClass().plainLayout());
846 par.insertInset(0, inset, Change(Change::UNCHANGED));
848 theCuts.push(make_pair(pars, bp.documentClassPtr()));
850 // stuff the selection onto the X clipboard, from an explicit copy request
851 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
856 void copySelectionToStack(Cursor const & cur, CutStack & cutstack)
858 // this doesn't make sense, if there is no selection
859 if (!cur.selection())
862 // copySelection can not yet handle the case of cross idx selection
863 if (cur.selBegin().idx() != cur.selEnd().idx())
866 if (cur.inTexted()) {
867 Text * text = cur.text();
869 // ok we have a selection. This is always between cur.selBegin()
870 // and sel_end cursor
872 // copy behind a space if there is one
873 ParagraphList & pars = text->paragraphs();
874 pos_type pos = cur.selBegin().pos();
875 pit_type par = cur.selBegin().pit();
876 while (pos < pars[par].size() &&
877 pars[par].isLineSeparator(pos) &&
878 (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
881 copySelectionHelper(*cur.buffer(), *text, par, cur.selEnd().pit(),
882 pos, cur.selEnd().pos(),
883 cur.buffer()->params().documentClassPtr(), cutstack);
885 // Reset the dirty_tabular_stack_ flag only when something
886 // is copied to the clipboard (not to the selectionBuffer).
887 if (&cutstack == &theCuts)
888 dirtyTabularStack(false);
891 if (cur.inMathed()) {
892 //lyxerr << "copySelection in mathed" << endl;
895 BufferParams const & bp = cur.buffer()->params();
896 // FIXME This should be the plain layout...right?
897 par.setLayout(bp.documentClass().plainLayout());
898 par.insert(0, grabSelection(cur), Font(), Change(Change::UNCHANGED));
900 cutstack.push(make_pair(pars, bp.documentClassPtr()));
907 void copySelectionToStack()
909 if (!selectionBuffer.empty())
910 theCuts.push(selectionBuffer[0]);
914 void copySelection(Cursor const & cur, docstring const & plaintext)
916 // In tablemode, because copy and paste actually use special table stack
917 // we do not attempt to get selected paragraphs under cursor. Instead, a
918 // paragraph with the plain text version is generated so that table cells
919 // can be pasted as pure text somewhere else.
920 if (cur.selBegin().idx() != cur.selEnd().idx()) {
923 BufferParams const & bp = cur.buffer()->params();
924 par.setLayout(bp.documentClass().plainLayout());
925 par.insert(0, plaintext, Font(), Change(Change::UNCHANGED));
927 theCuts.push(make_pair(pars, bp.documentClassPtr()));
929 copySelectionToStack(cur, theCuts);
932 // stuff the selection onto the X clipboard, from an explicit copy request
933 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
937 void saveSelection(Cursor const & cur)
939 // This function is called, not when a selection is formed, but when
940 // a selection is cleared. Therefore, multiple keyboard selection
941 // will not repeatively trigger this function (bug 3877).
943 && cur.selBegin() == cur.bv().cursor().selBegin()
944 && cur.selEnd() == cur.bv().cursor().selEnd()) {
945 LYXERR(Debug::SELECTION, "saveSelection: '" << cur.selectionAsString(true) << "'");
946 copySelectionToStack(cur, selectionBuffer);
953 return !selectionBuffer.empty();
957 void clearSelection()
959 selectionBuffer.clear();
969 docstring selection(size_t sel_index)
971 return sel_index < theCuts.size()
972 ? theCuts[sel_index].first.back().asString(AS_STR_INSETS | AS_STR_NEWLINES)
977 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
978 DocumentClass const * const docclass, ErrorList & errorList)
980 if (cur.inTexted()) {
981 Text * text = cur.text();
987 boost::tie(ppp, endpit) =
988 pasteSelectionHelper(cur, parlist, docclass, errorList);
989 cur.forceBufferUpdate();
990 cur.clearSelection();
991 text->setCursor(cur, ppp.first, ppp.second);
994 // mathed is handled in InsetMathNest/InsetMathGrid
995 LASSERT(!cur.inMathed(), /**/);
999 void pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
1001 // this does not make sense, if there is nothing to paste
1002 if (!checkPastePossible(sel_index))
1006 pasteParagraphList(cur, theCuts[sel_index].first,
1007 theCuts[sel_index].second, errorList);
1012 void pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs)
1014 // Use internal clipboard if it is the most recent one
1015 if (theClipboard().isInternal()) {
1016 pasteFromStack(cur, errorList, 0);
1020 // First try LyX format
1021 if (theClipboard().hasLyXContents()) {
1022 string lyx = theClipboard().getAsLyX();
1024 // For some strange reason gcc 3.2 and 3.3 do not accept
1025 // Buffer buffer(string(), false);
1026 Buffer buffer("", false);
1027 buffer.setUnnamed(true);
1028 if (buffer.readString(lyx)) {
1030 pasteParagraphList(cur, buffer.paragraphs(),
1031 buffer.params().documentClassPtr(), errorList);
1038 // Then try plain text
1039 docstring const text = theClipboard().getAsText();
1044 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1046 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1051 void pasteSimpleText(Cursor & cur, bool asParagraphs)
1054 // Use internal clipboard if it is the most recent one
1055 if (theClipboard().isInternal()) {
1056 if (!checkPastePossible(0))
1059 ParagraphList const & pars = theCuts[0].first;
1060 ParagraphList::const_iterator it = pars.begin();
1061 for (; it != pars.end(); ++it) {
1062 if (it != pars.begin())
1064 text += (*it).asString();
1066 asParagraphs = false;
1068 // Then try plain text
1069 text = theClipboard().getAsText();
1076 cutSelection(cur, true, false);
1078 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1080 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1084 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
1085 Clipboard::GraphicsType preferedType)
1087 LASSERT(theClipboard().hasGraphicsContents(preferedType), /**/);
1089 // get picture from clipboard
1090 FileName filename = theClipboard().getAsGraphics(cur, preferedType);
1091 if (filename.empty())
1094 // create inset for graphic
1095 InsetGraphics * inset = new InsetGraphics(cur.buffer());
1096 InsetGraphicsParams params;
1097 params.filename = support::DocFileName(filename.absFileName(), false);
1098 inset->setParams(params);
1104 void pasteSelection(Cursor & cur, ErrorList & errorList)
1106 if (selectionBuffer.empty())
1109 pasteParagraphList(cur, selectionBuffer[0].first,
1110 selectionBuffer[0].second, errorList);
1114 void replaceSelectionWithString(Cursor & cur, docstring const & str, bool backwards)
1117 DocIterator selbeg = cur.selectionBegin();
1119 // Get font setting before we cut, we need a copy here, not a bare reference.
1121 selbeg.paragraph().getFontSettings(cur.buffer()->params(), selbeg.pos());
1123 // Insert the new string
1124 pos_type pos = cur.selEnd().pos();
1125 Paragraph & par = cur.selEnd().paragraph();
1126 docstring::const_iterator cit = str.begin();
1127 docstring::const_iterator end = str.end();
1128 for (; cit != end; ++cit, ++pos)
1129 par.insertChar(pos, *cit, font, cur.buffer()->params().trackChanges);
1131 // Cut the selection
1132 cutSelection(cur, true, false);
1134 // select the replacement
1136 selbeg.pos() += str.length();
1137 cur.setSelection(selbeg, -int(str.length()));
1139 cur.setSelection(selbeg, str.length());
1143 void replaceSelection(Cursor & cur)
1145 if (cur.selection())
1146 cutSelection(cur, true, false);
1150 void eraseSelection(Cursor & cur)
1152 //lyxerr << "cap::eraseSelection begin: " << cur << endl;
1153 CursorSlice const & i1 = cur.selBegin();
1154 CursorSlice const & i2 = cur.selEnd();
1155 if (i1.inset().asInsetMath()) {
1158 if (i1.idx() == i2.idx()) {
1159 i1.cell().erase(i1.pos(), i2.pos());
1160 // We may have deleted i1.cell(cur.pos()).
1161 // Make sure that pos is valid.
1162 if (cur.pos() > cur.lastpos())
1163 cur.pos() = cur.lastpos();
1165 InsetMath * p = i1.asInsetMath();
1166 Inset::row_type r1, r2;
1167 Inset::col_type c1, c2;
1168 region(i1, i2, r1, r2, c1, c2);
1169 for (Inset::row_type row = r1; row <= r2; ++row)
1170 for (Inset::col_type col = c1; col <= c2; ++col)
1171 p->cell(p->index(row, col)).clear();
1172 // We've deleted the whole cell. Only pos 0 is valid.
1175 // need a valid cursor. (Lgb)
1176 cur.clearSelection();
1178 lyxerr << "can't erase this selection 1" << endl;
1180 //lyxerr << "cap::eraseSelection end: " << cur << endl;
1184 void selDel(Cursor & cur)
1186 //lyxerr << "cap::selDel" << endl;
1187 if (cur.selection())
1188 eraseSelection(cur);
1192 void selClearOrDel(Cursor & cur)
1194 //lyxerr << "cap::selClearOrDel" << endl;
1195 if (lyxrc.auto_region_delete)
1198 cur.setSelection(false);
1202 docstring grabSelection(Cursor const & cur)
1204 if (!cur.selection())
1208 // grab selection by glueing multiple cells together. This is not what
1209 // we want because selections spanning multiple cells will get "&" and "\\"
1212 for (DocIterator dit = cur.selectionBegin();
1213 dit != cur.selectionEnd(); dit.forwardPos())
1214 os << asString(dit.cell());
1218 CursorSlice i1 = cur.selBegin();
1219 CursorSlice i2 = cur.selEnd();
1221 if (i1.idx() == i2.idx()) {
1222 if (i1.inset().asInsetMath()) {
1223 MathData::const_iterator it = i1.cell().begin();
1224 Buffer * buf = cur.buffer();
1225 return asString(MathData(buf, it + i1.pos(), it + i2.pos()));
1227 return from_ascii("unknown selection 1");
1231 Inset::row_type r1, r2;
1232 Inset::col_type c1, c2;
1233 region(i1, i2, r1, r2, c1, c2);
1236 if (i1.inset().asInsetMath()) {
1237 for (Inset::row_type row = r1; row <= r2; ++row) {
1240 for (Inset::col_type col = c1; col <= c2; ++col) {
1243 data += asString(i1.asInsetMath()->
1244 cell(i1.asInsetMath()->index(row, col)));
1248 data = from_ascii("unknown selection 2");
1254 void dirtyTabularStack(bool b)
1256 dirty_tabular_stack_ = b;
1260 bool tabularStackDirty()
1262 return dirty_tabular_stack_;