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/InsetTabular.h"
48 #include "mathed/MathData.h"
49 #include "mathed/InsetMath.h"
50 #include "mathed/MathSupport.h"
52 #include "support/debug.h"
53 #include "support/docstream.h"
54 #include "support/gettext.h"
55 #include "support/limited_stack.h"
56 #include "support/lstrings.h"
58 #include "frontends/alert.h"
59 #include "frontends/Clipboard.h"
60 #include "frontends/Selection.h"
62 #include <boost/tuple/tuple.hpp>
63 #include <boost/next_prior.hpp>
68 using namespace lyx::support;
69 using lyx::frontend::Clipboard;
75 typedef pair<pit_type, int> PitPosPair;
77 typedef limited_stack<pair<ParagraphList, DocumentClass const *> > CutStack;
80 // persistent selection, cleared until the next selection
81 CutStack selectionBuffer(1);
83 // store whether the tabular stack is newer than the normal copy stack
84 // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
85 // when we (hopefully) have a one-for-all paste mechanism.
86 bool dirty_tabular_stack_ = false;
89 bool checkPastePossible(int index)
91 return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
95 pair<PitPosPair, pit_type>
96 pasteSelectionHelper(Cursor & cur, ParagraphList const & parlist,
97 DocumentClass const * const oldDocClass, ErrorList & errorlist)
99 Buffer const & buffer = *cur.buffer();
100 pit_type pit = cur.pit();
101 pos_type pos = cur.pos();
102 InsetText * target_inset = cur.inset().asInsetText();
104 InsetTabular * it = cur.inset().asInsetTabular();
105 target_inset = it? it->cell(cur.idx())->asInsetText() : 0;
107 LASSERT(target_inset, return make_pair(PitPosPair(pit, pos), pit));
108 ParagraphList & pars = target_inset->paragraphs();
111 return make_pair(PitPosPair(pit, pos), pit);
113 BOOST_ASSERT (pos <= pars[pit].size());
115 // Make a copy of the CaP paragraphs.
116 ParagraphList insertion = parlist;
117 DocumentClass const * const newDocClass =
118 buffer.params().documentClassPtr();
120 // Now remove all out of the pars which is NOT allowed in the
121 // new environment and set also another font if that is required.
123 // Convert newline to paragraph break in ERT inset.
124 // This should not be here!
125 InsetCode const code = target_inset->lyxCode();
126 if (code == ERT_CODE || code == LISTINGS_CODE) {
127 for (size_t i = 0; i != insertion.size(); ++i) {
128 for (pos_type j = 0; j != insertion[i].size(); ++j) {
129 if (insertion[i].isNewline(j)) {
130 // do not track deletion of newline
131 insertion[i].eraseChar(j, false);
132 insertion[i].setInsetOwner(target_inset);
133 breakParagraphConservative(
142 // set the paragraphs to plain layout if necessary
143 if (cur.inset().usePlainLayout()) {
144 bool forcePlainLayout = cur.inset().forcePlainLayout();
145 Layout const & plainLayout = newDocClass->plainLayout();
146 Layout const & defaultLayout = newDocClass->defaultLayout();
147 ParagraphList::iterator const end = insertion.end();
148 ParagraphList::iterator par = insertion.begin();
149 for (; par != end; ++par) {
150 Layout const & parLayout = par->layout();
151 if (forcePlainLayout || parLayout == defaultLayout)
152 par->setLayout(plainLayout);
154 } else { // check if we need to reset from plain layout
155 Layout const & defaultLayout = newDocClass->defaultLayout();
156 Layout const & plainLayout = newDocClass->plainLayout();
157 ParagraphList::iterator const end = insertion.end();
158 ParagraphList::iterator par = insertion.begin();
159 for (; par != end; ++par) {
160 Layout const & parLayout = par->layout();
161 if (parLayout == plainLayout)
162 par->setLayout(defaultLayout);
166 InsetText in(buffer);
167 // Make sure there is no class difference.
168 in.paragraphs().clear();
169 // This works without copying any paragraph data because we have
170 // a specialized swap method for ParagraphList. This is important
171 // since we store pointers to insets at some places and we don't
172 // want to invalidate them.
173 insertion.swap(in.paragraphs());
174 cap::switchBetweenClasses(oldDocClass, newDocClass, in, errorlist);
175 insertion.swap(in.paragraphs());
177 ParagraphList::iterator tmpbuf = insertion.begin();
178 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
180 depth_type max_depth = pars[pit].getMaxDepthAfter();
182 for (; tmpbuf != insertion.end(); ++tmpbuf) {
183 // If we have a negative jump so that the depth would
184 // go below 0 depth then we have to redo the delta to
185 // this new max depth level so that subsequent
186 // paragraphs are aligned correctly to this paragraph
188 if (int(tmpbuf->params().depth()) + depth_delta < 0)
191 // Set the right depth so that we are not too deep or shallow.
192 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
193 if (tmpbuf->params().depth() > max_depth)
194 tmpbuf->params().depth(max_depth);
196 // Only set this from the 2nd on as the 2nd depends
197 // for maxDepth still on pit.
198 if (tmpbuf != insertion.begin())
199 max_depth = tmpbuf->getMaxDepthAfter();
201 // Set the inset owner of this paragraph.
202 tmpbuf->setInsetOwner(target_inset);
203 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
204 // do not track deletion of invalid insets
205 if (Inset * inset = tmpbuf->getInset(i))
206 if (!target_inset->insetAllowed(inset->lyxCode()))
207 tmpbuf->eraseChar(i--, false);
210 tmpbuf->setChange(Change(buffer.params().trackChanges ?
211 Change::INSERTED : Change::UNCHANGED));
214 bool const empty = pars[pit].empty();
216 // Make the buf exactly the same layout as the cursor
218 insertion.begin()->makeSameLayout(pars[pit]);
221 // Prepare the paragraphs and insets for insertion.
222 insertion.swap(in.paragraphs());
224 InsetIterator const i_end = inset_iterator_end(in);
225 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
226 // Even though this will also be done later, it has to be done here
227 // since, e.g., InsetLabel::updateCommand() is going to try to access
228 // the buffer() member.
229 it->setBuffer(const_cast<Buffer &>(buffer));
230 switch (it->lyxCode()) {
233 // check for duplicates
234 InsetCommand & lab = static_cast<InsetCommand &>(*it);
235 docstring const oldname = lab.getParam("name");
236 lab.updateCommand(oldname, false);
237 docstring const newname = lab.getParam("name");
238 if (oldname != newname) {
239 // adapt the references
240 for (InsetIterator itt = inset_iterator_begin(in); itt != i_end; ++itt) {
241 if (itt->lyxCode() == REF_CODE) {
242 InsetCommand & ref = dynamic_cast<InsetCommand &>(*itt);
243 if (ref.getParam("reference") == oldname)
244 ref.setParam("reference", newname);
252 InsetInclude & inc = static_cast<InsetInclude &>(*it);
258 // check for duplicates
259 InsetCommand & bib = static_cast<InsetCommand &>(*it);
260 docstring const oldkey = bib.getParam("key");
261 bib.updateCommand(oldkey, false);
262 docstring const newkey = bib.getParam("key");
263 if (oldkey != newkey) {
264 // adapt the references
265 for (InsetIterator itt = inset_iterator_begin(in); itt != i_end; ++itt) {
266 if (itt->lyxCode() == CITE_CODE) {
267 InsetCommand & ref = dynamic_cast<InsetCommand &>(*itt);
268 if (ref.getParam("key") == oldkey)
269 ref.setParam("key", newkey);
277 // check if branch is known to target buffer
279 InsetBranch & br = static_cast<InsetBranch &>(*it);
280 docstring const name = br.branch();
283 bool const is_child = (&buffer != buffer.masterBuffer());
284 BranchList branchlist = buffer.params().branchlist();
285 if ((!is_child && branchlist.find(name))
286 || (is_child && (branchlist.find(name)
287 || buffer.masterBuffer()->params().branchlist().find(name))))
289 // FIXME: add an option to add the branch to the master's BranchList.
290 docstring text = bformat(
291 _("The pasted branch \"%1$s\" is undefined.\n"
292 "Do you want to add it to the document's branch list?"),
294 if (frontend::Alert::prompt(_("Unknown branch"),
295 text, 0, 1, _("&Add"), _("&Don't Add")) != 0)
297 lyx::dispatch(FuncRequest(LFUN_BRANCH_ADD, name));
305 insertion.swap(in.paragraphs());
307 // Split the paragraph for inserting the buf if necessary.
309 breakParagraphConservative(buffer.params(), pars, pit, pos);
313 pars.insert(boost::next(pars.begin(), pit),
317 // merge the empty par with the last par of the insertion
318 mergeParagraph(buffer.params(), pars,
319 pit + insertion.size() - 1);
321 pars.insert(boost::next(pars.begin(), pit + 1),
325 // merge the first par of the insertion with the current par
326 mergeParagraph(buffer.params(), pars, pit);
329 // Store the new cursor position.
330 pit_type last_paste = pit + insertion.size() - 1;
331 pit_type startpit = pit;
333 pos = pars[last_paste].size();
335 // FIXME Should we do it here, or should we let updateLabels() do it?
336 // Set paragraph buffers. It's important to do this right away
337 // before something calls Inset::buffer() and causes a crash.
338 for (pit_type p = startpit; p <= pit; ++p)
339 pars[p].setBuffer(const_cast<Buffer &>(buffer));
341 // Join (conditionally) last pasted paragraph with next one, i.e.,
342 // the tail of the spliced document paragraph
343 if (!empty && last_paste + 1 != pit_type(pars.size())) {
344 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
345 mergeParagraph(buffer.params(), pars, last_paste);
346 } else if (pars[last_paste + 1].empty()) {
347 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
348 mergeParagraph(buffer.params(), pars, last_paste);
349 } else if (pars[last_paste].empty()) {
350 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
351 mergeParagraph(buffer.params(), pars, last_paste);
353 pars[last_paste + 1].stripLeadingSpaces(buffer.params().trackChanges);
358 return make_pair(PitPosPair(pit, pos), last_paste + 1);
362 PitPosPair eraseSelectionHelper(BufferParams const & params,
363 ParagraphList & pars,
364 pit_type startpit, pit_type endpit,
365 int startpos, int endpos)
367 // Start of selection is really invalid.
368 if (startpit == pit_type(pars.size()) ||
369 (startpos > pars[startpit].size()))
370 return PitPosPair(endpit, endpos);
372 // Start and end is inside same paragraph
373 if (endpit == pit_type(pars.size()) || startpit == endpit) {
374 endpos -= pars[startpit].eraseChars(startpos, endpos, params.trackChanges);
375 return PitPosPair(endpit, endpos);
378 for (pit_type pit = startpit; pit != endpit + 1;) {
379 pos_type const left = (pit == startpit ? startpos : 0);
380 pos_type right = (pit == endpit ? endpos : pars[pit].size() + 1);
381 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.trackChanges);
383 // Logically erase only, including the end-of-paragraph character
384 pars[pit].eraseChars(left, right, params.trackChanges);
386 // Separate handling of paragraph break:
387 if (merge && pit != endpit &&
389 || pars[pit].hasSameLayout(pars[endpit])
390 || pars[endpit].size() == endpos)) {
391 if (pit + 1 == endpit)
392 endpos += pars[pit].size();
393 mergeParagraph(params, pars, pit);
399 // Ensure legal cursor pos:
402 return PitPosPair(endpit, endpos);
406 void putClipboard(ParagraphList const & paragraphs,
407 DocumentClass const * const docclass, docstring const & plaintext)
409 // For some strange reason gcc 3.2 and 3.3 do not accept
410 // Buffer buffer(string(), false);
411 // This needs to be static to avoid a memory leak. When a Buffer is
412 // constructed, it constructs a BufferParams, which in turn constructs
413 // a DocumentClass, via new, that is never deleted. If we were to go to
414 // some kind of garbage collection there, or a shared_ptr, then this
415 // would not be needed.
416 static Buffer * buffer = theBufferList().newBuffer(
417 FileName::tempName().absFilename() + "_clipboard.internal");
418 buffer->setUnnamed(true);
419 buffer->paragraphs() = paragraphs;
420 buffer->inset().setBuffer(*buffer);
421 buffer->params().setDocumentClass(docclass);
423 if (buffer->write(lyx))
424 theClipboard().put(lyx.str(), plaintext);
426 theClipboard().put(string(), plaintext);
428 buffer->paragraphs().clear();
432 void copySelectionHelper(Buffer const & buf, Text const & text,
433 pit_type startpit, pit_type endpit,
434 int start, int end, DocumentClass const * const dc, CutStack & cutstack)
436 ParagraphList const & pars = text.paragraphs();
438 LASSERT(0 <= start && start <= pars[startpit].size(), /**/);
439 LASSERT(0 <= end && end <= pars[endpit].size(), /**/);
440 LASSERT(startpit != endpit || start <= end, /**/);
442 // Clone the paragraphs within the selection.
443 ParagraphList copy_pars(boost::next(pars.begin(), startpit),
444 boost::next(pars.begin(), endpit + 1));
446 // Remove the end of the last paragraph; afterwards, remove the
447 // beginning of the first paragraph. Keep this order - there may only
448 // be one paragraph! Do not track deletions here; this is an internal
449 // action not visible to the user
451 Paragraph & back = copy_pars.back();
452 back.eraseChars(end, back.size(), false);
453 Paragraph & front = copy_pars.front();
454 front.eraseChars(0, start, false);
456 ParagraphList::iterator it = copy_pars.begin();
457 ParagraphList::iterator it_end = copy_pars.end();
459 for (; it != it_end; it++) {
460 // Since we have a copy of the paragraphs, the insets
461 // do not have a proper buffer reference. It makes
462 // sense to add them temporarily, because the
463 // operations below depend on that (acceptChanges included).
464 it->setBuffer(const_cast<Buffer &>(buf));
465 // PassThru paragraphs have the Language
466 // latex_language. This is invalid for others, so we
467 // need to change it to the buffer language.
468 if (text.inset().getLayout().isPassThru())
469 it->changeLanguage(buf.params(),
470 latex_language, buf.language());
473 // do not copy text (also nested in insets) which is marked as
474 // deleted, unless the whole selection was deleted
475 if (!isFullyDeleted(copy_pars))
476 acceptChanges(copy_pars, buf.params());
479 // do some final cleanup now, to make sure that the paragraphs
480 // are not linked to something else.
481 it = copy_pars.begin();
482 for (; it != it_end; it++) {
483 it->setBuffer(*static_cast<Buffer *>(0));
484 it->setInsetOwner(0);
487 DocumentClass * d = const_cast<DocumentClass *>(dc);
488 cutstack.push(make_pair(copy_pars, d));
498 void region(CursorSlice const & i1, CursorSlice const & i2,
499 Inset::row_type & r1, Inset::row_type & r2,
500 Inset::col_type & c1, Inset::col_type & c2)
502 Inset & p = i1.inset();
503 c1 = p.col(i1.idx());
504 c2 = p.col(i2.idx());
507 r1 = p.row(i1.idx());
508 r2 = p.row(i2.idx());
514 docstring grabAndEraseSelection(Cursor & cur)
516 if (!cur.selection())
518 docstring res = grabSelection(cur);
524 bool reduceSelectionToOneCell(Cursor & cur)
526 if (!cur.selection() || !cur.inMathed())
529 CursorSlice i1 = cur.selBegin();
530 CursorSlice i2 = cur.selEnd();
531 if (!i1.inset().asInsetMath())
534 // the easy case: do nothing if only one cell is selected
535 if (i1.idx() == i2.idx())
540 cur.top().pos() = cur.top().lastpos();
546 bool multipleCellsSelected(Cursor const & cur)
548 if (!cur.selection() || !cur.inMathed())
551 CursorSlice i1 = cur.selBegin();
552 CursorSlice i2 = cur.selEnd();
553 if (!i1.inset().asInsetMath())
556 if (i1.idx() == i2.idx())
563 void switchBetweenClasses(DocumentClass const * const oldone,
564 DocumentClass const * const newone, InsetText & in, ErrorList & errorlist)
568 LASSERT(!in.paragraphs().empty(), /**/);
569 if (oldone == newone)
572 DocumentClass const & oldtc = *oldone;
573 DocumentClass const & newtc = *newone;
576 ParIterator end = par_iterator_end(in);
577 for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
578 docstring const name = it->layout().name();
580 // the pasted text will keep their own layout name. If this layout does
581 // not exist in the new document, it will behave like a standard layout.
582 newtc.addLayoutIfNeeded(name);
584 if (in.usePlainLayout())
585 it->setLayout(newtc.plainLayout());
587 it->setLayout(newtc[name]);
591 InsetIterator const i_end = inset_iterator_end(in);
592 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
593 if (it->lyxCode() != FLEX_CODE)
594 // FIXME: Should we verify all InsetCollapsable?
596 if (!it->undefined())
598 // The flex inset is undefined in newtc
599 docstring const s = bformat(_(
600 "Flex inset %1$s is "
601 "undefined because of class "
602 "conversion from\n%2$s to %3$s"),
603 it->name(), from_utf8(oldtc.name()),
604 from_utf8(newtc.name()));
605 // To warn the user that something had to be done.
606 errorlist.push_back(ErrorItem(
607 _("Undefined flex inset"),
608 s, it.paragraph().id(), it.pos(), it.pos() + 1));
613 vector<docstring> availableSelections(Buffer const * buf)
615 vector<docstring> selList;
619 CutStack::const_iterator cit = theCuts.begin();
620 CutStack::const_iterator end = theCuts.end();
621 for (; cit != end; ++cit) {
622 // we do not use cit-> here because gcc 2.9x does not
624 ParagraphList const & pars = (*cit).first;
626 ParagraphList::const_iterator pit = pars.begin();
627 ParagraphList::const_iterator pend = pars.end();
628 for (; pit != pend; ++pit) {
629 Paragraph par(*pit, 0, 26);
630 // adapt paragraph to current buffer.
631 par.setBuffer(const_cast<Buffer &>(*buf));
632 asciiSel += par.asString(AS_STR_INSETS);
633 if (asciiSel.size() > 25) {
634 asciiSel.replace(22, docstring::npos,
640 selList.push_back(asciiSel);
647 size_type numberOfSelections()
649 return theCuts.size();
653 void cutSelection(Cursor & cur, bool doclear, bool realcut)
655 // This doesn't make sense, if there is no selection
656 if (!cur.selection())
659 // OK, we have a selection. This is always between cur.selBegin()
662 if (cur.inTexted()) {
663 Text * text = cur.text();
668 // make sure that the depth behind the selection are restored, too
669 cur.recordUndoSelection();
670 pit_type begpit = cur.selBegin().pit();
671 pit_type endpit = cur.selEnd().pit();
673 int endpos = cur.selEnd().pos();
675 BufferParams const & bp = cur.buffer()->params();
677 copySelectionHelper(*cur.buffer(),
680 cur.selBegin().pos(), endpos,
681 bp.documentClassPtr(), theCuts);
682 // Stuff what we got on the clipboard.
683 // Even if there is no selection.
684 putClipboard(theCuts[0].first, theCuts[0].second,
685 cur.selectionAsString(true));
688 if (begpit != endpit)
689 cur.updateFlags(Update::Force | Update::FitCursor);
691 boost::tie(endpit, endpos) =
692 eraseSelectionHelper(bp,
695 cur.selBegin().pos(), endpos);
697 // cutSelection can invalidate the cursor so we need to set
699 // we prefer the end for when tracking changes
703 // sometimes necessary
705 && text->paragraphs()[begpit].stripLeadingSpaces(bp.trackChanges))
708 // need a valid cursor. (Lgb)
709 cur.clearSelection();
710 cur.buffer()->updateLabels();
712 // tell tabular that a recent copy happened
713 dirtyTabularStack(false);
716 if (cur.inMathed()) {
717 if (cur.selBegin().idx() != cur.selEnd().idx()) {
718 // The current selection spans more than one cell.
720 cur.recordUndoInset();
722 // Record only the current cell to avoid a jumping
733 void copySelection(Cursor const & cur)
735 copySelection(cur, cur.selectionAsString(true));
739 void copyInset(Cursor const & cur, Inset * inset, docstring const & plaintext)
743 BufferParams const & bp = cur.buffer()->params();
744 par.setLayout(bp.documentClass().plainLayout());
745 par.insertInset(0, inset, Change(Change::UNCHANGED));
747 theCuts.push(make_pair(pars, bp.documentClassPtr()));
749 // stuff the selection onto the X clipboard, from an explicit copy request
750 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
755 void copySelectionToStack(Cursor const & cur, CutStack & cutstack)
757 // this doesn't make sense, if there is no selection
758 if (!cur.selection())
761 // copySelection can not yet handle the case of cross idx selection
762 if (cur.selBegin().idx() != cur.selEnd().idx())
765 if (cur.inTexted()) {
766 Text * text = cur.text();
768 // ok we have a selection. This is always between cur.selBegin()
769 // and sel_end cursor
771 // copy behind a space if there is one
772 ParagraphList & pars = text->paragraphs();
773 pos_type pos = cur.selBegin().pos();
774 pit_type par = cur.selBegin().pit();
775 while (pos < pars[par].size() &&
776 pars[par].isLineSeparator(pos) &&
777 (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
780 copySelectionHelper(*cur.buffer(), *text, par, cur.selEnd().pit(),
781 pos, cur.selEnd().pos(),
782 cur.buffer()->params().documentClassPtr(), cutstack);
784 // Reset the dirty_tabular_stack_ flag only when something
785 // is copied to the clipboard (not to the selectionBuffer).
786 if (&cutstack == &theCuts)
787 dirtyTabularStack(false);
790 if (cur.inMathed()) {
791 //lyxerr << "copySelection in mathed" << endl;
794 BufferParams const & bp = cur.buffer()->params();
795 // FIXME This should be the plain layout...right?
796 par.setLayout(bp.documentClass().plainLayout());
797 par.insert(0, grabSelection(cur), Font(), Change(Change::UNCHANGED));
799 cutstack.push(make_pair(pars, bp.documentClassPtr()));
806 void copySelectionToStack()
808 if (!selectionBuffer.empty())
809 theCuts.push(selectionBuffer[0]);
813 void copySelection(Cursor const & cur, docstring const & plaintext)
815 // In tablemode, because copy and paste actually use special table stack
816 // we do not attempt to get selected paragraphs under cursor. Instead, a
817 // paragraph with the plain text version is generated so that table cells
818 // can be pasted as pure text somewhere else.
819 if (cur.selBegin().idx() != cur.selEnd().idx()) {
822 BufferParams const & bp = cur.buffer()->params();
823 par.setLayout(bp.documentClass().plainLayout());
824 par.insert(0, plaintext, Font(), Change(Change::UNCHANGED));
826 theCuts.push(make_pair(pars, bp.documentClassPtr()));
828 copySelectionToStack(cur, theCuts);
831 // stuff the selection onto the X clipboard, from an explicit copy request
832 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
836 void saveSelection(Cursor const & cur)
838 // This function is called, not when a selection is formed, but when
839 // a selection is cleared. Therefore, multiple keyboard selection
840 // will not repeatively trigger this function (bug 3877).
842 && cur.selBegin() == cur.bv().cursor().selBegin()
843 && cur.selEnd() == cur.bv().cursor().selEnd()) {
844 LYXERR(Debug::SELECTION, "saveSelection: '" << cur.selectionAsString(true) << "'");
845 copySelectionToStack(cur, selectionBuffer);
852 return !selectionBuffer.empty();
856 void clearSelection()
858 selectionBuffer.clear();
868 docstring selection(size_t sel_index)
870 return sel_index < theCuts.size()
871 ? theCuts[sel_index].first.back().asString(AS_STR_INSETS | AS_STR_NEWLINES)
876 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
877 DocumentClass const * const docclass, ErrorList & errorList)
879 if (cur.inTexted()) {
880 Text * text = cur.text();
886 boost::tie(ppp, endpit) =
887 pasteSelectionHelper(cur, parlist, docclass, errorList);
888 cur.buffer()->updateLabels();
889 cur.clearSelection();
890 text->setCursor(cur, ppp.first, ppp.second);
893 // mathed is handled in InsetMathNest/InsetMathGrid
894 LASSERT(!cur.inMathed(), /**/);
898 void pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
900 // this does not make sense, if there is nothing to paste
901 if (!checkPastePossible(sel_index))
905 pasteParagraphList(cur, theCuts[sel_index].first,
906 theCuts[sel_index].second, errorList);
911 void pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs)
913 // Use internal clipboard if it is the most recent one
914 if (theClipboard().isInternal()) {
915 pasteFromStack(cur, errorList, 0);
919 // First try LyX format
920 if (theClipboard().hasLyXContents()) {
921 string lyx = theClipboard().getAsLyX();
923 // For some strange reason gcc 3.2 and 3.3 do not accept
924 // Buffer buffer(string(), false);
925 Buffer buffer("", false);
926 buffer.setUnnamed(true);
927 if (buffer.readString(lyx)) {
929 pasteParagraphList(cur, buffer.paragraphs(),
930 buffer.params().documentClassPtr(), errorList);
937 // Then try plain text
938 docstring const text = theClipboard().getAsText();
943 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
945 cur.text()->insertStringAsLines(cur, text, cur.current_font);
949 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
950 Clipboard::GraphicsType preferedType)
952 LASSERT(theClipboard().hasGraphicsContents(preferedType), /**/);
954 // get picture from clipboard
955 FileName filename = theClipboard().getAsGraphics(cur, preferedType);
956 if (filename.empty())
959 // create inset for graphic
960 InsetGraphics * inset = new InsetGraphics(*cur.buffer());
961 InsetGraphicsParams params;
962 params.filename = support::DocFileName(filename.absFilename());
963 inset->setParams(params);
969 void pasteSelection(Cursor & cur, ErrorList & errorList)
971 if (selectionBuffer.empty())
974 pasteParagraphList(cur, selectionBuffer[0].first,
975 selectionBuffer[0].second, errorList);
979 void replaceSelectionWithString(Cursor & cur, docstring const & str, bool backwards)
982 DocIterator selbeg = cur.selectionBegin();
984 // Get font setting before we cut, we need a copy here, not a bare reference.
986 selbeg.paragraph().getFontSettings(cur.buffer()->params(), selbeg.pos());
988 // Insert the new string
989 pos_type pos = cur.selEnd().pos();
990 Paragraph & par = cur.selEnd().paragraph();
991 docstring::const_iterator cit = str.begin();
992 docstring::const_iterator end = str.end();
993 for (; cit != end; ++cit, ++pos)
994 par.insertChar(pos, *cit, font, cur.buffer()->params().trackChanges);
997 cutSelection(cur, true, false);
999 // select the replacement
1001 selbeg.pos() += str.length();
1002 cur.setSelection(selbeg, -int(str.length()));
1004 cur.setSelection(selbeg, str.length());
1008 void replaceSelection(Cursor & cur)
1010 if (cur.selection())
1011 cutSelection(cur, true, false);
1015 void eraseSelection(Cursor & cur)
1017 //lyxerr << "cap::eraseSelection begin: " << cur << endl;
1018 CursorSlice const & i1 = cur.selBegin();
1019 CursorSlice const & i2 = cur.selEnd();
1020 if (i1.inset().asInsetMath()) {
1023 if (i1.idx() == i2.idx()) {
1024 i1.cell().erase(i1.pos(), i2.pos());
1025 // We may have deleted i1.cell(cur.pos()).
1026 // Make sure that pos is valid.
1027 if (cur.pos() > cur.lastpos())
1028 cur.pos() = cur.lastpos();
1030 InsetMath * p = i1.asInsetMath();
1031 Inset::row_type r1, r2;
1032 Inset::col_type c1, c2;
1033 region(i1, i2, r1, r2, c1, c2);
1034 for (Inset::row_type row = r1; row <= r2; ++row)
1035 for (Inset::col_type col = c1; col <= c2; ++col)
1036 p->cell(p->index(row, col)).clear();
1037 // We've deleted the whole cell. Only pos 0 is valid.
1040 // need a valid cursor. (Lgb)
1041 cur.clearSelection();
1043 lyxerr << "can't erase this selection 1" << endl;
1045 //lyxerr << "cap::eraseSelection end: " << cur << endl;
1049 void selDel(Cursor & cur)
1051 //lyxerr << "cap::selDel" << endl;
1052 if (cur.selection())
1053 eraseSelection(cur);
1057 void selClearOrDel(Cursor & cur)
1059 //lyxerr << "cap::selClearOrDel" << endl;
1060 if (lyxrc.auto_region_delete)
1063 cur.setSelection(false);
1067 docstring grabSelection(Cursor const & cur)
1069 if (!cur.selection())
1073 // grab selection by glueing multiple cells together. This is not what
1074 // we want because selections spanning multiple cells will get "&" and "\\"
1077 for (DocIterator dit = cur.selectionBegin();
1078 dit != cur.selectionEnd(); dit.forwardPos())
1079 os << asString(dit.cell());
1083 CursorSlice i1 = cur.selBegin();
1084 CursorSlice i2 = cur.selEnd();
1086 if (i1.idx() == i2.idx()) {
1087 if (i1.inset().asInsetMath()) {
1088 MathData::const_iterator it = i1.cell().begin();
1089 return asString(MathData(it + i1.pos(), it + i2.pos()));
1091 return from_ascii("unknown selection 1");
1095 Inset::row_type r1, r2;
1096 Inset::col_type c1, c2;
1097 region(i1, i2, r1, r2, c1, c2);
1100 if (i1.inset().asInsetMath()) {
1101 for (Inset::row_type row = r1; row <= r2; ++row) {
1104 for (Inset::col_type col = c1; col <= c2; ++col) {
1107 data += asString(i1.asInsetMath()->
1108 cell(i1.asInsetMath()->index(row, col)));
1112 data = from_ascii("unknown selection 2");
1118 void dirtyTabularStack(bool b)
1120 dirty_tabular_stack_ = b;
1124 bool tabularStackDirty()
1126 return dirty_tabular_stack_;