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, ErrorList & errorlist)
115 Buffer const & buffer = *cur.buffer();
116 pit_type pit = cur.pit();
117 pos_type pos = cur.pos();
118 bool need_update = false;
119 InsetText * target_inset = cur.inset().asInsetText();
121 InsetTabular * it = cur.inset().asInsetTabular();
122 target_inset = it? it->cell(cur.idx())->asInsetText() : 0;
124 LASSERT(target_inset, return PasteReturnValue(pit, pos, need_update));
125 ParagraphList & pars = target_inset->paragraphs();
128 return PasteReturnValue(pit, pos, need_update);
130 BOOST_ASSERT (pos <= pars[pit].size());
132 // Make a copy of the CaP paragraphs.
133 ParagraphList insertion = parlist;
134 DocumentClassConstPtr newDocClass = buffer.params().documentClassPtr();
136 // Now remove all out of the pars which is NOT allowed in the
137 // new environment and set also another font if that is required.
139 // Convert newline to paragraph break in ParbreakIsNewline
140 if (target_inset->getLayout().parbreakIsNewline()
141 || pars[pit].layout().parbreak_is_newline) {
142 for (size_t i = 0; i != insertion.size(); ++i) {
143 for (pos_type j = 0; j != insertion[i].size(); ++j) {
144 if (insertion[i].isNewline(j)) {
145 // do not track deletion of newline
146 insertion[i].eraseChar(j, false);
147 insertion[i].setInsetOwner(target_inset);
148 breakParagraphConservative(
157 // set the paragraphs to plain layout if necessary
158 if (cur.inset().usePlainLayout()) {
159 bool forcePlainLayout = cur.inset().forcePlainLayout();
160 Layout const & plainLayout = newDocClass->plainLayout();
161 Layout const & defaultLayout = newDocClass->defaultLayout();
162 ParagraphList::iterator const end = insertion.end();
163 ParagraphList::iterator par = insertion.begin();
164 for (; par != end; ++par) {
165 Layout const & parLayout = par->layout();
166 if (forcePlainLayout || parLayout == defaultLayout)
167 par->setLayout(plainLayout);
169 } else { // check if we need to reset from plain layout
170 Layout const & defaultLayout = newDocClass->defaultLayout();
171 Layout const & plainLayout = newDocClass->plainLayout();
172 ParagraphList::iterator const end = insertion.end();
173 ParagraphList::iterator par = insertion.begin();
174 for (; par != end; ++par) {
175 Layout const & parLayout = par->layout();
176 if (parLayout == plainLayout)
177 par->setLayout(defaultLayout);
181 InsetText in(cur.buffer());
182 // Make sure there is no class difference.
183 in.paragraphs().clear();
184 // This works without copying any paragraph data because we have
185 // a specialized swap method for ParagraphList. This is important
186 // since we store pointers to insets at some places and we don't
187 // want to invalidate them.
188 insertion.swap(in.paragraphs());
189 cap::switchBetweenClasses(oldDocClass, newDocClass, in, errorlist);
190 insertion.swap(in.paragraphs());
192 ParagraphList::iterator tmpbuf = insertion.begin();
193 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
195 depth_type max_depth = pars[pit].getMaxDepthAfter();
197 for (; tmpbuf != insertion.end(); ++tmpbuf) {
198 // If we have a negative jump so that the depth would
199 // go below 0 depth then we have to redo the delta to
200 // this new max depth level so that subsequent
201 // paragraphs are aligned correctly to this paragraph
203 if (int(tmpbuf->params().depth()) + depth_delta < 0)
206 // Set the right depth so that we are not too deep or shallow.
207 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
208 if (tmpbuf->params().depth() > max_depth)
209 tmpbuf->params().depth(max_depth);
211 // Only set this from the 2nd on as the 2nd depends
212 // for maxDepth still on pit.
213 if (tmpbuf != insertion.begin())
214 max_depth = tmpbuf->getMaxDepthAfter();
216 // Set the inset owner of this paragraph.
217 tmpbuf->setInsetOwner(target_inset);
218 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
219 // do not track deletion of invalid insets
220 if (Inset * inset = tmpbuf->getInset(i))
221 if (!target_inset->insetAllowed(inset->lyxCode()))
222 tmpbuf->eraseChar(i--, false);
225 tmpbuf->setChange(Change(buffer.params().trackChanges ?
226 Change::INSERTED : Change::UNCHANGED));
229 bool const empty = pars[pit].empty();
231 // Make the buf exactly the same layout as the cursor
233 insertion.begin()->makeSameLayout(pars[pit]);
236 // Prepare the paragraphs and insets for insertion.
237 insertion.swap(in.paragraphs());
239 InsetIterator const i_end = inset_iterator_end(in);
240 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
241 // Even though this will also be done later, it has to be done here
242 // since some inset might going to try to access
243 // the buffer() member.
244 it->setBuffer(const_cast<Buffer &>(buffer));
245 switch (it->lyxCode()) {
247 case MATH_HULL_CODE: {
248 // check for equation labels and resolve duplicates
249 InsetMathHull * ins = it->asInsetMath()->asHullInset();
250 std::vector<InsetLabel *> labels = ins->getLabels();
251 for (size_t i = 0; i != labels.size(); ++i) {
254 InsetLabel * lab = labels[i];
255 docstring const oldname = lab->getParam("name");
256 lab->updateLabel(oldname);
257 // We need to update the buffer reference cache.
259 docstring const newname = lab->getParam("name");
260 if (oldname == newname)
262 // adapt the references
263 for (InsetIterator itt = inset_iterator_begin(in);
264 itt != i_end; ++itt) {
265 if (itt->lyxCode() == REF_CODE) {
266 InsetCommand * ref = itt->asInsetCommand();
267 if (ref->getParam("reference") == oldname)
268 ref->setParam("reference", newname);
269 } else if (itt->lyxCode() == MATH_REF_CODE) {
270 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
271 // this is necessary to prevent an uninitialized
272 // buffer when the RefInset is in a MathBox.
273 // FIXME audit setBuffer calls
274 mi->setBuffer(const_cast<Buffer &>(buffer));
275 if (mi->getTarget() == oldname)
276 mi->changeTarget(newname);
284 // check for duplicates
285 InsetLabel & lab = static_cast<InsetLabel &>(*it);
286 docstring const oldname = lab.getParam("name");
287 lab.updateLabel(oldname);
288 // We need to update the buffer reference cache.
290 docstring const newname = lab.getParam("name");
291 if (oldname == newname)
293 // adapt the references
294 for (InsetIterator itt = inset_iterator_begin(in); itt != i_end; ++itt) {
295 if (itt->lyxCode() == REF_CODE) {
296 InsetCommand & ref = static_cast<InsetCommand &>(*itt);
297 if (ref.getParam("reference") == oldname)
298 ref.setParam("reference", newname);
299 } else if (itt->lyxCode() == MATH_REF_CODE) {
300 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
301 // this is necessary to prevent an uninitialized
302 // buffer when the RefInset is in a MathBox.
303 // FIXME audit setBuffer calls
304 mi->setBuffer(const_cast<Buffer &>(buffer));
305 if (mi->getTarget() == oldname)
306 mi->changeTarget(newname);
313 InsetInclude & inc = static_cast<InsetInclude &>(*it);
315 // We need to update the list of included files.
321 // check for duplicates
322 InsetBibitem & bib = static_cast<InsetBibitem &>(*it);
323 docstring const oldkey = bib.getParam("key");
324 bib.updateCommand(oldkey, false);
325 // We need to update the buffer reference cache.
327 docstring const newkey = bib.getParam("key");
328 if (oldkey == newkey)
330 // adapt the references
331 for (InsetIterator itt = inset_iterator_begin(in);
332 itt != i_end; ++itt) {
333 if (itt->lyxCode() == CITE_CODE) {
334 InsetCommand * ref = itt->asInsetCommand();
335 if (ref->getParam("key") == oldkey)
336 ref->setParam("key", newkey);
343 // check if branch is known to target buffer
345 InsetBranch & br = static_cast<InsetBranch &>(*it);
346 docstring const name = br.branch();
349 bool const is_child = (&buffer != buffer.masterBuffer());
350 BranchList branchlist = buffer.params().branchlist();
351 if ((!is_child && branchlist.find(name))
352 || (is_child && (branchlist.find(name)
353 || buffer.masterBuffer()->params().branchlist().find(name))))
355 // FIXME: add an option to add the branch to the master's BranchList.
356 docstring text = bformat(
357 _("The pasted branch \"%1$s\" is undefined.\n"
358 "Do you want to add it to the document's branch list?"),
360 if (frontend::Alert::prompt(_("Unknown branch"),
361 text, 0, 1, _("&Add"), _("&Don't Add")) != 0)
363 lyx::dispatch(FuncRequest(LFUN_BRANCH_ADD, name));
364 // We need to update the list of branches.
373 insertion.swap(in.paragraphs());
375 // Split the paragraph for inserting the buf if necessary.
377 breakParagraphConservative(buffer.params(), pars, pit, pos);
381 pars.insert(boost::next(pars.begin(), pit),
385 // merge the empty par with the last par of the insertion
386 mergeParagraph(buffer.params(), pars,
387 pit + insertion.size() - 1);
389 pars.insert(boost::next(pars.begin(), pit + 1),
393 // merge the first par of the insertion with the current par
394 mergeParagraph(buffer.params(), pars, pit);
397 // Store the new cursor position.
398 pit_type last_paste = pit + insertion.size() - 1;
399 pit_type startpit = pit;
401 pos = pars[last_paste].size();
403 // FIXME Should we do it here, or should we let updateBuffer() do it?
404 // Set paragraph buffers. It's important to do this right away
405 // before something calls Inset::buffer() and causes a crash.
406 for (pit_type p = startpit; p <= pit; ++p)
407 pars[p].setBuffer(const_cast<Buffer &>(buffer));
409 // Join (conditionally) last pasted paragraph with next one, i.e.,
410 // the tail of the spliced document paragraph
411 if (!empty && last_paste + 1 != pit_type(pars.size())) {
412 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
413 mergeParagraph(buffer.params(), pars, last_paste);
414 } else if (pars[last_paste + 1].empty()) {
415 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
416 mergeParagraph(buffer.params(), pars, last_paste);
417 } else if (pars[last_paste].empty()) {
418 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
419 mergeParagraph(buffer.params(), pars, last_paste);
421 pars[last_paste + 1].stripLeadingSpaces(buffer.params().trackChanges);
426 return PasteReturnValue(pit, pos, need_update);
430 PitPosPair eraseSelectionHelper(BufferParams const & params,
431 ParagraphList & pars,
432 pit_type startpit, pit_type endpit,
433 int startpos, int endpos)
435 // Start of selection is really invalid.
436 if (startpit == pit_type(pars.size()) ||
437 (startpos > pars[startpit].size()))
438 return PitPosPair(endpit, endpos);
440 // Start and end is inside same paragraph
441 if (endpit == pit_type(pars.size()) || startpit == endpit) {
442 endpos -= pars[startpit].eraseChars(startpos, endpos, params.trackChanges);
443 return PitPosPair(endpit, endpos);
446 for (pit_type pit = startpit; pit != endpit + 1;) {
447 pos_type const left = (pit == startpit ? startpos : 0);
448 pos_type right = (pit == endpit ? endpos : pars[pit].size() + 1);
449 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.trackChanges);
451 // Logically erase only, including the end-of-paragraph character
452 pars[pit].eraseChars(left, right, params.trackChanges);
454 // Separate handling of paragraph break:
455 if (merge && pit != endpit &&
457 || pars[pit].hasSameLayout(pars[endpit])
458 || pars[endpit].size() == endpos)) {
459 if (pit + 1 == endpit)
460 endpos += pars[pit].size();
461 mergeParagraph(params, pars, pit);
467 // Ensure legal cursor pos:
470 return PitPosPair(endpit, endpos);
474 void putClipboard(ParagraphList const & paragraphs,
475 DocumentClassConstPtr docclass, docstring const & plaintext)
477 // This used to need to be static to avoid a memory leak. It no longer needs
478 // to be so, but the alternative is to construct a new one of these (with a
479 // new temporary directory, etc) every time, and then to destroy it. So maybe
480 // it's worth just keeping this one around.
481 static Buffer * buffer = theBufferList().newInternalBuffer(
482 FileName::tempName("clipboard.internal").absFileName());
484 // These two things only really need doing the first time.
485 buffer->setUnnamed(true);
486 buffer->inset().setBuffer(*buffer);
488 // This needs doing every time.
489 buffer->params().setDocumentClass(docclass);
491 // we will use pasteSelectionHelper to copy the paragraphs into the
492 // temporary Buffer, since it does a lot of things to fix them up.
493 DocIterator dit = doc_iterator_begin(buffer, &buffer->inset());
495 pasteSelectionHelper(dit, paragraphs, docclass, el);
497 // We don't want to produce images that are not used. Therefore,
498 // output formulas as MathML. Even if this is not understood by all
499 // applications, the number that can parse it should go up in the future.
500 buffer->params().html_math_output = BufferParams::MathML;
502 // The Buffer is being used to export. This is necessary so that the
503 // updateMacros call will record the needed information.
504 MarkAsExporting mex(buffer);
506 buffer->updateBuffer(Buffer::UpdateMaster, OutputUpdate);
507 buffer->updateMacros();
508 buffer->updateMacroInstances(OutputUpdate);
513 if (buffer->write(oslyx))
517 odocstringstream oshtml;
518 OutputParams runparams(encodings.fromLyXName("utf8"));
519 buffer->writeLyXHTMLSource(oshtml, runparams, Buffer::FullSource);
521 theClipboard().put(lyx, oshtml.str(), plaintext);
524 buffer->paragraphs().clear();
528 /// return true if the whole ParagraphList is deleted
529 static bool isFullyDeleted(ParagraphList const & pars)
531 pit_type const pars_size = static_cast<pit_type>(pars.size());
533 // check all paragraphs
534 for (pit_type pit = 0; pit < pars_size; ++pit) {
535 if (!pars[pit].empty()) // prevent assertion failure
536 if (!pars[pit].isDeleted(0, pars[pit].size()))
543 void copySelectionHelper(Buffer const & buf, Text const & text,
544 pit_type startpit, pit_type endpit,
545 int start, int end, DocumentClassConstPtr dc, CutStack & cutstack)
547 ParagraphList const & pars = text.paragraphs();
549 LASSERT(0 <= start && start <= pars[startpit].size(), /**/);
550 LASSERT(0 <= end && end <= pars[endpit].size(), /**/);
551 LASSERT(startpit != endpit || start <= end, /**/);
553 // Clone the paragraphs within the selection.
554 ParagraphList copy_pars(boost::next(pars.begin(), startpit),
555 boost::next(pars.begin(), endpit + 1));
557 // Remove the end of the last paragraph; afterwards, remove the
558 // beginning of the first paragraph. Keep this order - there may only
559 // be one paragraph! Do not track deletions here; this is an internal
560 // action not visible to the user
562 Paragraph & back = copy_pars.back();
563 back.eraseChars(end, back.size(), false);
564 Paragraph & front = copy_pars.front();
565 front.eraseChars(0, start, false);
567 ParagraphList::iterator it = copy_pars.begin();
568 ParagraphList::iterator it_end = copy_pars.end();
570 for (; it != it_end; ++it) {
571 // Since we have a copy of the paragraphs, the insets
572 // do not have a proper buffer reference. It makes
573 // sense to add them temporarily, because the
574 // operations below depend on that (acceptChanges included).
575 it->setBuffer(const_cast<Buffer &>(buf));
576 // PassThru paragraphs have the Language
577 // latex_language. This is invalid for others, so we
578 // need to change it to the buffer language.
579 if (it->isPassThru())
580 it->changeLanguage(buf.params(),
581 latex_language, buf.language());
584 // do not copy text (also nested in insets) which is marked as
585 // deleted, unless the whole selection was deleted
586 if (!isFullyDeleted(copy_pars))
587 acceptChanges(copy_pars, buf.params());
589 rejectChanges(copy_pars, buf.params());
592 // do some final cleanup now, to make sure that the paragraphs
593 // are not linked to something else.
594 it = copy_pars.begin();
595 for (; it != it_end; ++it) {
596 it->setBuffer(*static_cast<Buffer *>(0));
597 it->setInsetOwner(0);
600 cutstack.push(make_pair(copy_pars, dc));
610 void region(CursorSlice const & i1, CursorSlice const & i2,
611 Inset::row_type & r1, Inset::row_type & r2,
612 Inset::col_type & c1, Inset::col_type & c2)
614 Inset & p = i1.inset();
615 c1 = p.col(i1.idx());
616 c2 = p.col(i2.idx());
619 r1 = p.row(i1.idx());
620 r2 = p.row(i2.idx());
626 docstring grabAndEraseSelection(Cursor & cur)
628 if (!cur.selection())
630 docstring res = grabSelection(cur);
636 bool reduceSelectionToOneCell(Cursor & cur)
638 if (!cur.selection() || !cur.inMathed())
641 CursorSlice i1 = cur.selBegin();
642 CursorSlice i2 = cur.selEnd();
643 if (!i1.inset().asInsetMath())
646 // the easy case: do nothing if only one cell is selected
647 if (i1.idx() == i2.idx())
652 cur.top().pos() = cur.top().lastpos();
658 bool multipleCellsSelected(Cursor const & cur)
660 if (!cur.selection() || !cur.inMathed())
663 CursorSlice i1 = cur.selBegin();
664 CursorSlice i2 = cur.selEnd();
665 if (!i1.inset().asInsetMath())
668 if (i1.idx() == i2.idx())
675 void switchBetweenClasses(DocumentClassConstPtr oldone,
676 DocumentClassConstPtr newone, InsetText & in, ErrorList & errorlist)
680 LASSERT(!in.paragraphs().empty(), /**/);
681 if (oldone == newone)
684 DocumentClass const & oldtc = *oldone;
685 DocumentClass const & newtc = *newone;
688 ParIterator it = par_iterator_begin(in);
689 ParIterator end = par_iterator_end(in);
690 // for remembering which layouts we've had to add
691 set<docstring> newlayouts;
692 for (; it != end; ++it) {
693 docstring const name = it->layout().name();
695 // the pasted text will keep their own layout name. If this layout does
696 // not exist in the new document, it will behave like a standard layout.
697 bool const added_one = newtc.addLayoutIfNeeded(name);
699 newlayouts.insert(name);
701 if (added_one || newlayouts.find(name) != newlayouts.end()) {
703 docstring const s = bformat(_("Layout `%1$s' was not found."), name);
705 ErrorItem(_("Layout Not Found"), s, it->id(), 0, it->size()));
708 if (in.usePlainLayout())
709 it->setLayout(newtc.plainLayout());
711 it->setLayout(newtc[name]);
715 InsetIterator const i_end = inset_iterator_end(in);
716 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
717 if (it->lyxCode() != FLEX_CODE)
718 // FIXME: Should we verify all InsetCollapsable?
721 docstring const layoutName = it->layoutName();
722 docstring const & n = newone->insetLayout(layoutName).name();
723 bool const is_undefined = n.empty() ||
724 n == DocumentClass::plainInsetLayout().name();
728 // The flex inset is undefined in newtc
729 docstring const oldname = from_utf8(oldtc.name());
730 docstring const newname = from_utf8(newtc.name());
732 if (oldname == newname)
733 s = bformat(_("Flex inset %1$s is undefined after "
734 "reloading `%2$s' layout."), layoutName, oldname);
736 s = bformat(_("Flex inset %1$s is undefined because of "
737 "conversion from `%2$s' layout to `%3$s'."),
738 layoutName, oldname, newname);
739 // To warn the user that something had to be done.
740 errorlist.push_back(ErrorItem(
741 _("Undefined flex inset"),
742 s, it.paragraph().id(), it.pos(), it.pos() + 1));
747 vector<docstring> availableSelections(Buffer const * buf)
749 vector<docstring> selList;
753 CutStack::const_iterator cit = theCuts.begin();
754 CutStack::const_iterator end = theCuts.end();
755 for (; cit != end; ++cit) {
756 // we do not use cit-> here because gcc 2.9x does not
758 ParagraphList const & pars = (*cit).first;
760 ParagraphList::const_iterator pit = pars.begin();
761 ParagraphList::const_iterator pend = pars.end();
762 for (; pit != pend; ++pit) {
763 Paragraph par(*pit, 0, 26);
764 // adapt paragraph to current buffer.
765 par.setBuffer(const_cast<Buffer &>(*buf));
766 asciiSel += par.asString(AS_STR_INSETS);
767 if (asciiSel.size() > 25) {
768 asciiSel.replace(22, docstring::npos,
774 selList.push_back(asciiSel);
781 size_type numberOfSelections()
783 return theCuts.size();
787 void cutSelection(Cursor & cur, bool doclear, bool realcut)
789 // This doesn't make sense, if there is no selection
790 if (!cur.selection())
793 // OK, we have a selection. This is always between cur.selBegin()
796 if (cur.inTexted()) {
797 Text * text = cur.text();
802 // make sure that the depth behind the selection are restored, too
803 cur.recordUndoSelection();
804 pit_type begpit = cur.selBegin().pit();
805 pit_type endpit = cur.selEnd().pit();
807 int endpos = cur.selEnd().pos();
809 BufferParams const & bp = cur.buffer()->params();
811 copySelectionHelper(*cur.buffer(),
814 cur.selBegin().pos(), endpos,
815 bp.documentClassPtr(), theCuts);
816 // Stuff what we got on the clipboard.
817 // Even if there is no selection.
818 putClipboard(theCuts[0].first, theCuts[0].second,
819 cur.selectionAsString(true));
822 if (begpit != endpit)
823 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
825 boost::tie(endpit, endpos) =
826 eraseSelectionHelper(bp,
829 cur.selBegin().pos(), endpos);
831 // cutSelection can invalidate the cursor so we need to set
833 // we prefer the end for when tracking changes
837 // sometimes necessary
839 && text->paragraphs()[begpit].stripLeadingSpaces(bp.trackChanges))
842 // need a valid cursor. (Lgb)
843 cur.clearSelection();
845 // After a cut operation, we must make sure that the Buffer is updated
846 // because some further operation might need updated label information for
847 // example. So we cannot just use "cur.forceBufferUpdate()" here.
849 cur.buffer()->updateBuffer();
851 // tell tabular that a recent copy happened
852 dirtyTabularStack(false);
855 if (cur.inMathed()) {
856 if (cur.selBegin().idx() != cur.selEnd().idx()) {
857 // The current selection spans more than one cell.
859 cur.recordUndoInset();
861 // Record only the current cell to avoid a jumping
872 void copySelection(Cursor const & cur)
874 copySelection(cur, cur.selectionAsString(true));
878 void copyInset(Cursor const & cur, Inset * inset, docstring const & plaintext)
882 BufferParams const & bp = cur.buffer()->params();
883 par.setLayout(bp.documentClass().plainLayout());
884 par.insertInset(0, inset, Change(Change::UNCHANGED));
886 theCuts.push(make_pair(pars, bp.documentClassPtr()));
888 // stuff the selection onto the X clipboard, from an explicit copy request
889 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
895 void copySelectionToStack(Cursor const & cur, CutStack & cutstack)
897 // this doesn't make sense, if there is no selection
898 if (!cur.selection())
901 // copySelection can not yet handle the case of cross idx selection
902 if (cur.selBegin().idx() != cur.selEnd().idx())
905 if (cur.inTexted()) {
906 Text * text = cur.text();
908 // ok we have a selection. This is always between cur.selBegin()
909 // and sel_end cursor
911 // copy behind a space if there is one
912 ParagraphList & pars = text->paragraphs();
913 pos_type pos = cur.selBegin().pos();
914 pit_type par = cur.selBegin().pit();
915 while (pos < pars[par].size() &&
916 pars[par].isLineSeparator(pos) &&
917 (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
920 copySelectionHelper(*cur.buffer(), *text, par, cur.selEnd().pit(),
921 pos, cur.selEnd().pos(),
922 cur.buffer()->params().documentClassPtr(), cutstack);
924 // Reset the dirty_tabular_stack_ flag only when something
925 // is copied to the clipboard (not to the selectionBuffer).
926 if (&cutstack == &theCuts)
927 dirtyTabularStack(false);
930 if (cur.inMathed()) {
931 //lyxerr << "copySelection in mathed" << endl;
934 BufferParams const & bp = cur.buffer()->params();
935 // FIXME This should be the plain layout...right?
936 par.setLayout(bp.documentClass().plainLayout());
937 par.insert(0, grabSelection(cur), Font(), Change(Change::UNCHANGED));
939 cutstack.push(make_pair(pars, bp.documentClassPtr()));
946 void copySelectionToStack()
948 if (!selectionBuffer.empty())
949 theCuts.push(selectionBuffer[0]);
953 void copySelection(Cursor const & cur, docstring const & plaintext)
955 // In tablemode, because copy and paste actually use special table stack
956 // we do not attempt to get selected paragraphs under cursor. Instead, a
957 // paragraph with the plain text version is generated so that table cells
958 // can be pasted as pure text somewhere else.
959 if (cur.selBegin().idx() != cur.selEnd().idx()) {
962 BufferParams const & bp = cur.buffer()->params();
963 par.setLayout(bp.documentClass().plainLayout());
964 par.insert(0, plaintext, Font(), Change(Change::UNCHANGED));
966 theCuts.push(make_pair(pars, bp.documentClassPtr()));
968 copySelectionToStack(cur, theCuts);
971 // stuff the selection onto the X clipboard, from an explicit copy request
972 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
976 void saveSelection(Cursor const & cur)
978 // This function is called, not when a selection is formed, but when
979 // a selection is cleared. Therefore, multiple keyboard selection
980 // will not repeatively trigger this function (bug 3877).
982 && cur.selBegin() == cur.bv().cursor().selBegin()
983 && cur.selEnd() == cur.bv().cursor().selEnd()) {
984 LYXERR(Debug::SELECTION, "saveSelection: '" << cur.selectionAsString(true) << "'");
985 copySelectionToStack(cur, selectionBuffer);
992 return !selectionBuffer.empty();
996 void clearSelection()
998 selectionBuffer.clear();
1002 void clearCutStack()
1008 docstring selection(size_t sel_index)
1010 return sel_index < theCuts.size()
1011 ? theCuts[sel_index].first.back().asString(AS_STR_INSETS | AS_STR_NEWLINES)
1016 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
1017 DocumentClassConstPtr docclass, ErrorList & errorList)
1019 if (cur.inTexted()) {
1020 Text * text = cur.text();
1021 LASSERT(text, /**/);
1023 PasteReturnValue prv =
1024 pasteSelectionHelper(cur, parlist, docclass, errorList);
1026 cur.forceBufferUpdate();
1027 cur.clearSelection();
1028 text->setCursor(cur, prv.par, prv.pos);
1031 // mathed is handled in InsetMathNest/InsetMathGrid
1032 LASSERT(!cur.inMathed(), /**/);
1036 void pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
1038 // this does not make sense, if there is nothing to paste
1039 if (!checkPastePossible(sel_index))
1043 pasteParagraphList(cur, theCuts[sel_index].first,
1044 theCuts[sel_index].second, errorList);
1048 void pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs,
1049 Clipboard::TextType type)
1051 // Use internal clipboard if it is the most recent one
1052 // This overrides asParagraphs and type on purpose!
1053 if (theClipboard().isInternal()) {
1054 pasteFromStack(cur, errorList, 0);
1058 // First try LyX format
1059 if ((type == Clipboard::LyXTextType ||
1060 type == Clipboard::LyXOrPlainTextType ||
1061 type == Clipboard::AnyTextType) &&
1062 theClipboard().hasTextContents(Clipboard::LyXTextType)) {
1063 string lyx = theClipboard().getAsLyX();
1065 // For some strange reason gcc 3.2 and 3.3 do not accept
1066 // Buffer buffer(string(), false);
1067 Buffer buffer("", false);
1068 buffer.setUnnamed(true);
1069 if (buffer.readString(lyx)) {
1071 pasteParagraphList(cur, buffer.paragraphs(),
1072 buffer.params().documentClassPtr(), errorList);
1078 // Then try TeX and HTML
1079 Clipboard::TextType types[2] = {Clipboard::HtmlTextType, Clipboard::LaTeXTextType};
1080 string names[2] = {"html", "latex"};
1081 for (int i = 0; i < 2; ++i) {
1082 if (type != types[i] && type != Clipboard::AnyTextType)
1084 bool available = theClipboard().hasTextContents(types[i]);
1086 // If a specific type was explicitly requested, try to
1087 // interpret plain text: The user told us that the clipboard
1088 // contents is in the desired format
1089 if (!available && type == types[i]) {
1090 types[i] = Clipboard::PlainTextType;
1091 available = theClipboard().hasTextContents(types[i]);
1095 docstring text = theClipboard().getAsText(types[i]);
1096 available = !text.empty();
1098 // For some strange reason gcc 3.2 and 3.3 do not accept
1099 // Buffer buffer(string(), false);
1100 Buffer buffer("", false);
1101 buffer.setUnnamed(true);
1102 if (buffer.importString(names[i], text, errorList)) {
1104 pasteParagraphList(cur, buffer.paragraphs(),
1105 buffer.params().documentClassPtr(), errorList);
1112 // Then try plain text
1113 docstring const text = theClipboard().getAsText(Clipboard::PlainTextType);
1118 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1120 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1124 void pasteSimpleText(Cursor & cur, bool asParagraphs)
1127 // Use internal clipboard if it is the most recent one
1128 if (theClipboard().isInternal()) {
1129 if (!checkPastePossible(0))
1132 ParagraphList const & pars = theCuts[0].first;
1133 ParagraphList::const_iterator it = pars.begin();
1134 for (; it != pars.end(); ++it) {
1135 if (it != pars.begin())
1137 text += (*it).asString();
1139 asParagraphs = false;
1141 // Then try plain text
1142 text = theClipboard().getAsText(Clipboard::PlainTextType);
1149 cutSelection(cur, true, false);
1151 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1153 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1157 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
1158 Clipboard::GraphicsType preferedType)
1160 LASSERT(theClipboard().hasGraphicsContents(preferedType), /**/);
1162 // get picture from clipboard
1163 FileName filename = theClipboard().getAsGraphics(cur, preferedType);
1164 if (filename.empty())
1167 // create inset for graphic
1168 InsetGraphics * inset = new InsetGraphics(cur.buffer());
1169 InsetGraphicsParams params;
1170 params.filename = support::DocFileName(filename.absFileName(), false);
1171 inset->setParams(params);
1177 void pasteSelection(Cursor & cur, ErrorList & errorList)
1179 if (selectionBuffer.empty())
1182 pasteParagraphList(cur, selectionBuffer[0].first,
1183 selectionBuffer[0].second, errorList);
1187 void replaceSelectionWithString(Cursor & cur, docstring const & str)
1190 DocIterator selbeg = cur.selectionBegin();
1192 // Get font setting before we cut, we need a copy here, not a bare reference.
1194 selbeg.paragraph().getFontSettings(cur.buffer()->params(), selbeg.pos());
1196 // Insert the new string
1197 pos_type pos = cur.selEnd().pos();
1198 Paragraph & par = cur.selEnd().paragraph();
1199 docstring::const_iterator cit = str.begin();
1200 docstring::const_iterator end = str.end();
1201 for (; cit != end; ++cit, ++pos)
1202 par.insertChar(pos, *cit, font, cur.buffer()->params().trackChanges);
1204 // Cut the selection
1205 cutSelection(cur, true, false);
1209 void replaceSelection(Cursor & cur)
1211 if (cur.selection())
1212 cutSelection(cur, true, false);
1216 void eraseSelection(Cursor & cur)
1218 //lyxerr << "cap::eraseSelection begin: " << cur << endl;
1219 CursorSlice const & i1 = cur.selBegin();
1220 CursorSlice const & i2 = cur.selEnd();
1221 if (i1.inset().asInsetMath()) {
1224 if (i1.idx() == i2.idx()) {
1225 i1.cell().erase(i1.pos(), i2.pos());
1226 // We may have deleted i1.cell(cur.pos()).
1227 // Make sure that pos is valid.
1228 if (cur.pos() > cur.lastpos())
1229 cur.pos() = cur.lastpos();
1231 InsetMath * p = i1.asInsetMath();
1232 Inset::row_type r1, r2;
1233 Inset::col_type c1, c2;
1234 region(i1, i2, r1, r2, c1, c2);
1235 for (Inset::row_type row = r1; row <= r2; ++row)
1236 for (Inset::col_type col = c1; col <= c2; ++col)
1237 p->cell(p->index(row, col)).clear();
1238 // We've deleted the whole cell. Only pos 0 is valid.
1241 // need a valid cursor. (Lgb)
1242 cur.clearSelection();
1244 lyxerr << "can't erase this selection 1" << endl;
1246 //lyxerr << "cap::eraseSelection end: " << cur << endl;
1250 void selDel(Cursor & cur)
1252 //lyxerr << "cap::selDel" << endl;
1253 if (cur.selection())
1254 eraseSelection(cur);
1258 void selClearOrDel(Cursor & cur)
1260 //lyxerr << "cap::selClearOrDel" << endl;
1261 if (lyxrc.auto_region_delete)
1264 cur.setSelection(false);
1268 docstring grabSelection(Cursor const & cur)
1270 if (!cur.selection())
1274 // grab selection by glueing multiple cells together. This is not what
1275 // we want because selections spanning multiple cells will get "&" and "\\"
1278 for (DocIterator dit = cur.selectionBegin();
1279 dit != cur.selectionEnd(); dit.forwardPos())
1280 os << asString(dit.cell());
1284 CursorSlice i1 = cur.selBegin();
1285 CursorSlice i2 = cur.selEnd();
1287 if (i1.idx() == i2.idx()) {
1288 if (i1.inset().asInsetMath()) {
1289 MathData::const_iterator it = i1.cell().begin();
1290 Buffer * buf = cur.buffer();
1291 return asString(MathData(buf, it + i1.pos(), it + i2.pos()));
1293 return from_ascii("unknown selection 1");
1297 Inset::row_type r1, r2;
1298 Inset::col_type c1, c2;
1299 region(i1, i2, r1, r2, c1, c2);
1302 if (i1.inset().asInsetMath()) {
1303 for (Inset::row_type row = r1; row <= r2; ++row) {
1306 for (Inset::col_type col = c1; col <= c2; ++col) {
1309 data += asString(i1.asInsetMath()->
1310 cell(i1.asInsetMath()->index(row, col)));
1314 data = from_ascii("unknown selection 2");
1320 void dirtyTabularStack(bool b)
1322 dirty_tabular_stack_ = b;
1326 bool tabularStackDirty()
1328 return dirty_tabular_stack_;