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 // Set max_depth for the next paragraph
213 max_depth = tmpbuf->getMaxDepthAfter();
215 // Set the inset owner of this paragraph.
216 tmpbuf->setInsetOwner(target_inset);
217 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
218 // do not track deletion of invalid insets
219 if (Inset * inset = tmpbuf->getInset(i))
220 if (!target_inset->insetAllowed(inset->lyxCode()))
221 tmpbuf->eraseChar(i--, false);
224 tmpbuf->setChange(Change(buffer.params().trackChanges ?
225 Change::INSERTED : Change::UNCHANGED));
228 bool const empty = pars[pit].empty();
230 // Make the buf exactly the same layout as the cursor
232 insertion.begin()->makeSameLayout(pars[pit]);
235 // Prepare the paragraphs and insets for insertion.
236 insertion.swap(in.paragraphs());
238 InsetIterator const i_end = inset_iterator_end(in);
239 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
240 // Even though this will also be done later, it has to be done here
241 // since some inset might going to try to access
242 // the buffer() member.
243 it->setBuffer(const_cast<Buffer &>(buffer));
244 switch (it->lyxCode()) {
246 case MATH_HULL_CODE: {
247 // check for equation labels and resolve duplicates
248 InsetMathHull * ins = it->asInsetMath()->asHullInset();
249 std::vector<InsetLabel *> labels = ins->getLabels();
250 for (size_t i = 0; i != labels.size(); ++i) {
253 InsetLabel * lab = labels[i];
254 docstring const oldname = lab->getParam("name");
255 lab->updateLabel(oldname);
256 // We need to update the buffer reference cache.
258 docstring const newname = lab->getParam("name");
259 if (oldname == newname)
261 // adapt the references
262 for (InsetIterator itt = inset_iterator_begin(in);
263 itt != i_end; ++itt) {
264 if (itt->lyxCode() == REF_CODE) {
265 InsetCommand * ref = itt->asInsetCommand();
266 if (ref->getParam("reference") == oldname)
267 ref->setParam("reference", newname);
268 } else if (itt->lyxCode() == MATH_REF_CODE) {
269 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
270 // this is necessary to prevent an uninitialized
271 // buffer when the RefInset is in a MathBox.
272 // FIXME audit setBuffer calls
273 mi->setBuffer(const_cast<Buffer &>(buffer));
274 if (mi->getTarget() == oldname)
275 mi->changeTarget(newname);
283 // check for duplicates
284 InsetLabel & lab = static_cast<InsetLabel &>(*it);
285 docstring const oldname = lab.getParam("name");
286 lab.updateLabel(oldname);
287 // We need to update the buffer reference cache.
289 docstring const newname = lab.getParam("name");
290 if (oldname == newname)
292 // adapt the references
293 for (InsetIterator itt = inset_iterator_begin(in); itt != i_end; ++itt) {
294 if (itt->lyxCode() == REF_CODE) {
295 InsetCommand & ref = static_cast<InsetCommand &>(*itt);
296 if (ref.getParam("reference") == oldname)
297 ref.setParam("reference", newname);
298 } else if (itt->lyxCode() == MATH_REF_CODE) {
299 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
300 // this is necessary to prevent an uninitialized
301 // buffer when the RefInset is in a MathBox.
302 // FIXME audit setBuffer calls
303 mi->setBuffer(const_cast<Buffer &>(buffer));
304 if (mi->getTarget() == oldname)
305 mi->changeTarget(newname);
312 InsetInclude & inc = static_cast<InsetInclude &>(*it);
314 // We need to update the list of included files.
320 // check for duplicates
321 InsetBibitem & bib = static_cast<InsetBibitem &>(*it);
322 docstring const oldkey = bib.getParam("key");
323 bib.updateCommand(oldkey, false);
324 // We need to update the buffer reference cache.
326 docstring const newkey = bib.getParam("key");
327 if (oldkey == newkey)
329 // adapt the references
330 for (InsetIterator itt = inset_iterator_begin(in);
331 itt != i_end; ++itt) {
332 if (itt->lyxCode() == CITE_CODE) {
333 InsetCommand * ref = itt->asInsetCommand();
334 if (ref->getParam("key") == oldkey)
335 ref->setParam("key", newkey);
342 // check if branch is known to target buffer
344 InsetBranch & br = static_cast<InsetBranch &>(*it);
345 docstring const name = br.branch();
348 bool const is_child = (&buffer != buffer.masterBuffer());
349 BranchList branchlist = buffer.params().branchlist();
350 if ((!is_child && branchlist.find(name))
351 || (is_child && (branchlist.find(name)
352 || buffer.masterBuffer()->params().branchlist().find(name))))
355 // This is for a temporary buffer, so simply create the branch.
356 // Must not use lyx::dispatch(), since tmpbuffer has no view.
358 tmpbuffer->dispatch(FuncRequest(LFUN_BRANCH_ADD, name), dr);
360 docstring text = bformat(
361 _("The pasted branch \"%1$s\" is undefined.\n"
362 "Do you want to add it to the document's branch list?"),
364 if (frontend::Alert::prompt(_("Unknown branch"),
365 text, 0, 1, _("&Add"), _("&Don't Add")) != 0)
367 lyx::dispatch(FuncRequest(LFUN_BRANCH_ADD, name));
369 // We need to update the list of branches.
378 insertion.swap(in.paragraphs());
380 // Split the paragraph for inserting the buf if necessary.
382 breakParagraphConservative(buffer.params(), pars, pit, pos);
386 pars.insert(boost::next(pars.begin(), pit),
390 // merge the empty par with the last par of the insertion
391 mergeParagraph(buffer.params(), pars,
392 pit + insertion.size() - 1);
394 pars.insert(boost::next(pars.begin(), pit + 1),
398 // merge the first par of the insertion with the current par
399 mergeParagraph(buffer.params(), pars, pit);
402 // Store the new cursor position.
403 pit_type last_paste = pit + insertion.size() - 1;
404 pit_type startpit = pit;
406 pos = pars[last_paste].size();
408 // FIXME Should we do it here, or should we let updateBuffer() do it?
409 // Set paragraph buffers. It's important to do this right away
410 // before something calls Inset::buffer() and causes a crash.
411 for (pit_type p = startpit; p <= pit; ++p)
412 pars[p].setBuffer(const_cast<Buffer &>(buffer));
414 // Join (conditionally) last pasted paragraph with next one, i.e.,
415 // the tail of the spliced document paragraph
416 if (!empty && last_paste + 1 != pit_type(pars.size())) {
417 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
418 mergeParagraph(buffer.params(), pars, last_paste);
419 } else if (pars[last_paste + 1].empty()) {
420 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
421 mergeParagraph(buffer.params(), pars, last_paste);
422 } else if (pars[last_paste].empty()) {
423 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
424 mergeParagraph(buffer.params(), pars, last_paste);
426 pars[last_paste + 1].stripLeadingSpaces(buffer.params().trackChanges);
431 return PasteReturnValue(pit, pos, need_update);
435 PitPosPair eraseSelectionHelper(BufferParams const & params,
436 ParagraphList & pars,
437 pit_type startpit, pit_type endpit,
438 int startpos, int endpos)
440 // Start of selection is really invalid.
441 if (startpit == pit_type(pars.size()) ||
442 (startpos > pars[startpit].size()))
443 return PitPosPair(endpit, endpos);
445 // Start and end is inside same paragraph
446 if (endpit == pit_type(pars.size()) || startpit == endpit) {
447 endpos -= pars[startpit].eraseChars(startpos, endpos, params.trackChanges);
448 return PitPosPair(endpit, endpos);
451 for (pit_type pit = startpit; pit != endpit + 1;) {
452 pos_type const left = (pit == startpit ? startpos : 0);
453 pos_type right = (pit == endpit ? endpos : pars[pit].size() + 1);
454 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.trackChanges);
456 // Logically erase only, including the end-of-paragraph character
457 pars[pit].eraseChars(left, right, params.trackChanges);
459 // Separate handling of paragraph break:
460 if (merge && pit != endpit &&
462 || pars[pit].hasSameLayout(pars[endpit])
463 || pars[endpit].size() == endpos)) {
464 if (pit + 1 == endpit)
465 endpos += pars[pit].size();
466 mergeParagraph(params, pars, pit);
472 // Ensure legal cursor pos:
475 return PitPosPair(endpit, endpos);
479 void putClipboard(ParagraphList const & paragraphs,
480 DocumentClassConstPtr docclass, docstring const & plaintext)
482 // This used to need to be static to avoid a memory leak. It no longer needs
483 // to be so, but the alternative is to construct a new one of these (with a
484 // new temporary directory, etc) every time, and then to destroy it. So maybe
485 // it's worth just keeping this one around.
486 static Buffer * staticbuffer = theBufferList().newInternalBuffer(
487 FileName::tempName("clipboard.internal").absFileName());
489 // These two things only really need doing the first time.
490 staticbuffer->setUnnamed(true);
491 staticbuffer->inset().setBuffer(*staticbuffer);
493 // Use a clone for the complicated stuff so that we do not need to clean
494 // up in order to avoid a crash.
495 Buffer * buffer = staticbuffer->cloneBufferOnly();
496 LASSERT(buffer, return);
498 // This needs doing every time.
499 buffer->params().setDocumentClass(docclass);
501 // we will use pasteSelectionHelper to copy the paragraphs into the
502 // temporary Buffer, since it does a lot of things to fix them up.
503 DocIterator dit = doc_iterator_begin(buffer, &buffer->inset());
505 pasteSelectionHelper(dit, paragraphs, docclass, buffer, el);
507 // We don't want to produce images that are not used. Therefore,
508 // output formulas as MathML. Even if this is not understood by all
509 // applications, the number that can parse it should go up in the future.
510 buffer->params().html_math_output = BufferParams::MathML;
512 // Make sure MarkAsExporting is deleted before buffer is
514 // The Buffer is being used to export. This is necessary so that the
515 // updateMacros call will record the needed information.
516 MarkAsExporting mex(buffer);
518 buffer->updateBuffer(Buffer::UpdateMaster, OutputUpdate);
519 buffer->updateMacros();
520 buffer->updateMacroInstances(OutputUpdate);
525 if (buffer->write(oslyx))
529 odocstringstream oshtml;
530 OutputParams runparams(encodings.fromLyXName("utf8"));
531 // We do not need to produce images, etc.
532 runparams.dryrun = true;
533 // We are not interested in errors (bug 8866)
534 runparams.silent = true;
535 buffer->writeLyXHTMLSource(oshtml, runparams, Buffer::FullSource);
537 theClipboard().put(lyx, oshtml.str(), plaintext);
545 /// return true if the whole ParagraphList is deleted
546 static bool isFullyDeleted(ParagraphList const & pars)
548 pit_type const pars_size = static_cast<pit_type>(pars.size());
550 // check all paragraphs
551 for (pit_type pit = 0; pit < pars_size; ++pit) {
552 if (!pars[pit].empty()) // prevent assertion failure
553 if (!pars[pit].isDeleted(0, pars[pit].size()))
560 void copySelectionHelper(Buffer const & buf, Text const & text,
561 pit_type startpit, pit_type endpit,
562 int start, int end, DocumentClassConstPtr dc, CutStack & cutstack)
564 ParagraphList const & pars = text.paragraphs();
566 // In most of these cases, we can try to recover.
567 LASSERT(0 <= start, start = 0);
568 LASSERT(start <= pars[startpit].size(), start = pars[startpit].size());
569 LASSERT(0 <= end, end = 0);
570 LASSERT(end <= pars[endpit].size(), end = pars[endpit].size());
571 LASSERT(startpit != endpit || start <= end, return);
573 // Clone the paragraphs within the selection.
574 ParagraphList copy_pars(boost::next(pars.begin(), startpit),
575 boost::next(pars.begin(), endpit + 1));
577 // Remove the end of the last paragraph; afterwards, remove the
578 // beginning of the first paragraph. Keep this order - there may only
579 // be one paragraph! Do not track deletions here; this is an internal
580 // action not visible to the user
582 Paragraph & back = copy_pars.back();
583 back.eraseChars(end, back.size(), false);
584 Paragraph & front = copy_pars.front();
585 front.eraseChars(0, start, false);
587 ParagraphList::iterator it = copy_pars.begin();
588 ParagraphList::iterator it_end = copy_pars.end();
590 for (; it != it_end; ++it) {
591 // Since we have a copy of the paragraphs, the insets
592 // do not have a proper buffer reference. It makes
593 // sense to add them temporarily, because the
594 // operations below depend on that (acceptChanges included).
595 it->setBuffer(const_cast<Buffer &>(buf));
596 // PassThru paragraphs have the Language
597 // latex_language. This is invalid for others, so we
598 // need to change it to the buffer language.
599 if (it->isPassThru())
600 it->changeLanguage(buf.params(),
601 latex_language, buf.language());
604 // do not copy text (also nested in insets) which is marked as
605 // deleted, unless the whole selection was deleted
606 if (!isFullyDeleted(copy_pars))
607 acceptChanges(copy_pars, buf.params());
609 rejectChanges(copy_pars, buf.params());
612 // do some final cleanup now, to make sure that the paragraphs
613 // are not linked to something else.
614 it = copy_pars.begin();
615 for (; it != it_end; ++it) {
616 it->setBuffer(*static_cast<Buffer *>(0));
617 it->setInsetOwner(0);
620 cutstack.push(make_pair(copy_pars, dc));
630 void region(CursorSlice const & i1, CursorSlice const & i2,
631 Inset::row_type & r1, Inset::row_type & r2,
632 Inset::col_type & c1, Inset::col_type & c2)
634 Inset & p = i1.inset();
635 c1 = p.col(i1.idx());
636 c2 = p.col(i2.idx());
639 r1 = p.row(i1.idx());
640 r2 = p.row(i2.idx());
646 docstring grabAndEraseSelection(Cursor & cur)
648 if (!cur.selection())
650 docstring res = grabSelection(cur);
656 bool reduceSelectionToOneCell(Cursor & cur)
658 if (!cur.selection() || !cur.inMathed())
661 CursorSlice i1 = cur.selBegin();
662 CursorSlice i2 = cur.selEnd();
663 if (!i1.inset().asInsetMath())
666 // the easy case: do nothing if only one cell is selected
667 if (i1.idx() == i2.idx())
672 cur.top().pos() = cur.top().lastpos();
678 bool multipleCellsSelected(Cursor const & cur)
680 if (!cur.selection() || !cur.inMathed())
683 CursorSlice i1 = cur.selBegin();
684 CursorSlice i2 = cur.selEnd();
685 if (!i1.inset().asInsetMath())
688 if (i1.idx() == i2.idx())
695 void switchBetweenClasses(DocumentClassConstPtr oldone,
696 DocumentClassConstPtr newone, InsetText & in, ErrorList & errorlist)
700 LBUFERR(!in.paragraphs().empty());
701 if (oldone == newone)
704 DocumentClass const & oldtc = *oldone;
705 DocumentClass const & newtc = *newone;
708 ParIterator it = par_iterator_begin(in);
709 ParIterator end = par_iterator_end(in);
710 // for remembering which layouts we've had to add
711 set<docstring> newlayouts;
712 for (; it != end; ++it) {
713 docstring const name = it->layout().name();
715 // the pasted text will keep their own layout name. If this layout does
716 // not exist in the new document, it will behave like a standard layout.
717 bool const added_one = newtc.addLayoutIfNeeded(name);
719 newlayouts.insert(name);
721 if (added_one || newlayouts.find(name) != newlayouts.end()) {
723 docstring const s = bformat(_("Layout `%1$s' was not found."), name);
725 ErrorItem(_("Layout Not Found"), s, it->id(), 0, it->size()));
728 if (in.usePlainLayout())
729 it->setLayout(newtc.plainLayout());
731 it->setLayout(newtc[name]);
735 InsetIterator const i_end = inset_iterator_end(in);
736 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
737 if (it->lyxCode() != FLEX_CODE)
738 // FIXME: Should we verify all InsetCollapsable?
741 docstring const layoutName = it->layoutName();
742 docstring const & n = newone->insetLayout(layoutName).name();
743 bool const is_undefined = n.empty() ||
744 n == DocumentClass::plainInsetLayout().name();
748 // The flex inset is undefined in newtc
749 docstring const oldname = from_utf8(oldtc.name());
750 docstring const newname = from_utf8(newtc.name());
752 if (oldname == newname)
753 s = bformat(_("Flex inset %1$s is undefined after "
754 "reloading `%2$s' layout."), layoutName, oldname);
756 s = bformat(_("Flex inset %1$s is undefined because of "
757 "conversion from `%2$s' layout to `%3$s'."),
758 layoutName, oldname, newname);
759 // To warn the user that something had to be done.
760 errorlist.push_back(ErrorItem(
761 _("Undefined flex inset"),
762 s, it.paragraph().id(), it.pos(), it.pos() + 1));
767 vector<docstring> availableSelections(Buffer const * buf)
769 vector<docstring> selList;
773 CutStack::const_iterator cit = theCuts.begin();
774 CutStack::const_iterator end = theCuts.end();
775 for (; cit != end; ++cit) {
776 // we do not use cit-> here because gcc 2.9x does not
778 ParagraphList const & pars = (*cit).first;
780 ParagraphList::const_iterator pit = pars.begin();
781 ParagraphList::const_iterator pend = pars.end();
782 for (; pit != pend; ++pit) {
783 Paragraph par(*pit, 0, 26);
784 // adapt paragraph to current buffer.
785 par.setBuffer(const_cast<Buffer &>(*buf));
786 asciiSel += par.asString(AS_STR_INSETS);
787 if (asciiSel.size() > 25) {
788 asciiSel.replace(22, docstring::npos,
794 selList.push_back(asciiSel);
801 size_type numberOfSelections()
803 return theCuts.size();
807 void cutSelection(Cursor & cur, bool doclear, bool realcut)
809 // This doesn't make sense, if there is no selection
810 if (!cur.selection())
813 // OK, we have a selection. This is always between cur.selBegin()
816 if (cur.inTexted()) {
817 Text * text = cur.text();
822 // make sure that the depth behind the selection are restored, too
823 cur.recordUndoSelection();
824 pit_type begpit = cur.selBegin().pit();
825 pit_type endpit = cur.selEnd().pit();
827 int endpos = cur.selEnd().pos();
829 BufferParams const & bp = cur.buffer()->params();
831 copySelectionHelper(*cur.buffer(),
834 cur.selBegin().pos(), endpos,
835 bp.documentClassPtr(), theCuts);
836 // Stuff what we got on the clipboard.
837 // Even if there is no selection.
838 putClipboard(theCuts[0].first, theCuts[0].second,
839 cur.selectionAsString(true));
842 if (begpit != endpit)
843 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
845 boost::tie(endpit, endpos) =
846 eraseSelectionHelper(bp,
849 cur.selBegin().pos(), endpos);
851 // cutSelection can invalidate the cursor so we need to set
853 // we prefer the end for when tracking changes
857 // sometimes necessary
859 && text->paragraphs()[begpit].stripLeadingSpaces(bp.trackChanges))
862 // need a valid cursor. (Lgb)
863 cur.clearSelection();
865 // After a cut operation, we must make sure that the Buffer is updated
866 // because some further operation might need updated label information for
867 // example. So we cannot just use "cur.forceBufferUpdate()" here.
869 cur.buffer()->updateBuffer();
871 // tell tabular that a recent copy happened
872 dirtyTabularStack(false);
875 if (cur.inMathed()) {
876 if (cur.selBegin().idx() != cur.selEnd().idx()) {
877 // The current selection spans more than one cell.
879 cur.recordUndoInset();
881 // Record only the current cell to avoid a jumping
892 void copySelection(Cursor const & cur)
894 copySelection(cur, cur.selectionAsString(true));
898 void copyInset(Cursor const & cur, Inset * inset, docstring const & plaintext)
902 BufferParams const & bp = cur.buffer()->params();
903 par.setLayout(bp.documentClass().plainLayout());
904 Font font(inherit_font, bp.language);
905 par.insertInset(0, inset, font, Change(Change::UNCHANGED));
907 theCuts.push(make_pair(pars, bp.documentClassPtr()));
909 // stuff the selection onto the X clipboard, from an explicit copy request
910 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
916 void copySelectionToStack(Cursor const & cur, CutStack & cutstack)
918 // this doesn't make sense, if there is no selection
919 if (!cur.selection())
922 // copySelection can not yet handle the case of cross idx selection
923 if (cur.selBegin().idx() != cur.selEnd().idx())
926 if (cur.inTexted()) {
927 Text * text = cur.text();
929 // ok we have a selection. This is always between cur.selBegin()
930 // and sel_end cursor
932 // copy behind a space if there is one
933 ParagraphList & pars = text->paragraphs();
934 pos_type pos = cur.selBegin().pos();
935 pit_type par = cur.selBegin().pit();
936 while (pos < pars[par].size() &&
937 pars[par].isLineSeparator(pos) &&
938 (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
941 copySelectionHelper(*cur.buffer(), *text, par, cur.selEnd().pit(),
942 pos, cur.selEnd().pos(),
943 cur.buffer()->params().documentClassPtr(), cutstack);
945 // Reset the dirty_tabular_stack_ flag only when something
946 // is copied to the clipboard (not to the selectionBuffer).
947 if (&cutstack == &theCuts)
948 dirtyTabularStack(false);
951 if (cur.inMathed()) {
952 //lyxerr << "copySelection in mathed" << endl;
955 BufferParams const & bp = cur.buffer()->params();
956 // FIXME This should be the plain layout...right?
957 par.setLayout(bp.documentClass().plainLayout());
958 par.insert(0, grabSelection(cur), Font(), Change(Change::UNCHANGED));
960 cutstack.push(make_pair(pars, bp.documentClassPtr()));
967 void copySelectionToStack()
969 if (!selectionBuffer.empty())
970 theCuts.push(selectionBuffer[0]);
974 void copySelection(Cursor const & cur, docstring const & plaintext)
976 // In tablemode, because copy and paste actually use special table stack
977 // we do not attempt to get selected paragraphs under cursor. Instead, a
978 // paragraph with the plain text version is generated so that table cells
979 // can be pasted as pure text somewhere else.
980 if (cur.selBegin().idx() != cur.selEnd().idx()) {
983 BufferParams const & bp = cur.buffer()->params();
984 par.setLayout(bp.documentClass().plainLayout());
985 par.insert(0, plaintext, Font(), Change(Change::UNCHANGED));
987 theCuts.push(make_pair(pars, bp.documentClassPtr()));
989 copySelectionToStack(cur, theCuts);
992 // stuff the selection onto the X clipboard, from an explicit copy request
993 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
997 void saveSelection(Cursor const & cur)
999 // This function is called, not when a selection is formed, but when
1000 // a selection is cleared. Therefore, multiple keyboard selection
1001 // will not repeatively trigger this function (bug 3877).
1003 && cur.selBegin() == cur.bv().cursor().selBegin()
1004 && cur.selEnd() == cur.bv().cursor().selEnd()) {
1005 LYXERR(Debug::SELECTION, "saveSelection: '" << cur.selectionAsString(true) << "'");
1006 copySelectionToStack(cur, selectionBuffer);
1013 return !selectionBuffer.empty();
1017 void clearSelection()
1019 selectionBuffer.clear();
1023 void clearCutStack()
1029 docstring selection(size_t sel_index)
1031 return sel_index < theCuts.size()
1032 ? theCuts[sel_index].first.back().asString(AS_STR_INSETS | AS_STR_NEWLINES)
1037 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
1038 DocumentClassConstPtr docclass, ErrorList & errorList)
1040 if (cur.inTexted()) {
1041 Text * text = cur.text();
1044 PasteReturnValue prv =
1045 pasteSelectionHelper(cur, parlist, docclass, 0, errorList);
1046 cur.forceBufferUpdate();
1047 cur.clearSelection();
1048 text->setCursor(cur, prv.par, prv.pos);
1051 // mathed is handled in InsetMathNest/InsetMathGrid
1052 LATTEST(!cur.inMathed());
1056 bool pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
1058 // this does not make sense, if there is nothing to paste
1059 if (!checkPastePossible(sel_index))
1063 pasteParagraphList(cur, theCuts[sel_index].first,
1064 theCuts[sel_index].second, errorList);
1069 bool pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs,
1070 Clipboard::TextType type)
1072 // Use internal clipboard if it is the most recent one
1073 // This overrides asParagraphs and type on purpose!
1074 if (theClipboard().isInternal())
1075 return pasteFromStack(cur, errorList, 0);
1077 // First try LyX format
1078 if ((type == Clipboard::LyXTextType ||
1079 type == Clipboard::LyXOrPlainTextType ||
1080 type == Clipboard::AnyTextType) &&
1081 theClipboard().hasTextContents(Clipboard::LyXTextType)) {
1082 string lyx = theClipboard().getAsLyX();
1084 // For some strange reason gcc 3.2 and 3.3 do not accept
1085 // Buffer buffer(string(), false);
1086 Buffer buffer("", false);
1087 buffer.setUnnamed(true);
1088 if (buffer.readString(lyx)) {
1090 pasteParagraphList(cur, buffer.paragraphs(),
1091 buffer.params().documentClassPtr(), errorList);
1097 // Then try TeX and HTML
1098 Clipboard::TextType types[2] = {Clipboard::HtmlTextType, Clipboard::LaTeXTextType};
1099 string names[2] = {"html", "latexclipboard"};
1100 for (int i = 0; i < 2; ++i) {
1101 if (type != types[i] && type != Clipboard::AnyTextType)
1103 bool available = theClipboard().hasTextContents(types[i]);
1105 // If a specific type was explicitly requested, try to
1106 // interpret plain text: The user told us that the clipboard
1107 // contents is in the desired format
1108 if (!available && type == types[i]) {
1109 types[i] = Clipboard::PlainTextType;
1110 available = theClipboard().hasTextContents(types[i]);
1114 docstring text = theClipboard().getAsText(types[i]);
1115 available = !text.empty();
1117 // For some strange reason gcc 3.2 and 3.3 do not accept
1118 // Buffer buffer(string(), false);
1119 Buffer buffer("", false);
1120 buffer.setUnnamed(true);
1121 available = buffer.importString(names[i], text, errorList);
1123 available = !buffer.paragraphs().empty();
1124 if (available && !buffer.paragraphs()[0].empty()) {
1126 pasteParagraphList(cur, buffer.paragraphs(),
1127 buffer.params().documentClassPtr(), errorList);
1134 // Then try plain text
1135 docstring const text = theClipboard().getAsText(Clipboard::PlainTextType);
1140 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1142 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1147 void pasteSimpleText(Cursor & cur, bool asParagraphs)
1150 // Use internal clipboard if it is the most recent one
1151 if (theClipboard().isInternal()) {
1152 if (!checkPastePossible(0))
1155 ParagraphList const & pars = theCuts[0].first;
1156 ParagraphList::const_iterator it = pars.begin();
1157 for (; it != pars.end(); ++it) {
1158 if (it != pars.begin())
1160 text += (*it).asString();
1162 asParagraphs = false;
1164 // Then try plain text
1165 text = theClipboard().getAsText(Clipboard::PlainTextType);
1172 cutSelection(cur, true, false);
1174 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1176 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1180 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
1181 Clipboard::GraphicsType preferedType)
1183 LASSERT(theClipboard().hasGraphicsContents(preferedType), return);
1185 // get picture from clipboard
1186 FileName filename = theClipboard().getAsGraphics(cur, preferedType);
1187 if (filename.empty())
1190 // create inset for graphic
1191 InsetGraphics * inset = new InsetGraphics(cur.buffer());
1192 InsetGraphicsParams params;
1193 params.filename = support::DocFileName(filename.absFileName(), false);
1194 inset->setParams(params);
1200 void pasteSelection(Cursor & cur, ErrorList & errorList)
1202 if (selectionBuffer.empty())
1205 pasteParagraphList(cur, selectionBuffer[0].first,
1206 selectionBuffer[0].second, errorList);
1210 void replaceSelectionWithString(Cursor & cur, docstring const & str)
1213 DocIterator selbeg = cur.selectionBegin();
1215 // Get font setting before we cut, we need a copy here, not a bare reference.
1217 selbeg.paragraph().getFontSettings(cur.buffer()->params(), selbeg.pos());
1219 // Insert the new string
1220 pos_type pos = cur.selEnd().pos();
1221 Paragraph & par = cur.selEnd().paragraph();
1222 docstring::const_iterator cit = str.begin();
1223 docstring::const_iterator end = str.end();
1224 for (; cit != end; ++cit, ++pos)
1225 par.insertChar(pos, *cit, font, cur.buffer()->params().trackChanges);
1227 // Cut the selection
1228 cutSelection(cur, true, false);
1232 void replaceSelection(Cursor & cur)
1234 if (cur.selection())
1235 cutSelection(cur, true, false);
1239 void eraseSelection(Cursor & cur)
1241 //lyxerr << "cap::eraseSelection begin: " << cur << endl;
1242 CursorSlice const & i1 = cur.selBegin();
1243 CursorSlice const & i2 = cur.selEnd();
1244 if (i1.inset().asInsetMath()) {
1247 if (i1.idx() == i2.idx()) {
1248 i1.cell().erase(i1.pos(), i2.pos());
1249 // We may have deleted i1.cell(cur.pos()).
1250 // Make sure that pos is valid.
1251 if (cur.pos() > cur.lastpos())
1252 cur.pos() = cur.lastpos();
1254 InsetMath * p = i1.asInsetMath();
1255 Inset::row_type r1, r2;
1256 Inset::col_type c1, c2;
1257 region(i1, i2, r1, r2, c1, c2);
1258 for (Inset::row_type row = r1; row <= r2; ++row)
1259 for (Inset::col_type col = c1; col <= c2; ++col)
1260 p->cell(p->index(row, col)).clear();
1261 // We've deleted the whole cell. Only pos 0 is valid.
1264 // need a valid cursor. (Lgb)
1265 cur.clearSelection();
1267 lyxerr << "can't erase this selection 1" << endl;
1269 //lyxerr << "cap::eraseSelection end: " << cur << endl;
1273 void selDel(Cursor & cur)
1275 //lyxerr << "cap::selDel" << endl;
1276 if (cur.selection())
1277 eraseSelection(cur);
1281 void selClearOrDel(Cursor & cur)
1283 //lyxerr << "cap::selClearOrDel" << endl;
1284 if (lyxrc.auto_region_delete)
1287 cur.setSelection(false);
1291 docstring grabSelection(Cursor const & cur)
1293 if (!cur.selection())
1297 // grab selection by glueing multiple cells together. This is not what
1298 // we want because selections spanning multiple cells will get "&" and "\\"
1301 for (DocIterator dit = cur.selectionBegin();
1302 dit != cur.selectionEnd(); dit.forwardPos())
1303 os << asString(dit.cell());
1307 CursorSlice i1 = cur.selBegin();
1308 CursorSlice i2 = cur.selEnd();
1310 if (i1.idx() == i2.idx()) {
1311 if (i1.inset().asInsetMath()) {
1312 MathData::const_iterator it = i1.cell().begin();
1313 Buffer * buf = cur.buffer();
1314 return asString(MathData(buf, it + i1.pos(), it + i2.pos()));
1316 return from_ascii("unknown selection 1");
1320 Inset::row_type r1, r2;
1321 Inset::col_type c1, c2;
1322 region(i1, i2, r1, r2, c1, c2);
1325 if (i1.inset().asInsetMath()) {
1326 for (Inset::row_type row = r1; row <= r2; ++row) {
1329 for (Inset::col_type col = c1; col <= c2; ++col) {
1332 data += asString(i1.asInsetMath()->
1333 cell(i1.asInsetMath()->index(row, col)));
1337 data = from_ascii("unknown selection 2");
1343 void dirtyTabularStack(bool b)
1345 dirty_tabular_stack_ = b;
1349 bool tabularStackDirty()
1351 return dirty_tabular_stack_;