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"
19 #include "BranchList.h"
21 #include "buffer_funcs.h"
22 #include "BufferList.h"
23 #include "BufferParams.h"
24 #include "BufferView.h"
28 #include "ErrorList.h"
30 #include "FuncRequest.h"
31 #include "InsetIterator.h"
32 #include "InsetList.h"
37 #include "Paragraph.h"
38 #include "ParagraphParameters.h"
39 #include "ParIterator.h"
40 #include "TextClass.h"
42 #include "insets/InsetBibitem.h"
43 #include "insets/InsetBranch.h"
44 #include "insets/InsetCitation.h"
45 #include "insets/InsetCommand.h"
46 #include "insets/InsetFlex.h"
47 #include "insets/InsetGraphics.h"
48 #include "insets/InsetGraphicsParams.h"
49 #include "insets/InsetInclude.h"
50 #include "insets/InsetLabel.h"
51 #include "insets/InsetTabular.h"
53 #include "mathed/MathData.h"
54 #include "mathed/InsetMath.h"
55 #include "mathed/InsetMathHull.h"
56 #include "mathed/InsetMathRef.h"
57 #include "mathed/MathSupport.h"
59 #include "support/debug.h"
60 #include "support/docstream.h"
61 #include "support/gettext.h"
62 #include "support/lassert.h"
63 #include "support/limited_stack.h"
64 #include "support/lstrings.h"
65 #include "support/lyxalgo.h"
66 #include "support/TempFile.h"
67 #include "support/unique_ptr.h"
69 #include "frontends/alert.h"
70 #include "frontends/Clipboard.h"
71 #include "frontends/Selection.h"
77 using namespace lyx::support;
78 using lyx::frontend::Clipboard;
84 typedef pair<pit_type, int> PitPosPair;
86 typedef limited_stack<pair<ParagraphList, DocumentClassConstPtr> > CutStack;
89 // persistent selection, cleared until the next selection
90 CutStack selectionBuffer(1);
91 // temporary scratch area
94 // store whether the tabular stack is newer than the normal copy stack
95 // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
96 // when we (hopefully) have a one-for-all paste mechanism.
97 bool dirty_tabular_stack_ = false;
100 bool checkPastePossible(int index)
102 return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
106 struct PasteReturnValue {
107 PasteReturnValue(pit_type r_pit, pos_type r_pos, bool r_nu) :
108 pit(r_pit), pos(r_pos), needupdate(r_nu)
117 pasteSelectionHelper(DocIterator const & cur, ParagraphList const & parlist,
118 DocumentClassConstPtr oldDocClass, cap::BranchAction branchAction,
119 ErrorList & errorlist)
121 Buffer const & buffer = *cur.buffer();
122 pit_type pit = cur.pit();
123 pos_type pos = cur.pos();
124 bool need_update = false;
127 return PasteReturnValue(pit, pos, need_update);
129 // Check whether we paste into an inset that does not
130 // produce output (needed for label duplicate check)
131 bool in_active_inset = cur.paragraph().inInset().producesOutput();
132 if (in_active_inset) {
133 for (size_type sl = 0 ; sl < cur.depth() ; ++sl) {
134 Paragraph const & outer_par = cur[sl].paragraph();
135 if (!outer_par.inInset().producesOutput()) {
136 in_active_inset = false;
142 InsetText * target_inset = cur.inset().asInsetText();
144 InsetTabular * it = cur.inset().asInsetTabular();
145 target_inset = it ? it->cell(cur.idx())->asInsetText() : nullptr;
147 LASSERT(target_inset, return PasteReturnValue(pit, pos, need_update));
149 ParagraphList & pars = target_inset->paragraphs();
150 LASSERT(pos <= pars[pit].size(),
151 return PasteReturnValue(pit, pos, need_update));
153 // Make a copy of the CaP paragraphs.
154 ParagraphList insertion = parlist;
156 // Now remove all out of the pars which is NOT allowed in the
157 // new environment and set also another font if that is required.
159 // Merge paragraphs that are to be pasted into a text inset
160 // that does not allow multiple pars.
161 InsetText * inset_text = target_inset->asInsetText();
162 if (inset_text && !inset_text->allowMultiPar()) {
163 while (insertion.size() > 1)
164 mergeParagraph(buffer.params(), insertion, 0);
167 // Convert newline to paragraph break in ParbreakIsNewline
168 if (target_inset->getLayout().parbreakIsNewline()
169 || pars[pit].layout().parbreak_is_newline) {
170 for (size_t i = 0; i != insertion.size(); ++i) {
171 for (pos_type j = 0; j != insertion[i].size(); ++j) {
172 if (insertion[i].isNewline(j)) {
173 // do not track deletion of newline
174 insertion[i].eraseChar(j, false);
175 insertion[i].setInsetOwner(target_inset);
176 breakParagraphConservative(
185 // Prevent to paste uncodable characters in verbatim and ERT.
186 // The encoding is inherited from the context here.
187 docstring uncodable_content;
188 if (target_inset->getLayout().isPassThru() && cur.getEncoding()) {
189 odocstringstream res;
190 Encoding const * e = cur.getEncoding();
191 for (size_t i = 0; i != insertion.size(); ++i) {
192 pos_type end = insertion[i].size();
193 for (pos_type j = 0; j != end; ++j) {
195 if (insertion[i].isInset(j))
197 char_type const c = insertion[i].getChar(j);
198 if (!e->encodable(c)) {
199 // do not track deletion
201 insertion[i].eraseChar(j, false);
207 docstring const uncodable = res.str();
208 if (!uncodable.empty()) {
209 if (uncodable.size() == 1)
210 uncodable_content = bformat(_("The character \"%1$s\" is uncodable in this verbatim context "
211 "and thus has not been pasted."),
214 uncodable_content = bformat(_("The characters \"%1$s\" are uncodable in this verbatim context "
215 "and thus have not been pasted."),
220 // set the paragraphs to plain layout if necessary
221 DocumentClassConstPtr newDocClass = buffer.params().documentClassPtr();
222 Layout const & plainLayout = newDocClass->plainLayout();
223 Layout const & defaultLayout = newDocClass->defaultLayout();
224 if (cur.inset().usePlainLayout()) {
225 bool forcePlainLayout = target_inset->forcePlainLayout();
226 for (auto & par : insertion) {
227 Layout const & parLayout = par.layout();
228 if (forcePlainLayout || parLayout == defaultLayout)
229 par.setLayout(plainLayout);
232 // check if we need to reset from plain layout
233 for (auto & par : insertion) {
234 Layout const & parLayout = par.layout();
235 if (parLayout == plainLayout)
236 par.setLayout(defaultLayout);
240 InsetText in(cur.buffer());
241 // Make sure there is no class difference.
242 in.paragraphs().clear();
243 // This works without copying any paragraph data because we have
244 // a specialized swap method for ParagraphList. This is important
245 // since we store pointers to insets at some places and we don't
246 // want to invalidate them.
247 insertion.swap(in.paragraphs());
248 cap::switchBetweenClasses(oldDocClass, newDocClass, in, errorlist);
249 // Do this here since switchBetweenClasses clears the errorlist
250 if (!uncodable_content.empty())
251 errorlist.push_back(ErrorItem(_("Uncodable content"), uncodable_content));
252 insertion.swap(in.paragraphs());
254 ParagraphList::iterator tmpbuf = insertion.begin();
255 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
257 depth_type max_depth = pars[pit].getMaxDepthAfter();
259 for (; tmpbuf != insertion.end(); ++tmpbuf) {
260 // If we have a negative jump so that the depth would
261 // go below 0 depth then we have to redo the delta to
262 // this new max depth level so that subsequent
263 // paragraphs are aligned correctly to this paragraph
265 if (int(tmpbuf->params().depth()) + depth_delta < 0)
268 // Set the right depth so that we are not too deep or shallow.
269 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
270 if (tmpbuf->params().depth() > max_depth)
271 tmpbuf->params().depth(max_depth);
273 // Set max_depth for the next paragraph
274 max_depth = tmpbuf->getMaxDepthAfter();
276 // Set the inset owner of this paragraph.
277 tmpbuf->setInsetOwner(target_inset);
278 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
279 // do not track deletion of invalid insets
280 if (Inset * inset = tmpbuf->getInset(i))
281 if (!target_inset->insetAllowed(inset->lyxCode()))
282 tmpbuf->eraseChar(i--, false);
285 if (lyxrc.ct_markup_copied)
286 tmpbuf->setChange(Change(buffer.params().track_changes ?
287 Change::INSERTED : Change::UNCHANGED));
290 bool const empty = pars[pit].empty();
292 // Make the buf exactly the same layout as the cursor
294 insertion.begin()->makeSameLayout(pars[pit]);
297 // Prepare the paragraphs and insets for insertion.
298 insertion.swap(in.paragraphs());
300 InsetIterator const i_end = inset_iterator_end(in);
301 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
302 // Even though this will also be done later, it has to be done here
303 // since some inset might try to access the buffer() member.
304 it->setBuffer(const_cast<Buffer &>(buffer));
305 switch (it->lyxCode()) {
307 case MATH_HULL_CODE: {
308 // check for equation labels and resolve duplicates
309 InsetMathHull * ins = it->asInsetMath()->asHullInset();
310 std::vector<InsetLabel *> labels = ins->getLabels();
311 for (size_t i = 0; i != labels.size(); ++i) {
314 InsetLabel * lab = labels[i];
315 docstring const oldname = lab->getParam("name");
316 lab->updateLabel(oldname, in_active_inset);
317 // We need to update the buffer reference cache.
319 docstring const newname = lab->getParam("name");
320 if (oldname == newname)
322 // adapt the references
323 for (InsetIterator itt = inset_iterator_begin(in);
324 itt != i_end; ++itt) {
325 if (itt->lyxCode() == REF_CODE) {
326 InsetCommand * ref = itt->asInsetCommand();
327 if (ref->getParam("reference") == oldname)
328 ref->setParam("reference", newname);
329 } else if (itt->lyxCode() == MATH_REF_CODE) {
330 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
331 // this is necessary to prevent an uninitialized
332 // buffer when the RefInset is in a MathBox.
333 // FIXME audit setBuffer calls
334 mi->setBuffer(const_cast<Buffer &>(buffer));
335 if (mi->getTarget() == oldname)
336 mi->changeTarget(newname);
344 // check for duplicates
345 InsetLabel & lab = static_cast<InsetLabel &>(*it);
346 docstring const oldname = lab.getParam("name");
347 lab.updateLabel(oldname, in_active_inset);
348 // We need to update the buffer reference cache.
350 docstring const newname = lab.getParam("name");
351 if (oldname == newname)
353 // adapt the references
354 for (InsetIterator itt = inset_iterator_begin(in); itt != i_end; ++itt) {
355 if (itt->lyxCode() == REF_CODE) {
356 InsetCommand & ref = static_cast<InsetCommand &>(*itt);
357 if (ref.getParam("reference") == oldname)
358 ref.setParam("reference", newname);
359 } else if (itt->lyxCode() == MATH_REF_CODE) {
360 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
361 // this is necessary to prevent an uninitialized
362 // buffer when the RefInset is in a MathBox.
363 // FIXME audit setBuffer calls
364 mi->setBuffer(const_cast<Buffer &>(buffer));
365 if (mi->getTarget() == oldname)
366 mi->changeTarget(newname);
373 InsetInclude & inc = static_cast<InsetInclude &>(*it);
375 // We need to update the list of included files.
381 InsetCitation & cit = static_cast<InsetCitation &>(*it);
382 // This actually only needs to be done if the cite engine
383 // differs, but we do it in general.
385 // We need to update the list of citations.
391 // check for duplicates
392 InsetBibitem & bib = static_cast<InsetBibitem &>(*it);
393 docstring const oldkey = bib.getParam("key");
394 bib.updateCommand(oldkey, false);
395 // We need to update the buffer reference cache.
397 docstring const newkey = bib.getParam("key");
398 if (oldkey == newkey)
400 // adapt the references
401 for (InsetIterator itt = inset_iterator_begin(in);
402 itt != i_end; ++itt) {
403 if (itt->lyxCode() == CITE_CODE) {
404 InsetCommand * ref = itt->asInsetCommand();
405 if (ref->getParam("key") == oldkey)
406 ref->setParam("key", newkey);
413 // check if branch is known to target buffer
415 InsetBranch & br = static_cast<InsetBranch &>(*it);
416 docstring const name = br.branch();
419 bool const is_child = (&buffer != buffer.masterBuffer());
420 BranchList branchlist = buffer.params().branchlist();
421 if ((!is_child && branchlist.find(name))
422 || (is_child && (branchlist.find(name)
423 || buffer.masterBuffer()->params().branchlist().find(name))))
425 switch(branchAction) {
426 case cap::BRANCH_ADD: {
427 // This is for a temporary buffer, so simply create the branch.
428 // Must not use lyx::dispatch(), since tmpbuffer has no view.
430 const_cast<Buffer&>(buffer).dispatch(FuncRequest(LFUN_BRANCH_ADD, name), dr);
433 case cap::BRANCH_ASK: {
434 docstring text = bformat(
435 _("The pasted branch \"%1$s\" is undefined.\n"
436 "Do you want to add it to the document's branch list?"),
438 if (frontend::Alert::prompt(_("Unknown branch"),
439 text, 0, 1, _("&Add"), _("&Don't Add")) != 0)
441 lyx::dispatch(FuncRequest(LFUN_BRANCH_ADD, name));
444 case cap::BRANCH_IGNORE:
447 // We need to update the list of branches.
456 insertion.swap(in.paragraphs());
458 // Split the paragraph for inserting the buf if necessary.
460 breakParagraphConservative(buffer.params(), pars, pit, pos);
464 pars.insert(pars.iterator_at(pit),
465 insertion.begin(), insertion.end());
467 // merge the empty par with the last par of the insertion
468 mergeParagraph(buffer.params(), pars,
469 pit + insertion.size() - 1);
471 pars.insert(pars.iterator_at(pit + 1),
472 insertion.begin(), insertion.end());
474 // merge the first par of the insertion with the current par
475 mergeParagraph(buffer.params(), pars, pit);
478 // Store the new cursor position.
479 pit_type last_paste = pit + insertion.size() - 1;
480 pit_type startpit = pit;
482 pos = pars[last_paste].size();
484 // FIXME Should we do it here, or should we let updateBuffer() do it?
485 // Set paragraph buffers. It's important to do this right away
486 // before something calls Inset::buffer() and causes a crash.
487 for (pit_type p = startpit; p <= pit; ++p)
488 pars[p].setInsetBuffers(const_cast<Buffer &>(buffer));
490 // Join (conditionally) last pasted paragraph with next one, i.e.,
491 // the tail of the spliced document paragraph
492 if (!empty && last_paste + 1 != pit_type(pars.size())) {
493 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
494 mergeParagraph(buffer.params(), pars, last_paste);
495 } else if (pars[last_paste + 1].empty()) {
496 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
497 mergeParagraph(buffer.params(), pars, last_paste);
498 } else if (pars[last_paste].empty()) {
499 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
500 mergeParagraph(buffer.params(), pars, last_paste);
502 pars[last_paste + 1].stripLeadingSpaces(buffer.params().track_changes);
507 return PasteReturnValue(pit, pos, need_update);
511 PitPosPair eraseSelectionHelper(BufferParams const & params,
512 ParagraphList & pars,
513 pit_type startpit, pit_type endpit,
514 int startpos, int endpos)
516 // Start of selection is really invalid.
517 if (startpit == pit_type(pars.size()) ||
518 (startpos > pars[startpit].size()))
519 return PitPosPair(endpit, endpos);
521 // Start and end is inside same paragraph
522 if (endpit == pit_type(pars.size()) || startpit == endpit) {
523 endpos -= pars[startpit].eraseChars(startpos, endpos, params.track_changes);
524 return PitPosPair(endpit, endpos);
527 for (pit_type pit = startpit; pit != endpit + 1;) {
528 pos_type const left = (pit == startpit ? startpos : 0);
529 pos_type right = (pit == endpit ? endpos : pars[pit].size() + 1);
530 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.track_changes);
532 // Logically erase only, including the end-of-paragraph character
533 pars[pit].eraseChars(left, right, params.track_changes);
535 // Separate handling of paragraph break:
536 if (merge && pit != endpit &&
538 || pars[pit].hasSameLayout(pars[endpit])
539 || pars[endpit].size() == endpos)) {
540 if (pit + 1 == endpit)
541 endpos += pars[pit].size();
542 mergeParagraph(params, pars, pit);
548 // Ensure legal cursor pos:
551 return PitPosPair(endpit, endpos);
555 Buffer * copyToTempBuffer(ParagraphList const & paragraphs, DocumentClassConstPtr docclass)
557 // This used to need to be static to avoid a memory leak. It no longer needs
558 // to be so, but the alternative is to construct a new one of these (with a
559 // new temporary directory, etc) every time, and then to destroy it. So maybe
560 // it's worth just keeping this one around.
561 static TempFile tempfile("clipboard.internal");
562 tempfile.setAutoRemove(false);
563 // The initialization of staticbuffer is thread-safe. Using a lambda
564 // guarantees that the properties are set only once.
565 static Buffer * staticbuffer = [&](){
567 theBufferList().newInternalBuffer(tempfile.name().absFileName());
569 b->inset().setBuffer(*b);
570 //initialize staticbuffer with b
573 // Use a clone for the complicated stuff so that we do not need to clean
574 // up in order to avoid a crash.
575 Buffer * buffer = staticbuffer->cloneBufferOnly();
576 LASSERT(buffer, return nullptr);
578 // This needs doing every time.
579 // Since setDocumentClass() causes deletion of the old document class
580 // we need to reset all layout pointers in paragraphs (otherwise they
581 // would be dangling).
582 ParIterator const end = buffer->par_iterator_end();
583 for (ParIterator it = buffer->par_iterator_begin(); it != end; ++it) {
584 docstring const name = it->layout().name();
585 if (docclass->hasLayout(name))
586 it->setLayout((*docclass)[name]);
588 it->setPlainOrDefaultLayout(*docclass);
590 buffer->params().setDocumentClass(docclass);
592 // we will use pasteSelectionHelper to copy the paragraphs into the
593 // temporary Buffer, since it does a lot of things to fix them up.
594 DocIterator dit = doc_iterator_begin(buffer, &buffer->inset());
596 pasteSelectionHelper(dit, paragraphs, docclass, cap::BRANCH_ADD, el);
602 void putClipboard(ParagraphList const & paragraphs,
603 DocumentClassConstPtr docclass, docstring const & plaintext,
604 BufferParams const & bp)
606 Buffer * buffer = copyToTempBuffer(paragraphs, docclass);
607 if (!buffer) // already asserted in copyToTempBuffer()
610 // We don't want to produce images that are not used. Therefore,
611 // output formulas as MathML. Even if this is not understood by all
612 // applications, the number that can parse it should go up in the future.
613 buffer->params().html_math_output = BufferParams::MathML;
615 if (lyxrc.ct_markup_copied) {
616 // Copy authors to the params. We need those pointers.
617 for (Author const & a : bp.authors())
618 buffer->params().authors().record(a);
621 // Make sure MarkAsExporting is deleted before buffer is
623 // The Buffer is being used to export. This is necessary so that the
624 // updateMacros call will record the needed information.
625 MarkAsExporting mex(buffer);
627 buffer->updateBuffer(Buffer::UpdateMaster, OutputUpdate);
628 buffer->updateMacros();
629 buffer->updateMacroInstances(OutputUpdate);
634 if (buffer->write(oslyx))
638 odocstringstream oshtml;
639 OutputParams runparams(encodings.fromLyXName("utf8"));
640 // We do not need to produce images, etc.
641 runparams.dryrun = true;
642 // We are not interested in errors (bug 8866)
643 runparams.silent = true;
644 buffer->writeLyXHTMLSource(oshtml, runparams, Buffer::FullSource);
646 theClipboard().put(lyx, oshtml.str(), plaintext);
654 /// return true if the whole ParagraphList is deleted
655 static bool isFullyDeleted(ParagraphList const & pars)
657 pit_type const pars_size = static_cast<pit_type>(pars.size());
659 // check all paragraphs
660 for (pit_type pit = 0; pit < pars_size; ++pit) {
661 if (!pars[pit].empty()) // prevent assertion failure
662 if (!pars[pit].isDeleted(0, pars[pit].size()))
669 void copySelectionHelper(Buffer const & buf, Text const & text,
670 pit_type startpit, pit_type endpit,
671 int start, int end, DocumentClassConstPtr dc, CutStack & cutstack)
673 ParagraphList const & pars = text.paragraphs();
675 // In most of these cases, we can try to recover.
676 LASSERT(0 <= start, start = 0);
677 LASSERT(start <= pars[startpit].size(), start = pars[startpit].size());
678 LASSERT(0 <= end, end = 0);
679 LASSERT(end <= pars[endpit].size(), end = pars[endpit].size());
680 LASSERT(startpit != endpit || start <= end, return);
682 // Clone the paragraphs within the selection.
683 ParagraphList copy_pars(pars.iterator_at(startpit),
684 pars.iterator_at(endpit + 1));
686 // Remove the end of the last paragraph; afterwards, remove the
687 // beginning of the first paragraph. Keep this order - there may only
688 // be one paragraph! Do not track deletions here; this is an internal
689 // action not visible to the user
691 Paragraph & back = copy_pars.back();
692 back.eraseChars(end, back.size(), false);
693 Paragraph & front = copy_pars.front();
694 front.eraseChars(0, start, false);
696 for (auto & par : copy_pars) {
697 // Since we have a copy of the paragraphs, the insets
698 // do not have a proper buffer reference. It makes
699 // sense to add them temporarily, because the
700 // operations below depend on that (acceptChanges included).
701 par.setInsetBuffers(const_cast<Buffer &>(buf));
702 // PassThru paragraphs have the Language
703 // latex_language. This is invalid for others, so we
704 // need to change it to the buffer language.
705 if (par.isPassThru())
706 par.changeLanguage(buf.params(),
707 latex_language, buf.language());
710 // do not copy text (also nested in insets) which is marked as
711 // deleted, unless the whole selection was deleted
712 if (!lyxrc.ct_markup_copied) {
713 if (!isFullyDeleted(copy_pars))
714 acceptChanges(copy_pars, buf.params());
716 rejectChanges(copy_pars, buf.params());
720 // do some final cleanup now, to make sure that the paragraphs
721 // are not linked to something else.
722 for (auto & par : copy_pars) {
724 par.setInsetOwner(nullptr);
727 cutstack.push(make_pair(copy_pars, dc));
735 void region(CursorSlice const & i1, CursorSlice const & i2,
736 Inset::row_type & r1, Inset::row_type & r2,
737 Inset::col_type & c1, Inset::col_type & c2)
739 Inset const & p = i1.inset();
740 c1 = p.col(i1.idx());
741 c2 = p.col(i2.idx());
744 r1 = p.row(i1.idx());
745 r2 = p.row(i2.idx());
751 docstring grabAndEraseSelection(Cursor & cur)
753 if (!cur.selection())
755 docstring res = grabSelection(cur);
761 bool reduceSelectionToOneCell(CursorData & cur)
763 if (!cur.selection() || !cur.inMathed())
766 CursorSlice i1 = cur.selBegin();
767 CursorSlice i2 = cur.selEnd();
768 if (!i1.inset().asInsetMath())
771 // the easy case: do nothing if only one cell is selected
772 if (i1.idx() == i2.idx())
777 cur.top().pos() = cur.top().lastpos();
783 bool multipleCellsSelected(CursorData const & cur)
785 if (!cur.selection() || !cur.inMathed())
788 CursorSlice i1 = cur.selBegin();
789 CursorSlice i2 = cur.selEnd();
790 if (!i1.inset().asInsetMath())
793 if (i1.idx() == i2.idx())
800 void switchBetweenClasses(DocumentClassConstPtr oldone,
801 DocumentClassConstPtr newone, InsetText & in, ErrorList & errorlist)
805 LBUFERR(!in.paragraphs().empty());
806 if (oldone == newone)
809 DocumentClass const & oldtc = *oldone;
810 DocumentClass const & newtc = *newone;
813 ParIterator it = par_iterator_begin(in);
814 ParIterator end = par_iterator_end(in);
815 // for remembering which layouts we've had to add
816 set<docstring> newlayouts;
817 for (; it != end; ++it) {
818 docstring const name = it->layout().name();
820 // the pasted text will keep their own layout name. If this layout does
821 // not exist in the new document, it will behave like a standard layout.
822 bool const added_one = newtc.addLayoutIfNeeded(name);
824 newlayouts.insert(name);
826 if (added_one || newlayouts.find(name) != newlayouts.end()) {
828 docstring const s = bformat(_("Layout `%1$s' was not found."), name);
829 errorlist.push_back(ErrorItem(_("Layout Not Found"), s,
830 {it->id(), 0}, {it->id(), -1}));
833 if (in.usePlainLayout())
834 it->setLayout(newtc.plainLayout());
836 it->setLayout(newtc[name]);
839 // character styles and hidden table cells
840 InsetIterator const i_end = inset_iterator_end(in);
841 for (InsetIterator iit = inset_iterator_begin(in); iit != i_end; ++iit) {
842 InsetCode const code = iit->lyxCode();
843 if (code == FLEX_CODE) {
844 // FIXME: Should we verify all InsetCollapsible?
845 docstring const layoutName = iit->layoutName();
846 docstring const & n = newone->insetLayout(layoutName).name();
847 bool const is_undefined = n.empty() ||
848 n == DocumentClass::plainInsetLayout().name();
852 // The flex inset is undefined in newtc
853 docstring const oldname = from_utf8(oldtc.name());
854 docstring const newname = from_utf8(newtc.name());
856 if (oldname == newname)
857 s = bformat(_("Flex inset %1$s is undefined after "
858 "reloading `%2$s' layout."), layoutName, oldname);
860 s = bformat(_("Flex inset %1$s is undefined because of "
861 "conversion from `%2$s' layout to `%3$s'."),
862 layoutName, oldname, newname);
863 // To warn the user that something had to be done.
864 errorlist.push_back(ErrorItem(
865 _("Undefined flex inset"), s,
866 {iit.paragraph().id(), iit.pos()},
867 {iit.paragraph().id(), iit.pos() + 1}));
868 } else if (code == TABULAR_CODE) {
869 // The recursion above does not catch paragraphs in "hidden" cells,
870 // i.e., ones that are part of a multirow or multicolum. So we need
871 // to handle those separately.
872 // This is the cause of bug #9049.
873 InsetTabular * table = iit->asInsetTabular();
874 table->setLayoutForHiddenCells(newtc);
880 vector<docstring> availableSelections(Buffer const * buf)
882 vector<docstring> selList;
886 for (auto const & cut : theCuts) {
887 ParagraphList const & pars = cut.first;
889 for (auto const & para : pars) {
890 Paragraph par(para, 0, 46);
891 // adapt paragraph to current buffer.
892 par.setInsetBuffers(const_cast<Buffer &>(*buf));
893 textSel += par.asString(AS_STR_INSETS);
894 if (textSel.size() > 45) {
895 support::truncateWithEllipsis(textSel,45);
899 selList.push_back(textSel);
906 size_type numberOfSelections()
908 return theCuts.size();
913 void cutSelectionHelper(Cursor & cur, CutStack & cuts, bool realcut, bool putclip)
915 // This doesn't make sense, if there is no selection
916 if (!cur.selection())
919 // OK, we have a selection. This is always between cur.selBegin()
922 if (cur.inTexted()) {
923 Text * text = cur.text();
928 // make sure that the depth behind the selection are restored, too
929 cur.recordUndoSelection();
930 pit_type begpit = cur.selBegin().pit();
931 pit_type endpit = cur.selEnd().pit();
933 int endpos = cur.selEnd().pos();
935 BufferParams const & bp = cur.buffer()->params();
937 copySelectionHelper(*cur.buffer(),
940 cur.selBegin().pos(), endpos,
941 bp.documentClassPtr(), cuts);
942 // Stuff what we got on the clipboard.
943 // Even if there is no selection.
945 putClipboard(cuts[0].first, cuts[0].second,
946 cur.selectionAsString(true, true), bp);
949 if (begpit != endpit)
950 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
952 tie(endpit, endpos) =
953 eraseSelectionHelper(bp, text->paragraphs(), begpit, endpit,
954 cur.selBegin().pos(), endpos);
956 // cutSelection can invalidate the cursor so we need to set
958 // we prefer the end for when tracking changes
962 // need a valid cursor. (Lgb)
963 cur.clearSelection();
965 // After a cut operation, we must make sure that the Buffer is updated
966 // because some further operation might need updated label information for
967 // example. So we cannot just use "cur.forceBufferUpdate()" here.
969 cur.buffer()->updateBuffer();
971 // tell tabular that a recent copy happened
972 dirtyTabularStack(false);
975 if (cur.inMathed()) {
976 if (cur.selBegin().idx() != cur.selEnd().idx()) {
977 // The current selection spans more than one cell.
979 cur.recordUndoInset();
981 // Record only the current cell to avoid a jumping
993 void cutSelection(Cursor & cur, bool realcut)
995 cutSelectionHelper(cur, theCuts, realcut, true);
999 void cutSelectionToTemp(Cursor & cur, bool realcut)
1001 cutSelectionHelper(cur, tempCut, realcut, false);
1005 void copySelection(Cursor const & cur)
1007 copySelection(cur, cur.selectionAsString(true, true));
1011 void copyInset(Cursor const & cur, Inset * inset, docstring const & plaintext)
1015 BufferParams const & bp = cur.buffer()->params();
1016 par.setLayout(bp.documentClass().plainLayout());
1017 Font font(inherit_font, bp.language);
1018 par.insertInset(0, inset, font, Change(Change::UNCHANGED));
1019 pars.push_back(par);
1020 theCuts.push(make_pair(pars, bp.documentClassPtr()));
1022 // stuff the selection onto the X clipboard, from an explicit copy request
1023 putClipboard(theCuts[0].first, theCuts[0].second, plaintext, bp);
1029 void copySelectionToStack(CursorData const & cur, CutStack & cutstack)
1031 // this doesn't make sense, if there is no selection
1032 if (!cur.selection())
1035 // copySelection can not yet handle the case of cross idx selection
1036 if (cur.selBegin().idx() != cur.selEnd().idx())
1039 if (cur.inTexted()) {
1040 Text * text = cur.text();
1042 // ok we have a selection. This is always between cur.selBegin()
1043 // and sel_end cursor
1044 copySelectionHelper(*cur.buffer(), *text,
1045 cur.selBegin().pit(), cur.selEnd().pit(),
1046 cur.selBegin().pos(), cur.selEnd().pos(),
1047 cur.buffer()->params().documentClassPtr(),
1049 // Reset the dirty_tabular_stack_ flag only when something
1050 // is copied to the clipboard (not to the selectionBuffer).
1051 if (&cutstack == &theCuts)
1052 dirtyTabularStack(false);
1055 if (cur.inMathed()) {
1056 //lyxerr << "copySelection in mathed" << endl;
1059 BufferParams const & bp = cur.buffer()->params();
1060 // FIXME This should be the plain layout...right?
1061 par.setLayout(bp.documentClass().plainLayout());
1062 // For pasting into text, we set the language to the paragraph language
1063 // (rather than the default_language which is always English; see #2596)
1064 par.insert(0, grabSelection(cur), Font(sane_font, par.getParLanguage(bp)),
1065 Change(Change::UNCHANGED));
1066 pars.push_back(par);
1067 cutstack.push(make_pair(pars, bp.documentClassPtr()));
1074 void copySelectionToStack()
1076 if (!selectionBuffer.empty())
1077 theCuts.push(selectionBuffer[0]);
1081 void copySelectionToTemp(Cursor const & cur)
1083 copySelectionToStack(cur, tempCut);
1087 void copySelection(Cursor const & cur, docstring const & plaintext)
1089 // In tablemode, because copy and paste actually use a special table stack,
1090 // we need to go through the cells and collect the paragraphs.
1091 // In math matrices, we generate a plain text version.
1092 if (cur.selBegin().idx() != cur.selEnd().idx()) {
1094 BufferParams const & bp = cur.buffer()->params();
1095 if (cur.inMathed()) {
1097 par.setLayout(bp.documentClass().plainLayout());
1098 // Replace (column-separating) tabs by space (#4449)
1099 docstring const clean_text = subst(plaintext, '\t', ' ');
1100 // For pasting into text, we set the language to the paragraph language
1101 // (rather than the default_language which is always English; see #11898)
1102 par.insert(0, clean_text, Font(sane_font, par.getParLanguage(bp)),
1103 Change(Change::UNCHANGED));
1104 pars.push_back(par);
1106 // Get paragraphs from all cells
1107 InsetTabular * table = cur.inset().asInsetTabular();
1108 LASSERT(table, return);
1109 ParagraphList tplist = table->asParList(cur.selBegin().idx(), cur.selEnd().idx());
1110 for (auto & cpar : tplist) {
1111 cpar.setLayout(bp.documentClass().plainLayout());
1112 pars.push_back(cpar);
1113 // since the pars are merged later, we separate them by blank
1115 epar.insert(0, from_ascii(" "), Font(sane_font, epar.getParLanguage(bp)),
1116 Change(Change::UNCHANGED));
1117 pars.push_back(epar);
1119 // remove last empty par
1121 // merge all paragraphs to one
1122 while (pars.size() > 1)
1123 mergeParagraph(bp, pars, 0);
1125 theCuts.push(make_pair(pars, bp.documentClassPtr()));
1127 copySelectionToStack(cur, theCuts);
1130 // stuff the selection onto the X clipboard, from an explicit copy request
1131 putClipboard(theCuts[0].first, theCuts[0].second, plaintext,
1132 cur.buffer()->params());
1136 void saveSelection(Cursor const & cur)
1138 // This function is called, not when a selection is formed, but when
1139 // a selection is cleared. Therefore, multiple keyboard selection
1140 // will not repeatively trigger this function (bug 3877).
1142 && cur.selBegin() == cur.bv().cursor().selBegin()
1143 && cur.selEnd() == cur.bv().cursor().selEnd()) {
1144 LYXERR(Debug::SELECTION, "saveSelection: '" << cur.selectionAsString(true, true) << "'");
1145 copySelectionToStack(cur, selectionBuffer);
1152 return !selectionBuffer.empty();
1156 void clearSelection()
1158 selectionBuffer.clear();
1162 void clearCutStack()
1169 docstring selection(size_t sel_index, DocumentClassConstPtr docclass)
1171 if (sel_index >= theCuts.size())
1174 unique_ptr<Buffer> buffer(copyToTempBuffer(theCuts[sel_index].first,
1179 return buffer->paragraphs().back().asString(AS_STR_INSETS | AS_STR_NEWLINES);
1183 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
1184 DocumentClassConstPtr docclass, ErrorList & errorList,
1185 cap::BranchAction branchAction)
1187 if (cur.inTexted()) {
1188 Text * text = cur.text();
1191 PasteReturnValue prv =
1192 pasteSelectionHelper(cur, parlist, docclass, branchAction, errorList);
1193 cur.forceBufferUpdate();
1194 cur.clearSelection();
1195 text->setCursor(cur, prv.pit, prv.pos);
1198 // mathed is handled in InsetMathNest/InsetMathGrid
1199 LATTEST(!cur.inMathed());
1203 bool pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
1205 // this does not make sense, if there is nothing to paste
1206 if (!checkPastePossible(sel_index))
1210 pasteParagraphList(cur, theCuts[sel_index].first,
1211 theCuts[sel_index].second, errorList, BRANCH_ASK);
1216 bool pasteFromTemp(Cursor & cur, ErrorList & errorList)
1218 // this does not make sense, if there is nothing to paste
1219 if (tempCut.empty() || tempCut[0].first.empty())
1223 pasteParagraphList(cur, tempCut[0].first,
1224 tempCut[0].second, errorList, BRANCH_IGNORE);
1229 bool pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs,
1230 Clipboard::TextType type)
1232 // Use internal clipboard if it is the most recent one
1233 // This overrides asParagraphs and type on purpose!
1234 if (theClipboard().isInternal())
1235 return pasteFromStack(cur, errorList, 0);
1237 // First try LyX format
1238 if ((type == Clipboard::LyXTextType ||
1239 type == Clipboard::LyXOrPlainTextType ||
1240 type == Clipboard::AnyTextType) &&
1241 theClipboard().hasTextContents(Clipboard::LyXTextType)) {
1242 string lyx = theClipboard().getAsLyX();
1244 Buffer buffer(string(), false);
1245 buffer.setUnnamed(true);
1246 if (buffer.readString(lyx)) {
1248 pasteParagraphList(cur, buffer.paragraphs(),
1249 buffer.params().documentClassPtr(), errorList);
1255 // Then try TeX and HTML
1256 Clipboard::TextType types[2] = {Clipboard::HtmlTextType, Clipboard::LaTeXTextType};
1257 string names[2] = {"html", "latexclipboard"};
1258 for (int i = 0; i < 2; ++i) {
1259 if (type != types[i] && type != Clipboard::AnyTextType)
1261 bool available = theClipboard().hasTextContents(types[i]);
1263 // If a specific type was explicitly requested, try to
1264 // interpret plain text: The user told us that the clipboard
1265 // contents is in the desired format
1266 if (!available && type == types[i]) {
1267 types[i] = Clipboard::PlainTextType;
1268 available = theClipboard().hasTextContents(types[i]);
1272 docstring text = theClipboard().getAsText(types[i]);
1273 available = !text.empty();
1275 Buffer buffer(string(), false);
1276 buffer.setUnnamed(true);
1277 available = buffer.importString(names[i], text, errorList);
1279 available = !buffer.paragraphs().empty();
1280 if (available && !buffer.paragraphs()[0].empty()) {
1281 // TeX2lyx (also used in the HTML chain) assumes English as document language
1282 // if no language is explicitly set (as is the case here).
1283 // We thus reset the temp buffer's language to the context language
1284 buffer.changeLanguage(buffer.language(), cur.getFont().language());
1286 pasteParagraphList(cur, buffer.paragraphs(),
1287 buffer.params().documentClassPtr(), errorList);
1294 // Then try plain text
1295 docstring const text = theClipboard().getAsText(Clipboard::PlainTextType);
1300 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1302 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1303 cur.forceBufferUpdate();
1308 void pasteSimpleText(Cursor & cur, bool asParagraphs)
1311 // Use internal clipboard if it is the most recent one
1312 if (theClipboard().isInternal()) {
1313 if (!checkPastePossible(0))
1316 ParagraphList const & pars = theCuts[0].first;
1317 ParagraphList::const_iterator it = pars.begin();
1318 for (; it != pars.end(); ++it) {
1319 if (it != pars.begin())
1321 text += (*it).asString();
1323 asParagraphs = false;
1325 // Then try plain text
1326 text = theClipboard().getAsText(Clipboard::PlainTextType);
1333 cutSelection(cur, false);
1335 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1337 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1341 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
1342 Clipboard::GraphicsType preferedType)
1344 LASSERT(theClipboard().hasGraphicsContents(preferedType), return);
1346 // get picture from clipboard
1347 FileName filename = theClipboard().getAsGraphics(cur, preferedType);
1348 if (filename.empty())
1351 // create inset for graphic
1352 InsetGraphics * inset = new InsetGraphics(cur.buffer());
1353 InsetGraphicsParams params;
1354 params.filename = support::DocFileName(filename.absFileName(), false);
1355 inset->setParams(params);
1361 void pasteSelection(Cursor & cur, ErrorList & errorList)
1363 if (selectionBuffer.empty())
1366 pasteParagraphList(cur, selectionBuffer[0].first,
1367 selectionBuffer[0].second, errorList);
1371 void replaceSelectionWithString(Cursor & cur, docstring const & str)
1374 DocIterator selbeg = cur.selectionBegin();
1376 // Get font setting before we cut, we need a copy here, not a bare reference.
1378 selbeg.paragraph().getFontSettings(cur.buffer()->params(), selbeg.pos());
1380 // Insert the new string
1381 pos_type pos = cur.selEnd().pos();
1382 Paragraph & par = cur.selEnd().paragraph();
1383 for (auto const & c : str) {
1384 par.insertChar(pos, c, font, cur.buffer()->params().track_changes);
1388 // Cut the selection
1389 cutSelection(cur, false);
1393 void replaceSelection(Cursor & cur)
1395 if (cur.selection())
1396 cutSelection(cur, false);
1400 void eraseSelection(Cursor & cur)
1402 //lyxerr << "cap::eraseSelection begin: " << cur << endl;
1403 CursorSlice const & i1 = cur.selBegin();
1404 CursorSlice const & i2 = cur.selEnd();
1405 if (!i1.asInsetMath()) {
1406 LYXERR0("Can't erase this selection");
1412 InsetMath * p = i1.asInsetMath();
1413 if (i1.idx() == i2.idx()) {
1414 i1.cell().erase(i1.pos(), i2.pos());
1415 // We may have deleted i1.cell(cur.pos()).
1416 // Make sure that pos is valid.
1417 if (cur.pos() > cur.lastpos())
1418 cur.pos() = cur.lastpos();
1419 } else if (p->nrows() > 0 && p->ncols() > 0) {
1420 // This is a grid, delete a nice square region
1421 Inset::row_type r1, r2;
1422 Inset::col_type c1, c2;
1423 region(i1, i2, r1, r2, c1, c2);
1424 for (Inset::row_type row = r1; row <= r2; ++row)
1425 for (Inset::col_type col = c1; col <= c2; ++col)
1426 p->cell(p->index(row, col)).clear();
1427 // We've deleted the whole cell. Only pos 0 is valid.
1430 Inset::idx_type idx1 = i1.idx();
1431 Inset::idx_type idx2 = i2.idx();
1434 for (Inset::idx_type idx = idx1 ; idx <= idx2; ++idx)
1435 p->cell(idx).clear();
1436 // We've deleted the whole cell. Only pos 0 is valid.
1440 // need a valid cursor. (Lgb)
1441 cur.clearSelection();
1442 //lyxerr << "cap::eraseSelection end: " << cur << endl;
1446 void selDel(Cursor & cur)
1448 //lyxerr << "cap::selDel" << endl;
1449 if (cur.selection())
1450 eraseSelection(cur);
1454 void selClearOrDel(Cursor & cur)
1456 //lyxerr << "cap::selClearOrDel" << endl;
1457 if (lyxrc.auto_region_delete)
1460 cur.selection(false);
1464 docstring grabSelection(CursorData const & cur)
1466 if (!cur.selection())
1470 // grab selection by glueing multiple cells together. This is not what
1471 // we want because selections spanning multiple cells will get "&" and "\\"
1474 for (DocIterator dit = cur.selectionBegin();
1475 dit != cur.selectionEnd(); dit.forwardPos())
1476 os << asString(dit.cell());
1480 CursorSlice i1 = cur.selBegin();
1481 CursorSlice i2 = cur.selEnd();
1483 if (i1.idx() == i2.idx()) {
1484 if (i1.inset().asInsetMath()) {
1485 MathData::const_iterator it = i1.cell().begin();
1486 Buffer * buf = cur.buffer();
1487 return asString(MathData(buf, it + i1.pos(), it + i2.pos()));
1489 return from_ascii("unknown selection 1");
1493 Inset::row_type r1, r2;
1494 Inset::col_type c1, c2;
1495 region(i1, i2, r1, r2, c1, c2);
1498 if (i1.inset().asInsetMath()) {
1499 for (Inset::row_type row = r1; row <= r2; ++row) {
1502 for (Inset::col_type col = c1; col <= c2; ++col) {
1505 data += asString(i1.asInsetMath()->
1506 cell(i1.asInsetMath()->index(row, col)));
1510 data = from_ascii("unknown selection 2");
1516 void dirtyTabularStack(bool b)
1518 dirty_tabular_stack_ = b;
1522 bool tabularStackDirty()
1524 return dirty_tabular_stack_;