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"
27 #include "ErrorList.h"
29 #include "FuncRequest.h"
30 #include "InsetIterator.h"
31 #include "InsetList.h"
36 #include "Paragraph.h"
37 #include "ParagraphParameters.h"
38 #include "ParIterator.h"
39 #include "TextClass.h"
41 #include "insets/InsetBibitem.h"
42 #include "insets/InsetBranch.h"
43 #include "insets/InsetCommand.h"
44 #include "insets/InsetFlex.h"
45 #include "insets/InsetGraphics.h"
46 #include "insets/InsetGraphicsParams.h"
47 #include "insets/InsetInclude.h"
48 #include "insets/InsetLabel.h"
49 #include "insets/InsetTabular.h"
51 #include "mathed/MathData.h"
52 #include "mathed/InsetMath.h"
53 #include "mathed/InsetMathHull.h"
54 #include "mathed/InsetMathRef.h"
55 #include "mathed/MathSupport.h"
57 #include "support/debug.h"
58 #include "support/docstream.h"
59 #include "support/gettext.h"
60 #include "support/lassert.h"
61 #include "support/limited_stack.h"
62 #include "support/lstrings.h"
64 #include "frontends/alert.h"
65 #include "frontends/Clipboard.h"
66 #include "frontends/Selection.h"
68 #include <boost/tuple/tuple.hpp>
69 #include <boost/next_prior.hpp>
74 using namespace lyx::support;
75 using lyx::frontend::Clipboard;
81 typedef pair<pit_type, int> PitPosPair;
83 typedef limited_stack<pair<ParagraphList, DocumentClassConstPtr> > CutStack;
86 // persistent selection, cleared until the next selection
87 CutStack selectionBuffer(1);
89 // store whether the tabular stack is newer than the normal copy stack
90 // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
91 // when we (hopefully) have a one-for-all paste mechanism.
92 bool dirty_tabular_stack_ = false;
95 bool checkPastePossible(int index)
97 return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
101 struct PasteReturnValue {
102 PasteReturnValue(pit_type r_par, pos_type r_pos, bool r_nu) :
103 par(r_par), pos(r_pos), needupdate(r_nu)
112 pasteSelectionHelper(DocIterator const & cur, ParagraphList const & parlist,
113 DocumentClassConstPtr oldDocClass, Buffer * tmpbuffer,
114 ErrorList & errorlist)
116 Buffer const & buffer = *cur.buffer();
117 pit_type pit = cur.pit();
118 pos_type pos = cur.pos();
119 bool need_update = false;
120 InsetText * target_inset = cur.inset().asInsetText();
122 InsetTabular * it = cur.inset().asInsetTabular();
123 target_inset = it? it->cell(cur.idx())->asInsetText() : 0;
125 LASSERT(target_inset, return PasteReturnValue(pit, pos, need_update));
126 ParagraphList & pars = target_inset->paragraphs();
129 return PasteReturnValue(pit, pos, need_update);
131 BOOST_ASSERT (pos <= pars[pit].size());
133 // Make a copy of the CaP paragraphs.
134 ParagraphList insertion = parlist;
135 DocumentClassConstPtr newDocClass = buffer.params().documentClassPtr();
137 // Now remove all out of the pars which is NOT allowed in the
138 // new environment and set also another font if that is required.
140 // Convert newline to paragraph break in ParbreakIsNewline
141 if (target_inset->getLayout().parbreakIsNewline()
142 || pars[pit].layout().parbreak_is_newline) {
143 for (size_t i = 0; i != insertion.size(); ++i) {
144 for (pos_type j = 0; j != insertion[i].size(); ++j) {
145 if (insertion[i].isNewline(j)) {
146 // do not track deletion of newline
147 insertion[i].eraseChar(j, false);
148 insertion[i].setInsetOwner(target_inset);
149 breakParagraphConservative(
158 // set the paragraphs to plain layout if necessary
159 if (cur.inset().usePlainLayout()) {
160 bool forcePlainLayout = cur.inset().forcePlainLayout();
161 Layout const & plainLayout = newDocClass->plainLayout();
162 Layout const & defaultLayout = newDocClass->defaultLayout();
163 ParagraphList::iterator const end = insertion.end();
164 ParagraphList::iterator par = insertion.begin();
165 for (; par != end; ++par) {
166 Layout const & parLayout = par->layout();
167 if (forcePlainLayout || parLayout == defaultLayout)
168 par->setLayout(plainLayout);
170 } else { // check if we need to reset from plain layout
171 Layout const & defaultLayout = newDocClass->defaultLayout();
172 Layout const & plainLayout = newDocClass->plainLayout();
173 ParagraphList::iterator const end = insertion.end();
174 ParagraphList::iterator par = insertion.begin();
175 for (; par != end; ++par) {
176 Layout const & parLayout = par->layout();
177 if (parLayout == plainLayout)
178 par->setLayout(defaultLayout);
182 InsetText in(cur.buffer());
183 // Make sure there is no class difference.
184 in.paragraphs().clear();
185 // This works without copying any paragraph data because we have
186 // a specialized swap method for ParagraphList. This is important
187 // since we store pointers to insets at some places and we don't
188 // want to invalidate them.
189 insertion.swap(in.paragraphs());
190 cap::switchBetweenClasses(oldDocClass, newDocClass, in, errorlist);
191 insertion.swap(in.paragraphs());
193 ParagraphList::iterator tmpbuf = insertion.begin();
194 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
196 depth_type max_depth = pars[pit].getMaxDepthAfter();
198 for (; tmpbuf != insertion.end(); ++tmpbuf) {
199 // If we have a negative jump so that the depth would
200 // go below 0 depth then we have to redo the delta to
201 // this new max depth level so that subsequent
202 // paragraphs are aligned correctly to this paragraph
204 if (int(tmpbuf->params().depth()) + depth_delta < 0)
207 // Set the right depth so that we are not too deep or shallow.
208 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
209 if (tmpbuf->params().depth() > max_depth)
210 tmpbuf->params().depth(max_depth);
212 // Only set this from the 2nd on as the 2nd depends
213 // for maxDepth still on pit.
214 if (tmpbuf != insertion.begin())
215 max_depth = tmpbuf->getMaxDepthAfter();
217 // Set the inset owner of this paragraph.
218 tmpbuf->setInsetOwner(target_inset);
219 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
220 // do not track deletion of invalid insets
221 if (Inset * inset = tmpbuf->getInset(i))
222 if (!target_inset->insetAllowed(inset->lyxCode()))
223 tmpbuf->eraseChar(i--, false);
226 tmpbuf->setChange(Change(buffer.params().trackChanges ?
227 Change::INSERTED : Change::UNCHANGED));
230 bool const empty = pars[pit].empty();
232 // Make the buf exactly the same layout as the cursor
234 insertion.begin()->makeSameLayout(pars[pit]);
237 // Prepare the paragraphs and insets for insertion.
238 insertion.swap(in.paragraphs());
240 InsetIterator const i_end = inset_iterator_end(in);
241 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
242 // Even though this will also be done later, it has to be done here
243 // since some inset might going to try to access
244 // the buffer() member.
245 it->setBuffer(const_cast<Buffer &>(buffer));
246 switch (it->lyxCode()) {
248 case MATH_HULL_CODE: {
249 // check for equation labels and resolve duplicates
250 InsetMathHull * ins = it->asInsetMath()->asHullInset();
251 std::vector<InsetLabel *> labels = ins->getLabels();
252 for (size_t i = 0; i != labels.size(); ++i) {
255 InsetLabel * lab = labels[i];
256 docstring const oldname = lab->getParam("name");
257 lab->updateLabel(oldname);
258 // We need to update the buffer reference cache.
260 docstring const newname = lab->getParam("name");
261 if (oldname == newname)
263 // adapt the references
264 for (InsetIterator itt = inset_iterator_begin(in);
265 itt != i_end; ++itt) {
266 if (itt->lyxCode() == REF_CODE) {
267 InsetCommand * ref = itt->asInsetCommand();
268 if (ref->getParam("reference") == oldname)
269 ref->setParam("reference", newname);
270 } else if (itt->lyxCode() == MATH_REF_CODE) {
271 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
272 // this is necessary to prevent an uninitialized
273 // buffer when the RefInset is in a MathBox.
274 // FIXME audit setBuffer calls
275 mi->setBuffer(const_cast<Buffer &>(buffer));
276 if (mi->getTarget() == oldname)
277 mi->changeTarget(newname);
285 // check for duplicates
286 InsetLabel & lab = static_cast<InsetLabel &>(*it);
287 docstring const oldname = lab.getParam("name");
288 lab.updateLabel(oldname);
289 // We need to update the buffer reference cache.
291 docstring const newname = lab.getParam("name");
292 if (oldname == newname)
294 // adapt the references
295 for (InsetIterator itt = inset_iterator_begin(in); itt != i_end; ++itt) {
296 if (itt->lyxCode() == REF_CODE) {
297 InsetCommand & ref = static_cast<InsetCommand &>(*itt);
298 if (ref.getParam("reference") == oldname)
299 ref.setParam("reference", newname);
300 } else if (itt->lyxCode() == MATH_REF_CODE) {
301 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
302 // this is necessary to prevent an uninitialized
303 // buffer when the RefInset is in a MathBox.
304 // FIXME audit setBuffer calls
305 mi->setBuffer(const_cast<Buffer &>(buffer));
306 if (mi->getTarget() == oldname)
307 mi->changeTarget(newname);
314 InsetInclude & inc = static_cast<InsetInclude &>(*it);
316 // We need to update the list of included files.
322 // check for duplicates
323 InsetBibitem & bib = static_cast<InsetBibitem &>(*it);
324 docstring const oldkey = bib.getParam("key");
325 bib.updateCommand(oldkey, false);
326 // We need to update the buffer reference cache.
328 docstring const newkey = bib.getParam("key");
329 if (oldkey == newkey)
331 // adapt the references
332 for (InsetIterator itt = inset_iterator_begin(in);
333 itt != i_end; ++itt) {
334 if (itt->lyxCode() == CITE_CODE) {
335 InsetCommand * ref = itt->asInsetCommand();
336 if (ref->getParam("key") == oldkey)
337 ref->setParam("key", newkey);
344 // check if branch is known to target buffer
346 InsetBranch & br = static_cast<InsetBranch &>(*it);
347 docstring const name = br.branch();
350 bool const is_child = (&buffer != buffer.masterBuffer());
351 BranchList branchlist = buffer.params().branchlist();
352 if ((!is_child && branchlist.find(name))
353 || (is_child && (branchlist.find(name)
354 || buffer.masterBuffer()->params().branchlist().find(name))))
357 // This is for a temporary buffer, so simply create the branch.
358 // Must not use lyx::dispatch(), since tmpbuffer has no view.
360 tmpbuffer->dispatch(FuncRequest(LFUN_BRANCH_ADD, name), dr);
362 docstring text = bformat(
363 _("The pasted branch \"%1$s\" is undefined.\n"
364 "Do you want to add it to the document's branch list?"),
366 if (frontend::Alert::prompt(_("Unknown branch"),
367 text, 0, 1, _("&Add"), _("&Don't Add")) != 0)
369 lyx::dispatch(FuncRequest(LFUN_BRANCH_ADD, name));
371 // We need to update the list of branches.
380 insertion.swap(in.paragraphs());
382 // Split the paragraph for inserting the buf if necessary.
384 breakParagraphConservative(buffer.params(), pars, pit, pos);
388 pars.insert(boost::next(pars.begin(), pit),
392 // merge the empty par with the last par of the insertion
393 mergeParagraph(buffer.params(), pars,
394 pit + insertion.size() - 1);
396 pars.insert(boost::next(pars.begin(), pit + 1),
400 // merge the first par of the insertion with the current par
401 mergeParagraph(buffer.params(), pars, pit);
404 // Store the new cursor position.
405 pit_type last_paste = pit + insertion.size() - 1;
406 pit_type startpit = pit;
408 pos = pars[last_paste].size();
410 // FIXME Should we do it here, or should we let updateBuffer() do it?
411 // Set paragraph buffers. It's important to do this right away
412 // before something calls Inset::buffer() and causes a crash.
413 for (pit_type p = startpit; p <= pit; ++p)
414 pars[p].setBuffer(const_cast<Buffer &>(buffer));
416 // Join (conditionally) last pasted paragraph with next one, i.e.,
417 // the tail of the spliced document paragraph
418 if (!empty && last_paste + 1 != pit_type(pars.size())) {
419 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
420 mergeParagraph(buffer.params(), pars, last_paste);
421 } else if (pars[last_paste + 1].empty()) {
422 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
423 mergeParagraph(buffer.params(), pars, last_paste);
424 } else if (pars[last_paste].empty()) {
425 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
426 mergeParagraph(buffer.params(), pars, last_paste);
428 pars[last_paste + 1].stripLeadingSpaces(buffer.params().trackChanges);
433 return PasteReturnValue(pit, pos, need_update);
437 PitPosPair eraseSelectionHelper(BufferParams const & params,
438 ParagraphList & pars,
439 pit_type startpit, pit_type endpit,
440 int startpos, int endpos)
442 // Start of selection is really invalid.
443 if (startpit == pit_type(pars.size()) ||
444 (startpos > pars[startpit].size()))
445 return PitPosPair(endpit, endpos);
447 // Start and end is inside same paragraph
448 if (endpit == pit_type(pars.size()) || startpit == endpit) {
449 endpos -= pars[startpit].eraseChars(startpos, endpos, params.trackChanges);
450 return PitPosPair(endpit, endpos);
453 for (pit_type pit = startpit; pit != endpit + 1;) {
454 pos_type const left = (pit == startpit ? startpos : 0);
455 pos_type right = (pit == endpit ? endpos : pars[pit].size() + 1);
456 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.trackChanges);
458 // Logically erase only, including the end-of-paragraph character
459 pars[pit].eraseChars(left, right, params.trackChanges);
461 // Separate handling of paragraph break:
462 if (merge && pit != endpit &&
464 || pars[pit].hasSameLayout(pars[endpit])
465 || pars[endpit].size() == endpos)) {
466 if (pit + 1 == endpit)
467 endpos += pars[pit].size();
468 mergeParagraph(params, pars, pit);
474 // Ensure legal cursor pos:
477 return PitPosPair(endpit, endpos);
481 void putClipboard(ParagraphList const & paragraphs,
482 DocumentClassConstPtr docclass, docstring const & plaintext)
484 // This used to need to be static to avoid a memory leak. It no longer needs
485 // to be so, but the alternative is to construct a new one of these (with a
486 // new temporary directory, etc) every time, and then to destroy it. So maybe
487 // it's worth just keeping this one around.
488 static Buffer * staticbuffer = theBufferList().newInternalBuffer(
489 FileName::tempName("clipboard.internal").absFileName());
491 // These two things only really need doing the first time.
492 staticbuffer->setUnnamed(true);
493 staticbuffer->inset().setBuffer(*staticbuffer);
495 // Use a clone for the complicated stuff so that we do not need to clean
496 // up in order to avoid a crash.
497 Buffer * buffer = staticbuffer->cloneBufferOnly();
498 LASSERT(buffer, return);
500 // This needs doing every time.
501 buffer->params().setDocumentClass(docclass);
503 // we will use pasteSelectionHelper to copy the paragraphs into the
504 // temporary Buffer, since it does a lot of things to fix them up.
505 DocIterator dit = doc_iterator_begin(buffer, &buffer->inset());
507 pasteSelectionHelper(dit, paragraphs, docclass, buffer, el);
509 // We don't want to produce images that are not used. Therefore,
510 // output formulas as MathML. Even if this is not understood by all
511 // applications, the number that can parse it should go up in the future.
512 buffer->params().html_math_output = BufferParams::MathML;
514 // Make sure MarkAsExporting is deleted before buffer is
516 // The Buffer is being used to export. This is necessary so that the
517 // updateMacros call will record the needed information.
518 MarkAsExporting mex(buffer);
520 buffer->updateBuffer(Buffer::UpdateMaster, OutputUpdate);
521 buffer->updateMacros();
522 buffer->updateMacroInstances(OutputUpdate);
527 if (buffer->write(oslyx))
531 odocstringstream oshtml;
532 OutputParams runparams(encodings.fromLyXName("utf8"));
533 buffer->writeLyXHTMLSource(oshtml, runparams, Buffer::FullSource);
535 theClipboard().put(lyx, oshtml.str(), plaintext);
543 /// return true if the whole ParagraphList is deleted
544 static bool isFullyDeleted(ParagraphList const & pars)
546 pit_type const pars_size = static_cast<pit_type>(pars.size());
548 // check all paragraphs
549 for (pit_type pit = 0; pit < pars_size; ++pit) {
550 if (!pars[pit].empty()) // prevent assertion failure
551 if (!pars[pit].isDeleted(0, pars[pit].size()))
558 void copySelectionHelper(Buffer const & buf, Text const & text,
559 pit_type startpit, pit_type endpit,
560 int start, int end, DocumentClassConstPtr dc, CutStack & cutstack)
562 ParagraphList const & pars = text.paragraphs();
564 // In most of these cases, we can try to recover.
565 LASSERT(0 <= start, start = 0);
566 LASSERT(start <= pars[startpit].size(), start = pars[startpit].size());
567 LASSERT(0 <= end, end = 0);
568 LASSERT(end <= pars[endpit].size(), end = pars[endpit].size());
569 LASSERT(startpit != endpit || start <= end, return);
571 // Clone the paragraphs within the selection.
572 ParagraphList copy_pars(boost::next(pars.begin(), startpit),
573 boost::next(pars.begin(), endpit + 1));
575 // Remove the end of the last paragraph; afterwards, remove the
576 // beginning of the first paragraph. Keep this order - there may only
577 // be one paragraph! Do not track deletions here; this is an internal
578 // action not visible to the user
580 Paragraph & back = copy_pars.back();
581 back.eraseChars(end, back.size(), false);
582 Paragraph & front = copy_pars.front();
583 front.eraseChars(0, start, false);
585 ParagraphList::iterator it = copy_pars.begin();
586 ParagraphList::iterator it_end = copy_pars.end();
588 for (; it != it_end; ++it) {
589 // Since we have a copy of the paragraphs, the insets
590 // do not have a proper buffer reference. It makes
591 // sense to add them temporarily, because the
592 // operations below depend on that (acceptChanges included).
593 it->setBuffer(const_cast<Buffer &>(buf));
594 // PassThru paragraphs have the Language
595 // latex_language. This is invalid for others, so we
596 // need to change it to the buffer language.
597 if (it->isPassThru())
598 it->changeLanguage(buf.params(),
599 latex_language, buf.language());
602 // do not copy text (also nested in insets) which is marked as
603 // deleted, unless the whole selection was deleted
604 if (!isFullyDeleted(copy_pars))
605 acceptChanges(copy_pars, buf.params());
607 rejectChanges(copy_pars, buf.params());
610 // do some final cleanup now, to make sure that the paragraphs
611 // are not linked to something else.
612 it = copy_pars.begin();
613 for (; it != it_end; ++it) {
614 it->setBuffer(*static_cast<Buffer *>(0));
615 it->setInsetOwner(0);
618 cutstack.push(make_pair(copy_pars, dc));
628 void region(CursorSlice const & i1, CursorSlice const & i2,
629 Inset::row_type & r1, Inset::row_type & r2,
630 Inset::col_type & c1, Inset::col_type & c2)
632 Inset & p = i1.inset();
633 c1 = p.col(i1.idx());
634 c2 = p.col(i2.idx());
637 r1 = p.row(i1.idx());
638 r2 = p.row(i2.idx());
644 docstring grabAndEraseSelection(Cursor & cur)
646 if (!cur.selection())
648 docstring res = grabSelection(cur);
654 bool reduceSelectionToOneCell(Cursor & cur)
656 if (!cur.selection() || !cur.inMathed())
659 CursorSlice i1 = cur.selBegin();
660 CursorSlice i2 = cur.selEnd();
661 if (!i1.inset().asInsetMath())
664 // the easy case: do nothing if only one cell is selected
665 if (i1.idx() == i2.idx())
670 cur.top().pos() = cur.top().lastpos();
676 bool multipleCellsSelected(Cursor const & cur)
678 if (!cur.selection() || !cur.inMathed())
681 CursorSlice i1 = cur.selBegin();
682 CursorSlice i2 = cur.selEnd();
683 if (!i1.inset().asInsetMath())
686 if (i1.idx() == i2.idx())
693 void switchBetweenClasses(DocumentClassConstPtr oldone,
694 DocumentClassConstPtr newone, InsetText & in, ErrorList & errorlist)
698 LBUFERR(!in.paragraphs().empty());
699 if (oldone == newone)
702 DocumentClass const & oldtc = *oldone;
703 DocumentClass const & newtc = *newone;
706 ParIterator it = par_iterator_begin(in);
707 ParIterator end = par_iterator_end(in);
708 // for remembering which layouts we've had to add
709 set<docstring> newlayouts;
710 for (; it != end; ++it) {
711 docstring const name = it->layout().name();
713 // the pasted text will keep their own layout name. If this layout does
714 // not exist in the new document, it will behave like a standard layout.
715 bool const added_one = newtc.addLayoutIfNeeded(name);
717 newlayouts.insert(name);
719 if (added_one || newlayouts.find(name) != newlayouts.end()) {
721 docstring const s = bformat(_("Layout `%1$s' was not found."), name);
723 ErrorItem(_("Layout Not Found"), s, it->id(), 0, it->size()));
726 if (in.usePlainLayout())
727 it->setLayout(newtc.plainLayout());
729 it->setLayout(newtc[name]);
733 InsetIterator const i_end = inset_iterator_end(in);
734 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
735 if (it->lyxCode() != FLEX_CODE)
736 // FIXME: Should we verify all InsetCollapsable?
739 docstring const layoutName = it->layoutName();
740 docstring const & n = newone->insetLayout(layoutName).name();
741 bool const is_undefined = n.empty() ||
742 n == DocumentClass::plainInsetLayout().name();
746 // The flex inset is undefined in newtc
747 docstring const oldname = from_utf8(oldtc.name());
748 docstring const newname = from_utf8(newtc.name());
750 if (oldname == newname)
751 s = bformat(_("Flex inset %1$s is undefined after "
752 "reloading `%2$s' layout."), layoutName, oldname);
754 s = bformat(_("Flex inset %1$s is undefined because of "
755 "conversion from `%2$s' layout to `%3$s'."),
756 layoutName, oldname, newname);
757 // To warn the user that something had to be done.
758 errorlist.push_back(ErrorItem(
759 _("Undefined flex inset"),
760 s, it.paragraph().id(), it.pos(), it.pos() + 1));
765 vector<docstring> availableSelections(Buffer const * buf)
767 vector<docstring> selList;
771 CutStack::const_iterator cit = theCuts.begin();
772 CutStack::const_iterator end = theCuts.end();
773 for (; cit != end; ++cit) {
774 // we do not use cit-> here because gcc 2.9x does not
776 ParagraphList const & pars = (*cit).first;
778 ParagraphList::const_iterator pit = pars.begin();
779 ParagraphList::const_iterator pend = pars.end();
780 for (; pit != pend; ++pit) {
781 Paragraph par(*pit, 0, 26);
782 // adapt paragraph to current buffer.
783 par.setBuffer(const_cast<Buffer &>(*buf));
784 asciiSel += par.asString(AS_STR_INSETS);
785 if (asciiSel.size() > 25) {
786 asciiSel.replace(22, docstring::npos,
792 selList.push_back(asciiSel);
799 size_type numberOfSelections()
801 return theCuts.size();
805 void cutSelection(Cursor & cur, bool doclear, bool realcut)
807 // This doesn't make sense, if there is no selection
808 if (!cur.selection())
811 // OK, we have a selection. This is always between cur.selBegin()
814 if (cur.inTexted()) {
815 Text * text = cur.text();
820 // make sure that the depth behind the selection are restored, too
821 cur.recordUndoSelection();
822 pit_type begpit = cur.selBegin().pit();
823 pit_type endpit = cur.selEnd().pit();
825 int endpos = cur.selEnd().pos();
827 BufferParams const & bp = cur.buffer()->params();
829 copySelectionHelper(*cur.buffer(),
832 cur.selBegin().pos(), endpos,
833 bp.documentClassPtr(), theCuts);
834 // Stuff what we got on the clipboard.
835 // Even if there is no selection.
836 putClipboard(theCuts[0].first, theCuts[0].second,
837 cur.selectionAsString(true));
840 if (begpit != endpit)
841 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
843 boost::tie(endpit, endpos) =
844 eraseSelectionHelper(bp,
847 cur.selBegin().pos(), endpos);
849 // cutSelection can invalidate the cursor so we need to set
851 // we prefer the end for when tracking changes
855 // sometimes necessary
857 && text->paragraphs()[begpit].stripLeadingSpaces(bp.trackChanges))
860 // need a valid cursor. (Lgb)
861 cur.clearSelection();
863 // After a cut operation, we must make sure that the Buffer is updated
864 // because some further operation might need updated label information for
865 // example. So we cannot just use "cur.forceBufferUpdate()" here.
867 cur.buffer()->updateBuffer();
869 // tell tabular that a recent copy happened
870 dirtyTabularStack(false);
873 if (cur.inMathed()) {
874 if (cur.selBegin().idx() != cur.selEnd().idx()) {
875 // The current selection spans more than one cell.
877 cur.recordUndoInset();
879 // Record only the current cell to avoid a jumping
890 void copySelection(Cursor const & cur)
892 copySelection(cur, cur.selectionAsString(true));
896 void copyInset(Cursor const & cur, Inset * inset, docstring const & plaintext)
900 BufferParams const & bp = cur.buffer()->params();
901 par.setLayout(bp.documentClass().plainLayout());
902 par.insertInset(0, inset, Change(Change::UNCHANGED));
904 theCuts.push(make_pair(pars, bp.documentClassPtr()));
906 // stuff the selection onto the X clipboard, from an explicit copy request
907 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
913 void copySelectionToStack(Cursor const & cur, CutStack & cutstack)
915 // this doesn't make sense, if there is no selection
916 if (!cur.selection())
919 // copySelection can not yet handle the case of cross idx selection
920 if (cur.selBegin().idx() != cur.selEnd().idx())
923 if (cur.inTexted()) {
924 Text * text = cur.text();
926 // ok we have a selection. This is always between cur.selBegin()
927 // and sel_end cursor
929 // copy behind a space if there is one
930 ParagraphList & pars = text->paragraphs();
931 pos_type pos = cur.selBegin().pos();
932 pit_type par = cur.selBegin().pit();
933 while (pos < pars[par].size() &&
934 pars[par].isLineSeparator(pos) &&
935 (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
938 copySelectionHelper(*cur.buffer(), *text, par, cur.selEnd().pit(),
939 pos, cur.selEnd().pos(),
940 cur.buffer()->params().documentClassPtr(), cutstack);
942 // Reset the dirty_tabular_stack_ flag only when something
943 // is copied to the clipboard (not to the selectionBuffer).
944 if (&cutstack == &theCuts)
945 dirtyTabularStack(false);
948 if (cur.inMathed()) {
949 //lyxerr << "copySelection in mathed" << endl;
952 BufferParams const & bp = cur.buffer()->params();
953 // FIXME This should be the plain layout...right?
954 par.setLayout(bp.documentClass().plainLayout());
955 par.insert(0, grabSelection(cur), Font(), Change(Change::UNCHANGED));
957 cutstack.push(make_pair(pars, bp.documentClassPtr()));
964 void copySelectionToStack()
966 if (!selectionBuffer.empty())
967 theCuts.push(selectionBuffer[0]);
971 void copySelection(Cursor const & cur, docstring const & plaintext)
973 // In tablemode, because copy and paste actually use special table stack
974 // we do not attempt to get selected paragraphs under cursor. Instead, a
975 // paragraph with the plain text version is generated so that table cells
976 // can be pasted as pure text somewhere else.
977 if (cur.selBegin().idx() != cur.selEnd().idx()) {
980 BufferParams const & bp = cur.buffer()->params();
981 par.setLayout(bp.documentClass().plainLayout());
982 par.insert(0, plaintext, Font(), Change(Change::UNCHANGED));
984 theCuts.push(make_pair(pars, bp.documentClassPtr()));
986 copySelectionToStack(cur, theCuts);
989 // stuff the selection onto the X clipboard, from an explicit copy request
990 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
994 void saveSelection(Cursor const & cur)
996 // This function is called, not when a selection is formed, but when
997 // a selection is cleared. Therefore, multiple keyboard selection
998 // will not repeatively trigger this function (bug 3877).
1000 && cur.selBegin() == cur.bv().cursor().selBegin()
1001 && cur.selEnd() == cur.bv().cursor().selEnd()) {
1002 LYXERR(Debug::SELECTION, "saveSelection: '" << cur.selectionAsString(true) << "'");
1003 copySelectionToStack(cur, selectionBuffer);
1010 return !selectionBuffer.empty();
1014 void clearSelection()
1016 selectionBuffer.clear();
1020 void clearCutStack()
1026 docstring selection(size_t sel_index)
1028 return sel_index < theCuts.size()
1029 ? theCuts[sel_index].first.back().asString(AS_STR_INSETS | AS_STR_NEWLINES)
1034 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
1035 DocumentClassConstPtr docclass, ErrorList & errorList)
1037 if (cur.inTexted()) {
1038 Text * text = cur.text();
1041 PasteReturnValue prv =
1042 pasteSelectionHelper(cur, parlist, docclass, 0, errorList);
1043 cur.forceBufferUpdate();
1044 cur.clearSelection();
1045 text->setCursor(cur, prv.par, prv.pos);
1048 // mathed is handled in InsetMathNest/InsetMathGrid
1049 LATTEST(!cur.inMathed());
1053 void pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
1055 // this does not make sense, if there is nothing to paste
1056 if (!checkPastePossible(sel_index))
1060 pasteParagraphList(cur, theCuts[sel_index].first,
1061 theCuts[sel_index].second, errorList);
1065 void pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs,
1066 Clipboard::TextType type)
1068 // Use internal clipboard if it is the most recent one
1069 // This overrides asParagraphs and type on purpose!
1070 if (theClipboard().isInternal()) {
1071 pasteFromStack(cur, errorList, 0);
1075 // First try LyX format
1076 if ((type == Clipboard::LyXTextType ||
1077 type == Clipboard::LyXOrPlainTextType ||
1078 type == Clipboard::AnyTextType) &&
1079 theClipboard().hasTextContents(Clipboard::LyXTextType)) {
1080 string lyx = theClipboard().getAsLyX();
1082 // For some strange reason gcc 3.2 and 3.3 do not accept
1083 // Buffer buffer(string(), false);
1084 Buffer buffer("", false);
1085 buffer.setUnnamed(true);
1086 if (buffer.readString(lyx)) {
1088 pasteParagraphList(cur, buffer.paragraphs(),
1089 buffer.params().documentClassPtr(), errorList);
1095 // Then try TeX and HTML
1096 Clipboard::TextType types[2] = {Clipboard::HtmlTextType, Clipboard::LaTeXTextType};
1097 string names[2] = {"html", "latex"};
1098 for (int i = 0; i < 2; ++i) {
1099 if (type != types[i] && type != Clipboard::AnyTextType)
1101 bool available = theClipboard().hasTextContents(types[i]);
1103 // If a specific type was explicitly requested, try to
1104 // interpret plain text: The user told us that the clipboard
1105 // contents is in the desired format
1106 if (!available && type == types[i]) {
1107 types[i] = Clipboard::PlainTextType;
1108 available = theClipboard().hasTextContents(types[i]);
1112 docstring text = theClipboard().getAsText(types[i]);
1113 available = !text.empty();
1115 // For some strange reason gcc 3.2 and 3.3 do not accept
1116 // Buffer buffer(string(), false);
1117 Buffer buffer("", false);
1118 buffer.setUnnamed(true);
1119 if (buffer.importString(names[i], text, errorList)) {
1121 pasteParagraphList(cur, buffer.paragraphs(),
1122 buffer.params().documentClassPtr(), errorList);
1129 // Then try plain text
1130 docstring const text = theClipboard().getAsText(Clipboard::PlainTextType);
1135 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1137 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1141 void pasteSimpleText(Cursor & cur, bool asParagraphs)
1144 // Use internal clipboard if it is the most recent one
1145 if (theClipboard().isInternal()) {
1146 if (!checkPastePossible(0))
1149 ParagraphList const & pars = theCuts[0].first;
1150 ParagraphList::const_iterator it = pars.begin();
1151 for (; it != pars.end(); ++it) {
1152 if (it != pars.begin())
1154 text += (*it).asString();
1156 asParagraphs = false;
1158 // Then try plain text
1159 text = theClipboard().getAsText(Clipboard::PlainTextType);
1166 cutSelection(cur, true, false);
1168 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1170 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1174 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
1175 Clipboard::GraphicsType preferedType)
1177 LASSERT(theClipboard().hasGraphicsContents(preferedType), return);
1179 // get picture from clipboard
1180 FileName filename = theClipboard().getAsGraphics(cur, preferedType);
1181 if (filename.empty())
1184 // create inset for graphic
1185 InsetGraphics * inset = new InsetGraphics(cur.buffer());
1186 InsetGraphicsParams params;
1187 params.filename = support::DocFileName(filename.absFileName(), false);
1188 inset->setParams(params);
1194 void pasteSelection(Cursor & cur, ErrorList & errorList)
1196 if (selectionBuffer.empty())
1199 pasteParagraphList(cur, selectionBuffer[0].first,
1200 selectionBuffer[0].second, errorList);
1204 void replaceSelectionWithString(Cursor & cur, docstring const & str)
1207 DocIterator selbeg = cur.selectionBegin();
1209 // Get font setting before we cut, we need a copy here, not a bare reference.
1211 selbeg.paragraph().getFontSettings(cur.buffer()->params(), selbeg.pos());
1213 // Insert the new string
1214 pos_type pos = cur.selEnd().pos();
1215 Paragraph & par = cur.selEnd().paragraph();
1216 docstring::const_iterator cit = str.begin();
1217 docstring::const_iterator end = str.end();
1218 for (; cit != end; ++cit, ++pos)
1219 par.insertChar(pos, *cit, font, cur.buffer()->params().trackChanges);
1221 // Cut the selection
1222 cutSelection(cur, true, false);
1226 void replaceSelection(Cursor & cur)
1228 if (cur.selection())
1229 cutSelection(cur, true, false);
1233 void eraseSelection(Cursor & cur)
1235 //lyxerr << "cap::eraseSelection begin: " << cur << endl;
1236 CursorSlice const & i1 = cur.selBegin();
1237 CursorSlice const & i2 = cur.selEnd();
1238 if (i1.inset().asInsetMath()) {
1241 if (i1.idx() == i2.idx()) {
1242 i1.cell().erase(i1.pos(), i2.pos());
1243 // We may have deleted i1.cell(cur.pos()).
1244 // Make sure that pos is valid.
1245 if (cur.pos() > cur.lastpos())
1246 cur.pos() = cur.lastpos();
1248 InsetMath * p = i1.asInsetMath();
1249 Inset::row_type r1, r2;
1250 Inset::col_type c1, c2;
1251 region(i1, i2, r1, r2, c1, c2);
1252 for (Inset::row_type row = r1; row <= r2; ++row)
1253 for (Inset::col_type col = c1; col <= c2; ++col)
1254 p->cell(p->index(row, col)).clear();
1255 // We've deleted the whole cell. Only pos 0 is valid.
1258 // need a valid cursor. (Lgb)
1259 cur.clearSelection();
1261 lyxerr << "can't erase this selection 1" << endl;
1263 //lyxerr << "cap::eraseSelection end: " << cur << endl;
1267 void selDel(Cursor & cur)
1269 //lyxerr << "cap::selDel" << endl;
1270 if (cur.selection())
1271 eraseSelection(cur);
1275 void selClearOrDel(Cursor & cur)
1277 //lyxerr << "cap::selClearOrDel" << endl;
1278 if (lyxrc.auto_region_delete)
1281 cur.setSelection(false);
1285 docstring grabSelection(Cursor const & cur)
1287 if (!cur.selection())
1291 // grab selection by glueing multiple cells together. This is not what
1292 // we want because selections spanning multiple cells will get "&" and "\\"
1295 for (DocIterator dit = cur.selectionBegin();
1296 dit != cur.selectionEnd(); dit.forwardPos())
1297 os << asString(dit.cell());
1301 CursorSlice i1 = cur.selBegin();
1302 CursorSlice i2 = cur.selEnd();
1304 if (i1.idx() == i2.idx()) {
1305 if (i1.inset().asInsetMath()) {
1306 MathData::const_iterator it = i1.cell().begin();
1307 Buffer * buf = cur.buffer();
1308 return asString(MathData(buf, it + i1.pos(), it + i2.pos()));
1310 return from_ascii("unknown selection 1");
1314 Inset::row_type r1, r2;
1315 Inset::col_type c1, c2;
1316 region(i1, i2, r1, r2, c1, c2);
1319 if (i1.inset().asInsetMath()) {
1320 for (Inset::row_type row = r1; row <= r2; ++row) {
1323 for (Inset::col_type col = c1; col <= c2; ++col) {
1326 data += asString(i1.asInsetMath()->
1327 cell(i1.asInsetMath()->index(row, col)));
1331 data = from_ascii("unknown selection 2");
1337 void dirtyTabularStack(bool b)
1339 dirty_tabular_stack_ = b;
1343 bool tabularStackDirty()
1345 return dirty_tabular_stack_;