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 "paragraph_funcs.h"
37 #include "ParagraphParameters.h"
38 #include "ParIterator.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/InsetTabular.h"
49 #include "mathed/MathData.h"
50 #include "mathed/InsetMath.h"
51 #include "mathed/MathSupport.h"
53 #include "support/debug.h"
54 #include "support/docstream.h"
55 #include "support/gettext.h"
56 #include "support/limited_stack.h"
57 #include "support/lstrings.h"
59 #include "frontends/alert.h"
60 #include "frontends/Clipboard.h"
61 #include "frontends/Selection.h"
63 #include <boost/tuple/tuple.hpp>
64 #include <boost/next_prior.hpp>
69 using namespace lyx::support;
70 using lyx::frontend::Clipboard;
76 typedef pair<pit_type, int> PitPosPair;
78 typedef limited_stack<pair<ParagraphList, DocumentClass const *> > CutStack;
81 // persistent selection, cleared until the next selection
82 CutStack selectionBuffer(1);
84 // store whether the tabular stack is newer than the normal copy stack
85 // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
86 // when we (hopefully) have a one-for-all paste mechanism.
87 bool dirty_tabular_stack_ = false;
90 bool checkPastePossible(int index)
92 return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
96 pair<PitPosPair, pit_type>
97 pasteSelectionHelper(Cursor & cur, ParagraphList const & parlist,
98 DocumentClass const * const oldDocClass, ErrorList & errorlist)
100 Buffer const & buffer = *cur.buffer();
101 pit_type pit = cur.pit();
102 pos_type pos = cur.pos();
103 InsetText * target_inset = cur.inset().asInsetText();
105 InsetTabular * it = cur.inset().asInsetTabular();
106 target_inset = it? it->cell(cur.idx())->asInsetText() : 0;
108 LASSERT(target_inset, return make_pair(PitPosPair(pit, pos), pit));
109 ParagraphList & pars = target_inset->paragraphs();
112 return make_pair(PitPosPair(pit, pos), pit);
114 BOOST_ASSERT (pos <= pars[pit].size());
116 // Make a copy of the CaP paragraphs.
117 ParagraphList insertion = parlist;
118 DocumentClass const * const newDocClass =
119 buffer.params().documentClassPtr();
121 // Now remove all out of the pars which is NOT allowed in the
122 // new environment and set also another font if that is required.
124 // Convert newline to paragraph break in ERT inset.
125 // This should not be here!
126 InsetCode const code = target_inset->lyxCode();
127 if (code == ERT_CODE || code == LISTINGS_CODE) {
128 for (size_t i = 0; i != insertion.size(); ++i) {
129 for (pos_type j = 0; j != insertion[i].size(); ++j) {
130 if (insertion[i].isNewline(j)) {
131 // do not track deletion of newline
132 insertion[i].eraseChar(j, false);
133 insertion[i].setInsetOwner(target_inset);
134 breakParagraphConservative(
143 // set the paragraphs to plain layout if necessary
144 if (cur.inset().usePlainLayout()) {
145 bool forcePlainLayout = cur.inset().forcePlainLayout();
146 Layout const & plainLayout = newDocClass->plainLayout();
147 Layout const & defaultLayout = newDocClass->defaultLayout();
148 ParagraphList::iterator const end = insertion.end();
149 ParagraphList::iterator par = insertion.begin();
150 for (; par != end; ++par) {
151 Layout const & parLayout = par->layout();
152 if (forcePlainLayout || parLayout == defaultLayout)
153 par->setLayout(plainLayout);
155 } else { // check if we need to reset from plain layout
156 Layout const & defaultLayout = newDocClass->defaultLayout();
157 Layout const & plainLayout = newDocClass->plainLayout();
158 ParagraphList::iterator const end = insertion.end();
159 ParagraphList::iterator par = insertion.begin();
160 for (; par != end; ++par) {
161 Layout const & parLayout = par->layout();
162 if (parLayout == plainLayout)
163 par->setLayout(defaultLayout);
167 InsetText in(buffer);
168 // Make sure there is no class difference.
169 in.paragraphs().clear();
170 // This works without copying any paragraph data because we have
171 // a specialized swap method for ParagraphList. This is important
172 // since we store pointers to insets at some places and we don't
173 // want to invalidate them.
174 insertion.swap(in.paragraphs());
175 cap::switchBetweenClasses(oldDocClass, newDocClass, in, errorlist);
176 insertion.swap(in.paragraphs());
178 ParagraphList::iterator tmpbuf = insertion.begin();
179 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
181 depth_type max_depth = pars[pit].getMaxDepthAfter();
183 for (; tmpbuf != insertion.end(); ++tmpbuf) {
184 // If we have a negative jump so that the depth would
185 // go below 0 depth then we have to redo the delta to
186 // this new max depth level so that subsequent
187 // paragraphs are aligned correctly to this paragraph
189 if (int(tmpbuf->params().depth()) + depth_delta < 0)
192 // Set the right depth so that we are not too deep or shallow.
193 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
194 if (tmpbuf->params().depth() > max_depth)
195 tmpbuf->params().depth(max_depth);
197 // Only set this from the 2nd on as the 2nd depends
198 // for maxDepth still on pit.
199 if (tmpbuf != insertion.begin())
200 max_depth = tmpbuf->getMaxDepthAfter();
202 // Set the inset owner of this paragraph.
203 tmpbuf->setInsetOwner(target_inset);
204 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
205 // do not track deletion of invalid insets
206 if (Inset * inset = tmpbuf->getInset(i))
207 if (!target_inset->insetAllowed(inset->lyxCode()))
208 tmpbuf->eraseChar(i--, false);
211 tmpbuf->setChange(Change(buffer.params().trackChanges ?
212 Change::INSERTED : Change::UNCHANGED));
215 bool const empty = pars[pit].empty();
217 // Make the buf exactly the same layout as the cursor
219 insertion.begin()->makeSameLayout(pars[pit]);
222 // Prepare the paragraphs and insets for insertion.
223 insertion.swap(in.paragraphs());
225 InsetIterator const i_end = inset_iterator_end(in);
226 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
227 // Even though this will also be done later, it has to be done here
228 // since, e.g., InsetLabel::updateCommand() is going to try to access
229 // the buffer() member.
230 it->setBuffer(const_cast<Buffer &>(buffer));
231 switch (it->lyxCode()) {
234 // check for duplicates
235 InsetCommand & lab = static_cast<InsetCommand &>(*it);
236 docstring const oldname = lab.getParam("name");
237 lab.updateCommand(oldname, false);
238 docstring const newname = lab.getParam("name");
239 if (oldname != newname) {
240 // adapt the references
241 for (InsetIterator itt = inset_iterator_begin(in); itt != i_end; ++itt) {
242 if (itt->lyxCode() == REF_CODE) {
243 InsetCommand & ref = dynamic_cast<InsetCommand &>(*itt);
244 if (ref.getParam("reference") == oldname)
245 ref.setParam("reference", newname);
253 InsetInclude & inc = static_cast<InsetInclude &>(*it);
259 // check for duplicates
260 InsetCommand & bib = static_cast<InsetCommand &>(*it);
261 docstring const oldkey = bib.getParam("key");
262 bib.updateCommand(oldkey, false);
263 docstring const newkey = bib.getParam("key");
264 if (oldkey != newkey) {
265 // adapt the references
266 for (InsetIterator itt = inset_iterator_begin(in); itt != i_end; ++itt) {
267 if (itt->lyxCode() == CITE_CODE) {
268 InsetCommand & ref = dynamic_cast<InsetCommand &>(*itt);
269 if (ref.getParam("key") == oldkey)
270 ref.setParam("key", newkey);
278 // check if branch is known to target buffer
280 InsetBranch & br = static_cast<InsetBranch &>(*it);
281 docstring const name = br.branch();
284 bool const is_child = (&buffer != buffer.masterBuffer());
285 BranchList branchlist = buffer.params().branchlist();
286 if ((!is_child && branchlist.find(name))
287 || (is_child && (branchlist.find(name)
288 || buffer.masterBuffer()->params().branchlist().find(name))))
290 // FIXME: add an option to add the branch to the master's BranchList.
291 docstring text = bformat(
292 _("The pasted branch \"%1$s\" is undefined.\n"
293 "Do you want to add it to the document's branch list?"),
295 if (frontend::Alert::prompt(_("Unknown branch"),
296 text, 0, 1, _("&Add"), _("&Don't Add")) != 0)
298 lyx::dispatch(FuncRequest(LFUN_BRANCH_ADD, name));
306 insertion.swap(in.paragraphs());
308 // Split the paragraph for inserting the buf if necessary.
310 breakParagraphConservative(buffer.params(), pars, pit, pos);
314 pars.insert(boost::next(pars.begin(), pit),
318 // merge the empty par with the last par of the insertion
319 mergeParagraph(buffer.params(), pars,
320 pit + insertion.size() - 1);
322 pars.insert(boost::next(pars.begin(), pit + 1),
326 // merge the first par of the insertion with the current par
327 mergeParagraph(buffer.params(), pars, pit);
330 // Store the new cursor position.
331 pit_type last_paste = pit + insertion.size() - 1;
332 pit_type startpit = pit;
334 pos = pars[last_paste].size();
336 // FIXME Should we do it here, or should we let updateLabels() do it?
337 // Set paragraph buffers. It's important to do this right away
338 // before something calls Inset::buffer() and causes a crash.
339 for (pit_type p = startpit; p <= pit; ++p)
340 pars[p].setBuffer(const_cast<Buffer &>(buffer));
342 // Join (conditionally) last pasted paragraph with next one, i.e.,
343 // the tail of the spliced document paragraph
344 if (!empty && last_paste + 1 != pit_type(pars.size())) {
345 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
346 mergeParagraph(buffer.params(), pars, last_paste);
347 } else if (pars[last_paste + 1].empty()) {
348 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
349 mergeParagraph(buffer.params(), pars, last_paste);
350 } else if (pars[last_paste].empty()) {
351 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
352 mergeParagraph(buffer.params(), pars, last_paste);
354 pars[last_paste + 1].stripLeadingSpaces(buffer.params().trackChanges);
359 return make_pair(PitPosPair(pit, pos), last_paste + 1);
363 PitPosPair eraseSelectionHelper(BufferParams const & params,
364 ParagraphList & pars,
365 pit_type startpit, pit_type endpit,
366 int startpos, int endpos)
368 // Start of selection is really invalid.
369 if (startpit == pit_type(pars.size()) ||
370 (startpos > pars[startpit].size()))
371 return PitPosPair(endpit, endpos);
373 // Start and end is inside same paragraph
374 if (endpit == pit_type(pars.size()) || startpit == endpit) {
375 endpos -= pars[startpit].eraseChars(startpos, endpos, params.trackChanges);
376 return PitPosPair(endpit, endpos);
379 for (pit_type pit = startpit; pit != endpit + 1;) {
380 pos_type const left = (pit == startpit ? startpos : 0);
381 pos_type right = (pit == endpit ? endpos : pars[pit].size() + 1);
382 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.trackChanges);
384 // Logically erase only, including the end-of-paragraph character
385 pars[pit].eraseChars(left, right, params.trackChanges);
387 // Separate handling of paragraph break:
388 if (merge && pit != endpit &&
390 || pars[pit].hasSameLayout(pars[endpit])
391 || pars[endpit].size() == endpos)) {
392 if (pit + 1 == endpit)
393 endpos += pars[pit].size();
394 mergeParagraph(params, pars, pit);
400 // Ensure legal cursor pos:
403 return PitPosPair(endpit, endpos);
407 void putClipboard(ParagraphList const & paragraphs,
408 DocumentClass const * const docclass, docstring const & plaintext)
410 // For some strange reason gcc 3.2 and 3.3 do not accept
411 // Buffer buffer(string(), false);
412 // This needs to be static to avoid a memory leak. When a Buffer is
413 // constructed, it constructs a BufferParams, which in turn constructs
414 // a DocumentClass, via new, that is never deleted. If we were to go to
415 // some kind of garbage collection there, or a shared_ptr, then this
416 // would not be needed.
417 static Buffer * buffer = theBufferList().newBuffer(
418 FileName::tempName().absFilename() + "_clipboard.internal");
419 buffer->setUnnamed(true);
420 buffer->paragraphs() = paragraphs;
421 buffer->inset().setBuffer(*buffer);
422 buffer->params().setDocumentClass(docclass);
424 if (buffer->write(lyx))
425 theClipboard().put(lyx.str(), plaintext);
427 theClipboard().put(string(), plaintext);
429 buffer->paragraphs().clear();
433 void copySelectionHelper(Buffer const & buf, ParagraphList const & pars,
434 pit_type startpit, pit_type endpit,
435 int start, int end, DocumentClass const * const dc, CutStack & cutstack)
437 LASSERT(0 <= start && start <= pars[startpit].size(), /**/);
438 LASSERT(0 <= end && end <= pars[endpit].size(), /**/);
439 LASSERT(startpit != endpit || start <= end, /**/);
441 // Clone the paragraphs within the selection.
442 ParagraphList copy_pars(boost::next(pars.begin(), startpit),
443 boost::next(pars.begin(), endpit + 1));
445 // Remove the end of the last paragraph; afterwards, remove the
446 // beginning of the first paragraph. Keep this order - there may only
447 // be one paragraph! Do not track deletions here; this is an internal
448 // action not visible to the user
450 Paragraph & back = copy_pars.back();
451 back.eraseChars(end, back.size(), false);
452 Paragraph & front = copy_pars.front();
453 front.eraseChars(0, start, false);
455 ParagraphList::iterator it = copy_pars.begin();
456 ParagraphList::iterator it_end = copy_pars.end();
458 for (; it != it_end; it++) {
459 // Since we have a copy of the paragraphs, the insets
460 // do not have a proper buffer reference. It makes
461 // sense to add them temporarily, because the
462 // operations below depend on that (acceptChanges included).
463 it->setBuffer(const_cast<Buffer &>(buf));
464 // PassThru paragraphs have the Language
465 // latex_language. This is invalid for others, so we
466 // need to change it to the buffer language.
467 if (it->inInset().getLayout().isPassThru())
468 it->changeLanguage(buf.params(),
469 latex_language, buf.language());
472 // do not copy text (also nested in insets) which is marked as
473 // deleted, unless the whole selection was deleted
474 if (!isFullyDeleted(copy_pars))
475 acceptChanges(copy_pars, buf.params());
478 // do some final cleanup now, to make sure that the paragraphs
479 // are not linked to something else.
480 it = copy_pars.begin();
481 for (; it != it_end; it++) {
482 it->setBuffer(*static_cast<Buffer *>(0));
483 it->setInsetOwner(0);
486 DocumentClass * d = const_cast<DocumentClass *>(dc);
487 cutstack.push(make_pair(copy_pars, d));
497 void region(CursorSlice const & i1, CursorSlice const & i2,
498 Inset::row_type & r1, Inset::row_type & r2,
499 Inset::col_type & c1, Inset::col_type & c2)
501 Inset & p = i1.inset();
502 c1 = p.col(i1.idx());
503 c2 = p.col(i2.idx());
506 r1 = p.row(i1.idx());
507 r2 = p.row(i2.idx());
513 docstring grabAndEraseSelection(Cursor & cur)
515 if (!cur.selection())
517 docstring res = grabSelection(cur);
523 bool reduceSelectionToOneCell(Cursor & cur)
525 if (!cur.selection() || !cur.inMathed())
528 CursorSlice i1 = cur.selBegin();
529 CursorSlice i2 = cur.selEnd();
530 if (!i1.inset().asInsetMath())
533 // the easy case: do nothing if only one cell is selected
534 if (i1.idx() == i2.idx())
539 cur.top().pos() = cur.top().lastpos();
545 bool multipleCellsSelected(Cursor const & cur)
547 if (!cur.selection() || !cur.inMathed())
550 CursorSlice i1 = cur.selBegin();
551 CursorSlice i2 = cur.selEnd();
552 if (!i1.inset().asInsetMath())
555 if (i1.idx() == i2.idx())
562 void switchBetweenClasses(DocumentClass const * const oldone,
563 DocumentClass const * const newone, InsetText & in, ErrorList & errorlist)
567 LASSERT(!in.paragraphs().empty(), /**/);
568 if (oldone == newone)
571 DocumentClass const & oldtc = *oldone;
572 DocumentClass const & newtc = *newone;
575 ParIterator end = par_iterator_end(in);
576 for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
577 docstring const name = it->layout().name();
579 // the pasted text will keep their own layout name. If this layout does
580 // not exist in the new document, it will behave like a standard layout.
581 newtc.addLayoutIfNeeded(name);
583 if (in.usePlainLayout())
584 it->setLayout(newtc.plainLayout());
586 it->setLayout(newtc[name]);
590 InsetIterator const i_end = inset_iterator_end(in);
591 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
592 if (it->lyxCode() != FLEX_CODE)
593 // FIXME: Should we verify all InsetCollapsable?
595 if (!it->undefined())
597 // The flex inset is undefined in newtc
598 docstring const s = bformat(_(
599 "Flex inset %1$s is "
600 "undefined because of class "
601 "conversion from\n%2$s to %3$s"),
602 it->name(), from_utf8(oldtc.name()),
603 from_utf8(newtc.name()));
604 // To warn the user that something had to be done.
605 errorlist.push_back(ErrorItem(
606 _("Undefined flex inset"),
607 s, it.paragraph().id(), it.pos(), it.pos() + 1));
612 vector<docstring> availableSelections(Buffer const * buf)
614 vector<docstring> selList;
618 CutStack::const_iterator cit = theCuts.begin();
619 CutStack::const_iterator end = theCuts.end();
620 for (; cit != end; ++cit) {
621 // we do not use cit-> here because gcc 2.9x does not
623 ParagraphList const & pars = (*cit).first;
625 ParagraphList::const_iterator pit = pars.begin();
626 ParagraphList::const_iterator pend = pars.end();
627 for (; pit != pend; ++pit) {
628 Paragraph par(*pit, 0, 26);
629 // adapt paragraph to current buffer.
630 par.setBuffer(const_cast<Buffer &>(*buf));
631 asciiSel += par.asString(AS_STR_INSETS);
632 if (asciiSel.size() > 25) {
633 asciiSel.replace(22, docstring::npos,
639 selList.push_back(asciiSel);
646 size_type numberOfSelections()
648 return theCuts.size();
652 void cutSelection(Cursor & cur, bool doclear, bool realcut)
654 // This doesn't make sense, if there is no selection
655 if (!cur.selection())
658 // OK, we have a selection. This is always between cur.selBegin()
661 if (cur.inTexted()) {
662 Text * text = cur.text();
667 // make sure that the depth behind the selection are restored, too
668 cur.recordUndoSelection();
669 pit_type begpit = cur.selBegin().pit();
670 pit_type endpit = cur.selEnd().pit();
672 int endpos = cur.selEnd().pos();
674 BufferParams const & bp = cur.buffer()->params();
676 copySelectionHelper(*cur.buffer(),
679 cur.selBegin().pos(), endpos,
680 bp.documentClassPtr(), theCuts);
681 // Stuff what we got on the clipboard.
682 // Even if there is no selection.
683 putClipboard(theCuts[0].first, theCuts[0].second,
684 cur.selectionAsString(true));
687 if (begpit != endpit)
688 cur.updateFlags(Update::Force | Update::FitCursor);
690 boost::tie(endpit, endpos) =
691 eraseSelectionHelper(bp,
694 cur.selBegin().pos(), endpos);
696 // cutSelection can invalidate the cursor so we need to set
698 // we prefer the end for when tracking changes
702 // sometimes necessary
704 && text->paragraphs()[begpit].stripLeadingSpaces(bp.trackChanges))
707 // need a valid cursor. (Lgb)
708 cur.clearSelection();
709 cur.buffer()->updateLabels();
711 // tell tabular that a recent copy happened
712 dirtyTabularStack(false);
715 if (cur.inMathed()) {
716 if (cur.selBegin().idx() != cur.selEnd().idx()) {
717 // The current selection spans more than one cell.
719 cur.recordUndoInset();
721 // Record only the current cell to avoid a jumping
732 void copySelection(Cursor const & cur)
734 copySelection(cur, cur.selectionAsString(true));
738 void copyInset(Cursor const & cur, Inset * inset, docstring const & plaintext)
742 BufferParams const & bp = cur.buffer()->params();
743 par.setLayout(bp.documentClass().plainLayout());
744 par.insertInset(0, inset, Change(Change::UNCHANGED));
746 theCuts.push(make_pair(pars, bp.documentClassPtr()));
748 // stuff the selection onto the X clipboard, from an explicit copy request
749 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
754 void copySelectionToStack(Cursor const & cur, CutStack & cutstack)
756 // this doesn't make sense, if there is no selection
757 if (!cur.selection())
760 // copySelection can not yet handle the case of cross idx selection
761 if (cur.selBegin().idx() != cur.selEnd().idx())
764 if (cur.inTexted()) {
765 Text * text = cur.text();
767 // ok we have a selection. This is always between cur.selBegin()
768 // and sel_end cursor
770 // copy behind a space if there is one
771 ParagraphList & pars = text->paragraphs();
772 pos_type pos = cur.selBegin().pos();
773 pit_type par = cur.selBegin().pit();
774 while (pos < pars[par].size() &&
775 pars[par].isLineSeparator(pos) &&
776 (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
779 copySelectionHelper(*cur.buffer(), pars, par, cur.selEnd().pit(),
780 pos, cur.selEnd().pos(),
781 cur.buffer()->params().documentClassPtr(), cutstack);
783 // Reset the dirty_tabular_stack_ flag only when something
784 // is copied to the clipboard (not to the selectionBuffer).
785 if (&cutstack == &theCuts)
786 dirtyTabularStack(false);
789 if (cur.inMathed()) {
790 //lyxerr << "copySelection in mathed" << endl;
793 BufferParams const & bp = cur.buffer()->params();
794 // FIXME This should be the plain layout...right?
795 par.setLayout(bp.documentClass().plainLayout());
796 par.insert(0, grabSelection(cur), Font(), Change(Change::UNCHANGED));
798 cutstack.push(make_pair(pars, bp.documentClassPtr()));
805 void copySelectionToStack()
807 if (!selectionBuffer.empty())
808 theCuts.push(selectionBuffer[0]);
812 void copySelection(Cursor const & cur, docstring const & plaintext)
814 // In tablemode, because copy and paste actually use special table stack
815 // we do not attempt to get selected paragraphs under cursor. Instead, a
816 // paragraph with the plain text version is generated so that table cells
817 // can be pasted as pure text somewhere else.
818 if (cur.selBegin().idx() != cur.selEnd().idx()) {
821 BufferParams const & bp = cur.buffer()->params();
822 par.setLayout(bp.documentClass().plainLayout());
823 par.insert(0, plaintext, Font(), Change(Change::UNCHANGED));
825 theCuts.push(make_pair(pars, bp.documentClassPtr()));
827 copySelectionToStack(cur, theCuts);
830 // stuff the selection onto the X clipboard, from an explicit copy request
831 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
835 void saveSelection(Cursor const & cur)
837 // This function is called, not when a selection is formed, but when
838 // a selection is cleared. Therefore, multiple keyboard selection
839 // will not repeatively trigger this function (bug 3877).
841 && cur.selBegin() == cur.bv().cursor().selBegin()
842 && cur.selEnd() == cur.bv().cursor().selEnd()) {
843 LYXERR(Debug::SELECTION, "saveSelection: '" << cur.selectionAsString(true) << "'");
844 copySelectionToStack(cur, selectionBuffer);
851 return !selectionBuffer.empty();
855 void clearSelection()
857 selectionBuffer.clear();
867 docstring selection(size_t sel_index)
869 return sel_index < theCuts.size()
870 ? theCuts[sel_index].first.back().asString(AS_STR_INSETS | AS_STR_NEWLINES)
875 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
876 DocumentClass const * const docclass, ErrorList & errorList)
878 if (cur.inTexted()) {
879 Text * text = cur.text();
885 boost::tie(ppp, endpit) =
886 pasteSelectionHelper(cur, parlist, docclass, errorList);
887 cur.buffer()->updateLabels();
888 cur.clearSelection();
889 text->setCursor(cur, ppp.first, ppp.second);
892 // mathed is handled in InsetMathNest/InsetMathGrid
893 LASSERT(!cur.inMathed(), /**/);
897 void pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
899 // this does not make sense, if there is nothing to paste
900 if (!checkPastePossible(sel_index))
904 pasteParagraphList(cur, theCuts[sel_index].first,
905 theCuts[sel_index].second, errorList);
910 void pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs)
912 // Use internal clipboard if it is the most recent one
913 if (theClipboard().isInternal()) {
914 pasteFromStack(cur, errorList, 0);
918 // First try LyX format
919 if (theClipboard().hasLyXContents()) {
920 string lyx = theClipboard().getAsLyX();
922 // For some strange reason gcc 3.2 and 3.3 do not accept
923 // Buffer buffer(string(), false);
924 Buffer buffer("", false);
925 buffer.setUnnamed(true);
926 if (buffer.readString(lyx)) {
928 pasteParagraphList(cur, buffer.paragraphs(),
929 buffer.params().documentClassPtr(), errorList);
936 // Then try plain text
937 docstring const text = theClipboard().getAsText();
942 cur.text()->insertStringAsParagraphs(cur, text);
944 cur.text()->insertStringAsLines(cur, text);
948 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
949 Clipboard::GraphicsType preferedType)
951 LASSERT(theClipboard().hasGraphicsContents(preferedType), /**/);
953 // get picture from clipboard
954 FileName filename = theClipboard().getAsGraphics(cur, preferedType);
955 if (filename.empty())
958 // create inset for graphic
959 InsetGraphics * inset = new InsetGraphics(*cur.buffer());
960 InsetGraphicsParams params;
961 params.filename = support::DocFileName(filename.absFilename());
962 inset->setParams(params);
968 void pasteSelection(Cursor & cur, ErrorList & errorList)
970 if (selectionBuffer.empty())
973 pasteParagraphList(cur, selectionBuffer[0].first,
974 selectionBuffer[0].second, errorList);
978 void replaceSelectionWithString(Cursor & cur, docstring const & str, bool backwards)
981 DocIterator selbeg = cur.selectionBegin();
983 // Get font setting before we cut, we need a copy here, not a bare reference.
985 selbeg.paragraph().getFontSettings(cur.buffer()->params(), selbeg.pos());
987 // Insert the new string
988 pos_type pos = cur.selEnd().pos();
989 Paragraph & par = cur.selEnd().paragraph();
990 docstring::const_iterator cit = str.begin();
991 docstring::const_iterator end = str.end();
992 for (; cit != end; ++cit, ++pos)
993 par.insertChar(pos, *cit, font, cur.buffer()->params().trackChanges);
996 cutSelection(cur, true, false);
998 // select the replacement
1000 selbeg.pos() += str.length();
1001 cur.setSelection(selbeg, -int(str.length()));
1003 cur.setSelection(selbeg, str.length());
1007 void replaceSelection(Cursor & cur)
1009 if (cur.selection())
1010 cutSelection(cur, true, false);
1014 void eraseSelection(Cursor & cur)
1016 //lyxerr << "cap::eraseSelection begin: " << cur << endl;
1017 CursorSlice const & i1 = cur.selBegin();
1018 CursorSlice const & i2 = cur.selEnd();
1019 if (i1.inset().asInsetMath()) {
1022 if (i1.idx() == i2.idx()) {
1023 i1.cell().erase(i1.pos(), i2.pos());
1024 // We may have deleted i1.cell(cur.pos()).
1025 // Make sure that pos is valid.
1026 if (cur.pos() > cur.lastpos())
1027 cur.pos() = cur.lastpos();
1029 InsetMath * p = i1.asInsetMath();
1030 Inset::row_type r1, r2;
1031 Inset::col_type c1, c2;
1032 region(i1, i2, r1, r2, c1, c2);
1033 for (Inset::row_type row = r1; row <= r2; ++row)
1034 for (Inset::col_type col = c1; col <= c2; ++col)
1035 p->cell(p->index(row, col)).clear();
1036 // We've deleted the whole cell. Only pos 0 is valid.
1039 // need a valid cursor. (Lgb)
1040 cur.clearSelection();
1042 lyxerr << "can't erase this selection 1" << endl;
1044 //lyxerr << "cap::eraseSelection end: " << cur << endl;
1048 void selDel(Cursor & cur)
1050 //lyxerr << "cap::selDel" << endl;
1051 if (cur.selection())
1052 eraseSelection(cur);
1056 void selClearOrDel(Cursor & cur)
1058 //lyxerr << "cap::selClearOrDel" << endl;
1059 if (lyxrc.auto_region_delete)
1062 cur.setSelection(false);
1066 docstring grabSelection(Cursor const & cur)
1068 if (!cur.selection())
1072 // grab selection by glueing multiple cells together. This is not what
1073 // we want because selections spanning multiple cells will get "&" and "\\"
1076 for (DocIterator dit = cur.selectionBegin();
1077 dit != cur.selectionEnd(); dit.forwardPos())
1078 os << asString(dit.cell());
1082 CursorSlice i1 = cur.selBegin();
1083 CursorSlice i2 = cur.selEnd();
1085 if (i1.idx() == i2.idx()) {
1086 if (i1.inset().asInsetMath()) {
1087 MathData::const_iterator it = i1.cell().begin();
1088 return asString(MathData(it + i1.pos(), it + i2.pos()));
1090 return from_ascii("unknown selection 1");
1094 Inset::row_type r1, r2;
1095 Inset::col_type c1, c2;
1096 region(i1, i2, r1, r2, c1, c2);
1099 if (i1.inset().asInsetMath()) {
1100 for (Inset::row_type row = r1; row <= r2; ++row) {
1103 for (Inset::col_type col = c1; col <= c2; ++col) {
1106 data += asString(i1.asInsetMath()->
1107 cell(i1.asInsetMath()->index(row, col)));
1111 data = from_ascii("unknown selection 2");
1117 void dirtyTabularStack(bool b)
1119 dirty_tabular_stack_ = b;
1123 bool tabularStackDirty()
1125 return dirty_tabular_stack_;