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 "BufferList.h"
22 #include "BufferParams.h"
23 #include "BufferView.h"
27 #include "ErrorList.h"
29 #include "FuncRequest.h"
30 #include "InsetIterator.h"
35 #include "Paragraph.h"
36 #include "ParagraphParameters.h"
37 #include "ParIterator.h"
38 #include "TextClass.h"
40 #include "insets/InsetBibitem.h"
41 #include "insets/InsetBranch.h"
42 #include "insets/InsetCitation.h"
43 #include "insets/InsetCommand.h"
44 #include "insets/InsetGraphics.h"
45 #include "insets/InsetGraphicsParams.h"
46 #include "insets/InsetInclude.h"
47 #include "insets/InsetLabel.h"
48 #include "insets/InsetTabular.h"
50 #include "mathed/MathData.h"
51 #include "mathed/InsetMath.h"
52 #include "mathed/InsetMathHull.h"
53 #include "mathed/InsetMathRef.h"
54 #include "mathed/MathSupport.h"
56 #include "support/debug.h"
57 #include "support/docstream.h"
58 #include "support/gettext.h"
59 #include "support/lassert.h"
60 #include "support/limited_stack.h"
61 #include "support/lstrings.h"
62 #include "support/TempFile.h"
63 #include "support/unique_ptr.h"
65 #include "frontends/alert.h"
66 #include "frontends/Clipboard.h"
72 using namespace lyx::support;
73 using lyx::frontend::Clipboard;
79 typedef pair<pit_type, int> PitPosPair;
81 typedef limited_stack<pair<ParagraphList, DocumentClassConstPtr> > CutStack;
84 // persistent selection, cleared until the next selection
85 CutStack selectionBuffer(1);
86 // temporary scratch area
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_pit, pos_type r_pos, bool r_nu) :
103 pit(r_pit), pos(r_pos), needupdate(r_nu)
112 pasteSelectionHelper(DocIterator const & cur, ParagraphList const & parlist,
113 DocumentClassConstPtr oldDocClass, cap::BranchAction branchAction,
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;
122 return PasteReturnValue(pit, pos, need_update);
124 // Check whether we paste into an inset that does not
125 // produce output (needed for label duplicate check)
126 bool in_active_inset = cur.paragraph().inInset().producesOutput();
127 if (in_active_inset) {
128 for (size_type sl = 0 ; sl < cur.depth() ; ++sl) {
129 Paragraph const & outer_par = cur[sl].paragraph();
130 if (!outer_par.inInset().producesOutput()) {
131 in_active_inset = false;
137 InsetText * target_inset = cur.inset().asInsetText();
139 InsetTabular * it = cur.inset().asInsetTabular();
140 target_inset = it ? it->cell(cur.idx())->asInsetText() : nullptr;
142 LASSERT(target_inset, return PasteReturnValue(pit, pos, need_update));
144 ParagraphList & pars = target_inset->paragraphs();
145 LASSERT(pos <= pars[pit].size(),
146 return PasteReturnValue(pit, pos, need_update));
148 // Make a copy of the CaP paragraphs.
149 ParagraphList insertion = parlist;
151 // Now remove all out of the pars which is NOT allowed in the
152 // new environment and set also another font if that is required.
154 // Merge paragraphs that are to be pasted into a text inset
155 // that does not allow multiple pars.
156 InsetText * inset_text = target_inset->asInsetText();
157 if (inset_text && !inset_text->allowMultiPar()) {
158 while (insertion.size() > 1)
159 mergeParagraph(buffer.params(), insertion, 0);
162 // Convert newline to paragraph break in ParbreakIsNewline
163 if (target_inset->getLayout().parbreakIsNewline()
164 || pars[pit].layout().parbreak_is_newline) {
165 for (size_t i = 0; i != insertion.size(); ++i) {
166 for (pos_type j = 0; j != insertion[i].size(); ++j) {
167 if (insertion[i].isNewline(j)) {
168 // do not track deletion of newline
169 insertion[i].eraseChar(j, false);
170 insertion[i].setInsetOwner(target_inset);
171 breakParagraphConservative(
180 // Prevent to paste uncodable characters in verbatim and ERT.
181 // The encoding is inherited from the context here.
182 docstring uncodable_content;
183 if (target_inset->getLayout().isPassThru() && cur.getEncoding()) {
184 odocstringstream res;
185 Encoding const * e = cur.getEncoding();
186 for (size_t i = 0; i != insertion.size(); ++i) {
187 pos_type end = insertion[i].size();
188 for (pos_type j = 0; j != end; ++j) {
190 if (insertion[i].isInset(j))
192 char_type const c = insertion[i].getChar(j);
193 if (!e->encodable(c)) {
194 // do not track deletion
196 insertion[i].eraseChar(j, false);
202 docstring const uncodable = res.str();
203 if (!uncodable.empty()) {
204 if (uncodable.size() == 1)
205 uncodable_content = bformat(_("The character \"%1$s\" is uncodable in this verbatim context "
206 "and thus has not been pasted."),
209 uncodable_content = bformat(_("The characters \"%1$s\" are uncodable in this verbatim context "
210 "and thus have not been pasted."),
215 // set the paragraphs to plain layout if necessary
216 DocumentClassConstPtr newDocClass = buffer.params().documentClassPtr();
217 Layout const & plainLayout = newDocClass->plainLayout();
218 Layout const & defaultLayout = newDocClass->defaultLayout();
219 if (cur.inset().usePlainLayout()) {
220 bool forcePlainLayout = target_inset->forcePlainLayout();
221 for (auto & par : insertion) {
222 Layout const & parLayout = par.layout();
223 if (forcePlainLayout || parLayout == defaultLayout)
224 par.setLayout(plainLayout);
227 // check if we need to reset from plain layout
228 for (auto & par : insertion) {
229 Layout const & parLayout = par.layout();
230 if (parLayout == plainLayout)
231 par.setLayout(defaultLayout);
235 InsetText in(cur.buffer());
236 // Make sure there is no class difference.
237 in.paragraphs().clear();
238 // This works without copying any paragraph data because we have
239 // a specialized swap method for ParagraphList. This is important
240 // since we store pointers to insets at some places and we don't
241 // want to invalidate them.
242 insertion.swap(in.paragraphs());
243 cap::switchBetweenClasses(oldDocClass, newDocClass, in, errorlist);
244 // Do this here since switchBetweenClasses clears the errorlist
245 if (!uncodable_content.empty())
246 errorlist.push_back(ErrorItem(_("Uncodable content"), uncodable_content));
247 insertion.swap(in.paragraphs());
249 ParagraphList::iterator tmpbuf = insertion.begin();
250 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
252 depth_type max_depth = pars[pit].getMaxDepthAfter();
254 for (; tmpbuf != insertion.end(); ++tmpbuf) {
255 // If we have a negative jump so that the depth would
256 // go below 0 depth then we have to redo the delta to
257 // this new max depth level so that subsequent
258 // paragraphs are aligned correctly to this paragraph
260 if (int(tmpbuf->params().depth()) + depth_delta < 0)
263 // Set the right depth so that we are not too deep or shallow.
264 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
265 if (tmpbuf->params().depth() > max_depth)
266 tmpbuf->params().depth(max_depth);
268 // Set max_depth for the next paragraph
269 max_depth = tmpbuf->getMaxDepthAfter();
271 // Set the inset owner of this paragraph.
272 tmpbuf->setInsetOwner(target_inset);
273 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
274 // do not track deletion of invalid insets
275 if (Inset * inset = tmpbuf->getInset(i))
276 if (!target_inset->insetAllowed(inset->lyxCode()))
277 tmpbuf->eraseChar(i--, false);
280 if (lyxrc.ct_markup_copied)
281 tmpbuf->setChange(Change(buffer.params().track_changes ?
282 Change::INSERTED : Change::UNCHANGED));
285 bool const empty = pars[pit].empty();
287 // Make the buf exactly the same layout as the cursor
289 insertion.begin()->makeSameLayout(pars[pit]);
292 // Prepare the paragraphs and insets for insertion.
293 insertion.swap(in.paragraphs());
295 InsetIterator const i_end = end(in);
296 for (InsetIterator it = begin(in); it != i_end; ++it) {
297 // Even though this will also be done later, it has to be done here
298 // since some inset might try to access the buffer() member.
299 it->setBuffer(const_cast<Buffer &>(buffer));
300 switch (it->lyxCode()) {
302 case MATH_HULL_CODE: {
303 // check for equation labels and resolve duplicates
304 InsetMathHull * ins = it->asInsetMath()->asHullInset();
305 std::vector<InsetLabel *> labels = ins->getLabels();
306 for (size_t i = 0; i != labels.size(); ++i) {
309 InsetLabel * lab = labels[i];
310 docstring const oldname = lab->getParam("name");
311 lab->updateLabel(oldname, in_active_inset);
312 // We need to update the buffer reference cache.
314 docstring const newname = lab->getParam("name");
315 if (oldname == newname)
317 // adapt the references
318 for (InsetIterator itt = begin(in);
319 itt != i_end; ++itt) {
320 if (itt->lyxCode() == REF_CODE) {
321 InsetCommand * ref = itt->asInsetCommand();
322 if (ref->getParam("reference") == oldname)
323 ref->setParam("reference", newname);
324 } else if (itt->lyxCode() == MATH_REF_CODE) {
325 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
326 // this is necessary to prevent an uninitialized
327 // buffer when the RefInset is in a MathBox.
328 // FIXME audit setBuffer calls
329 mi->setBuffer(const_cast<Buffer &>(buffer));
330 if (mi->getTarget() == oldname)
331 mi->changeTarget(newname);
339 // check for duplicates
340 InsetLabel & lab = static_cast<InsetLabel &>(*it);
341 docstring const oldname = lab.getParam("name");
342 lab.updateLabel(oldname, in_active_inset);
343 // We need to update the buffer reference cache.
345 docstring const newname = lab.getParam("name");
346 if (oldname == newname)
348 // adapt the references
349 for (InsetIterator itt = begin(in); itt != i_end; ++itt) {
350 if (itt->lyxCode() == REF_CODE) {
351 InsetCommand & ref = static_cast<InsetCommand &>(*itt);
352 if (ref.getParam("reference") == oldname)
353 ref.setParam("reference", newname);
354 } else if (itt->lyxCode() == MATH_REF_CODE) {
355 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
356 // this is necessary to prevent an uninitialized
357 // buffer when the RefInset is in a MathBox.
358 // FIXME audit setBuffer calls
359 mi->setBuffer(const_cast<Buffer &>(buffer));
360 if (mi->getTarget() == oldname)
361 mi->changeTarget(newname);
368 InsetInclude & inc = static_cast<InsetInclude &>(*it);
370 // We need to update the list of included files.
376 InsetCitation & cit = static_cast<InsetCitation &>(*it);
377 // This actually only needs to be done if the cite engine
378 // differs, but we do it in general.
380 // We need to update the list of citations.
386 // check for duplicates
387 InsetBibitem & bib = static_cast<InsetBibitem &>(*it);
388 docstring const oldkey = bib.getParam("key");
389 bib.updateCommand(oldkey, false);
390 // We need to update the buffer reference cache.
392 docstring const newkey = bib.getParam("key");
393 if (oldkey == newkey)
395 // adapt the references
396 for (InsetIterator itt = begin(in);
397 itt != i_end; ++itt) {
398 if (itt->lyxCode() == CITE_CODE) {
399 InsetCommand * ref = itt->asInsetCommand();
400 if (ref->getParam("key") == oldkey)
401 ref->setParam("key", newkey);
408 // check if branch is known to target buffer
410 InsetBranch & br = static_cast<InsetBranch &>(*it);
411 docstring const name = br.branch();
414 bool const is_child = (&buffer != buffer.masterBuffer());
415 BranchList branchlist = buffer.params().branchlist();
416 if ((!is_child && branchlist.find(name))
417 || (is_child && (branchlist.find(name)
418 || buffer.masterBuffer()->params().branchlist().find(name))))
420 switch(branchAction) {
421 case cap::BRANCH_ADD: {
422 // This is for a temporary buffer, so simply create the branch.
423 // Must not use lyx::dispatch(), since tmpbuffer has no view.
425 const_cast<Buffer&>(buffer).dispatch(FuncRequest(LFUN_BRANCH_ADD, name), dr);
428 case cap::BRANCH_ASK: {
429 docstring text = bformat(
430 _("The pasted branch \"%1$s\" is undefined.\n"
431 "Do you want to add it to the document's branch list?"),
433 if (frontend::Alert::prompt(_("Unknown branch"),
434 text, 0, 1, _("&Add"), _("&Don't Add")) != 0)
436 lyx::dispatch(FuncRequest(LFUN_BRANCH_ADD, name));
439 case cap::BRANCH_IGNORE:
442 // We need to update the list of branches.
451 insertion.swap(in.paragraphs());
453 // Split the paragraph for inserting the buf if necessary.
455 breakParagraphConservative(buffer.params(), pars, pit, pos);
459 pars.insert(pars.iterator_at(pit),
460 insertion.begin(), insertion.end());
462 // merge the empty par with the last par of the insertion
463 mergeParagraph(buffer.params(), pars,
464 pit + insertion.size() - 1);
466 pars.insert(pars.iterator_at(pit + 1),
467 insertion.begin(), insertion.end());
469 // merge the first par of the insertion with the current par
470 mergeParagraph(buffer.params(), pars, pit);
473 // Store the new cursor position.
474 pit_type last_paste = pit + insertion.size() - 1;
475 pit_type startpit = pit;
477 pos = pars[last_paste].size();
479 // FIXME Should we do it here, or should we let updateBuffer() do it?
480 // Set paragraph buffers. It's important to do this right away
481 // before something calls Inset::buffer() and causes a crash.
482 for (pit_type p = startpit; p <= pit; ++p)
483 pars[p].setInsetBuffers(const_cast<Buffer &>(buffer));
485 // Join (conditionally) last pasted paragraph with next one, i.e.,
486 // the tail of the spliced document paragraph
487 if (!empty && last_paste + 1 != pit_type(pars.size())) {
488 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
489 mergeParagraph(buffer.params(), pars, last_paste);
490 } else if (pars[last_paste + 1].empty()) {
491 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
492 mergeParagraph(buffer.params(), pars, last_paste);
493 } else if (pars[last_paste].empty()) {
494 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
495 mergeParagraph(buffer.params(), pars, last_paste);
497 pars[last_paste + 1].stripLeadingSpaces(buffer.params().track_changes);
502 return PasteReturnValue(pit, pos, need_update);
506 PitPosPair eraseSelectionHelper(BufferParams const & params,
507 ParagraphList & pars,
508 pit_type startpit, pit_type endpit,
509 int startpos, int endpos)
511 // Start of selection is really invalid.
512 if (startpit == pit_type(pars.size()) ||
513 (startpos > pars[startpit].size()))
514 return PitPosPair(endpit, endpos);
516 // Start and end is inside same paragraph
517 if (endpit == pit_type(pars.size()) || startpit == endpit) {
518 endpos -= pars[startpit].eraseChars(startpos, endpos, params.track_changes);
519 return PitPosPair(endpit, endpos);
522 for (pit_type pit = startpit; pit != endpit + 1;) {
523 pos_type const left = (pit == startpit ? startpos : 0);
524 pos_type right = (pit == endpit ? endpos : pars[pit].size() + 1);
525 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.track_changes);
527 // Logically erase only, including the end-of-paragraph character
528 pars[pit].eraseChars(left, right, params.track_changes);
530 // Separate handling of paragraph break:
531 if (merge && pit != endpit &&
533 || pars[pit].hasSameLayout(pars[endpit])
534 || pars[endpit].size() == endpos)) {
535 if (pit + 1 == endpit)
536 endpos += pars[pit].size();
537 mergeParagraph(params, pars, pit);
543 // Ensure legal cursor pos:
546 return PitPosPair(endpit, endpos);
550 Buffer * copyToTempBuffer(ParagraphList const & paragraphs, DocumentClassConstPtr docclass)
552 // This used to need to be static to avoid a memory leak. It no longer needs
553 // to be so, but the alternative is to construct a new one of these (with a
554 // new temporary directory, etc) every time, and then to destroy it. So maybe
555 // it's worth just keeping this one around.
556 static TempFile tempfile("clipboard.internal");
557 tempfile.setAutoRemove(false);
558 // The initialization of staticbuffer is thread-safe. Using a lambda
559 // guarantees that the properties are set only once.
560 static Buffer * staticbuffer = [&](){
562 theBufferList().newInternalBuffer(tempfile.name().absFileName());
564 b->inset().setBuffer(*b);
565 //initialize staticbuffer with b
568 // Use a clone for the complicated stuff so that we do not need to clean
569 // up in order to avoid a crash.
570 Buffer * buffer = staticbuffer->cloneBufferOnly();
571 LASSERT(buffer, return nullptr);
573 // This needs doing every time.
574 // Since setDocumentClass() causes deletion of the old document class
575 // we need to reset all layout pointers in paragraphs (otherwise they
576 // would be dangling).
577 ParIterator const end = buffer->par_iterator_end();
578 for (ParIterator it = buffer->par_iterator_begin(); it != end; ++it) {
579 docstring const name = it->layout().name();
580 if (docclass->hasLayout(name))
581 it->setLayout((*docclass)[name]);
583 it->setPlainOrDefaultLayout(*docclass);
585 buffer->params().setDocumentClass(docclass);
587 // we will use pasteSelectionHelper to copy the paragraphs into the
588 // temporary Buffer, since it does a lot of things to fix them up.
589 DocIterator dit = doc_iterator_begin(buffer, &buffer->inset());
591 pasteSelectionHelper(dit, paragraphs, docclass, cap::BRANCH_ADD, el);
597 void putClipboard(ParagraphList const & paragraphs,
598 DocumentClassConstPtr docclass, docstring const & plaintext,
599 BufferParams const & bp)
601 Buffer * buffer = copyToTempBuffer(paragraphs, docclass);
602 if (!buffer) // already asserted in copyToTempBuffer()
605 // We don't want to produce images that are not used. Therefore,
606 // output formulas as MathML. Even if this is not understood by all
607 // applications, the number that can parse it should go up in the future.
608 buffer->params().html_math_output = BufferParams::MathML;
610 if (lyxrc.ct_markup_copied) {
611 // Copy authors to the params. We need those pointers.
612 for (Author const & a : bp.authors())
613 buffer->params().authors().record(a);
616 // Make sure MarkAsExporting is deleted before buffer is
618 // The Buffer is being used to export. This is necessary so that the
619 // updateMacros call will record the needed information.
620 MarkAsExporting mex(buffer);
622 buffer->updateBuffer(Buffer::UpdateMaster, OutputUpdate);
623 buffer->updateMacros();
624 buffer->updateMacroInstances(OutputUpdate);
629 if (buffer->write(oslyx))
633 odocstringstream oshtml;
634 OutputParams runparams(encodings.fromLyXName("utf8"));
635 // We do not need to produce images, etc.
636 runparams.dryrun = true;
637 // We are not interested in errors (bug 8866)
638 runparams.silent = true;
639 buffer->writeLyXHTMLSource(oshtml, runparams, Buffer::FullSource);
641 theClipboard().put(lyx, oshtml.str(), plaintext);
649 /// return true if the whole ParagraphList is deleted
650 static bool isFullyDeleted(ParagraphList const & pars)
652 pit_type const pars_size = static_cast<pit_type>(pars.size());
654 // check all paragraphs
655 for (pit_type pit = 0; pit < pars_size; ++pit) {
656 if (!pars[pit].empty()) // prevent assertion failure
657 if (!pars[pit].isDeleted(0, pars[pit].size()))
664 void copySelectionHelper(Buffer const & buf, Text const & text,
665 pit_type startpit, pit_type endpit,
666 int start, int end, DocumentClassConstPtr dc, CutStack & cutstack)
668 ParagraphList const & pars = text.paragraphs();
670 // In most of these cases, we can try to recover.
671 LASSERT(0 <= start, start = 0);
672 LASSERT(start <= pars[startpit].size(), start = pars[startpit].size());
673 LASSERT(0 <= end, end = 0);
674 LASSERT(end <= pars[endpit].size(), end = pars[endpit].size());
675 LASSERT(startpit != endpit || start <= end, return);
677 // Clone the paragraphs within the selection.
678 ParagraphList copy_pars(pars.iterator_at(startpit),
679 pars.iterator_at(endpit + 1));
681 // Remove the end of the last paragraph; afterwards, remove the
682 // beginning of the first paragraph. Keep this order - there may only
683 // be one paragraph! Do not track deletions here; this is an internal
684 // action not visible to the user
686 Paragraph & back = copy_pars.back();
687 back.eraseChars(end, back.size(), false);
688 Paragraph & front = copy_pars.front();
689 front.eraseChars(0, start, false);
691 for (auto & par : copy_pars) {
692 // Since we have a copy of the paragraphs, the insets
693 // do not have a proper buffer reference. It makes
694 // sense to add them temporarily, because the
695 // operations below depend on that (acceptChanges included).
696 par.setInsetBuffers(const_cast<Buffer &>(buf));
697 // PassThru paragraphs have the Language
698 // latex_language. This is invalid for others, so we
699 // need to change it to the buffer language.
700 if (par.isPassThru())
701 par.changeLanguage(buf.params(),
702 latex_language, buf.language());
705 // do not copy text (also nested in insets) which is marked as
706 // deleted, unless the whole selection was deleted
707 if (!lyxrc.ct_markup_copied) {
708 if (!isFullyDeleted(copy_pars))
709 acceptChanges(copy_pars, buf.params());
711 rejectChanges(copy_pars, buf.params());
715 // do some final cleanup now, to make sure that the paragraphs
716 // are not linked to something else.
717 for (auto & par : copy_pars) {
719 par.setInsetOwner(nullptr);
722 cutstack.push(make_pair(copy_pars, dc));
730 void region(CursorSlice const & i1, CursorSlice const & i2,
731 row_type & r1, row_type & r2,
732 col_type & c1, col_type & c2)
734 Inset const & p = i1.inset();
735 c1 = p.col(i1.idx());
736 c2 = p.col(i2.idx());
739 r1 = p.row(i1.idx());
740 r2 = p.row(i2.idx());
746 docstring grabAndEraseSelection(Cursor & cur)
748 if (!cur.selection())
750 docstring res = grabSelection(cur);
756 bool reduceSelectionToOneCell(CursorData & cur)
758 if (!cur.selection() || !cur.inMathed())
761 CursorSlice i1 = cur.selBegin();
762 CursorSlice i2 = cur.selEnd();
763 if (!i1.inset().asInsetMath())
766 // the easy case: do nothing if only one cell is selected
767 if (i1.idx() == i2.idx())
772 cur.top().pos() = cur.top().lastpos();
778 bool multipleCellsSelected(CursorData const & cur)
780 if (!cur.selection() || !cur.inMathed())
783 CursorSlice i1 = cur.selBegin();
784 CursorSlice i2 = cur.selEnd();
785 if (!i1.inset().asInsetMath())
788 if (i1.idx() == i2.idx())
795 void switchBetweenClasses(DocumentClassConstPtr oldone,
796 DocumentClassConstPtr newone, InsetText & in, ErrorList & errorlist)
800 LBUFERR(!in.paragraphs().empty());
801 if (oldone == newone)
804 DocumentClass const & oldtc = *oldone;
805 DocumentClass const & newtc = *newone;
808 ParIterator it = par_iterator_begin(in);
809 ParIterator pend = par_iterator_end(in);
810 // for remembering which layouts we've had to add
811 set<docstring> newlayouts;
812 for (; it != pend; ++it) {
813 docstring const name = it->layout().name();
815 // the pasted text will keep their own layout name. If this layout does
816 // not exist in the new document, it will behave like a standard layout.
817 bool const added_one = newtc.addLayoutIfNeeded(name);
819 newlayouts.insert(name);
821 if (added_one || newlayouts.find(name) != newlayouts.end()) {
823 docstring const s = bformat(_("Layout `%1$s' was not found."), name);
824 errorlist.push_back(ErrorItem(_("Layout Not Found"), s,
825 {it->id(), 0}, {it->id(), -1}));
828 if (in.usePlainLayout())
829 it->setLayout(newtc.plainLayout());
831 it->setLayout(newtc[name]);
834 // character styles and hidden table cells
835 InsetIterator const i_end = end(in);
836 for (InsetIterator iit = begin(in); iit != i_end; ++iit) {
837 InsetCode const code = iit->lyxCode();
838 if (code == FLEX_CODE) {
839 // FIXME: Should we verify all InsetCollapsible?
840 docstring const layoutName = iit->layoutName();
841 docstring const & n = newone->insetLayout(layoutName).name();
842 bool const is_undefined = n.empty() ||
843 n == DocumentClass::plainInsetLayout().name();
847 // The flex inset is undefined in newtc
848 docstring const oldname = from_utf8(oldtc.name());
849 docstring const newname = from_utf8(newtc.name());
851 if (oldname == newname)
852 s = bformat(_("Flex inset %1$s is undefined after "
853 "reloading `%2$s' layout."), layoutName, oldname);
855 s = bformat(_("Flex inset %1$s is undefined because of "
856 "conversion from `%2$s' layout to `%3$s'."),
857 layoutName, oldname, newname);
858 // To warn the user that something had to be done.
859 errorlist.push_back(ErrorItem(
860 _("Undefined flex inset"), s,
861 {iit.paragraph().id(), iit.pos()},
862 {iit.paragraph().id(), iit.pos() + 1}));
863 } else if (code == TABULAR_CODE) {
864 // The recursion above does not catch paragraphs in "hidden" cells,
865 // i.e., ones that are part of a multirow or multicolum. So we need
866 // to handle those separately.
867 // This is the cause of bug #9049.
868 InsetTabular * table = iit->asInsetTabular();
869 table->setLayoutForHiddenCells(newtc);
875 vector<docstring> availableSelections(Buffer const * buf)
877 vector<docstring> selList;
881 for (auto const & cut : theCuts) {
882 ParagraphList const & pars = cut.first;
884 for (auto const & para : pars) {
885 Paragraph par(para, 0, 46);
886 // adapt paragraph to current buffer.
887 par.setInsetBuffers(const_cast<Buffer &>(*buf));
888 textSel += par.asString(AS_STR_INSETS);
889 if (textSel.size() > 45) {
890 support::truncateWithEllipsis(textSel,45);
894 selList.push_back(textSel);
901 size_type numberOfSelections()
903 return theCuts.size();
908 void cutSelectionHelper(Cursor & cur, CutStack & cuts, bool realcut, bool putclip)
910 // This doesn't make sense, if there is no selection
911 if (!cur.selection())
914 // OK, we have a selection. This is always between cur.selBegin()
917 if (cur.inTexted()) {
918 Text * text = cur.text();
923 // make sure that the depth behind the selection are restored, too
924 cur.recordUndoSelection();
925 pit_type begpit = cur.selBegin().pit();
926 pit_type endpit = cur.selEnd().pit();
928 int endpos = cur.selEnd().pos();
930 BufferParams const & bp = cur.buffer()->params();
932 copySelectionHelper(*cur.buffer(),
935 cur.selBegin().pos(), endpos,
936 bp.documentClassPtr(), cuts);
937 // Stuff what we got on the clipboard.
938 // Even if there is no selection.
940 putClipboard(cuts[0].first, cuts[0].second,
941 cur.selectionAsString(true, true), bp);
944 if (begpit != endpit)
945 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
947 tie(endpit, endpos) =
948 eraseSelectionHelper(bp, text->paragraphs(), begpit, endpit,
949 cur.selBegin().pos(), endpos);
951 // cutSelection can invalidate the cursor so we need to set
953 // we prefer the end for when tracking changes
957 // need a valid cursor. (Lgb)
958 cur.clearSelection();
960 // After a cut operation, we must make sure that the Buffer is updated
961 // because some further operation might need updated label information for
962 // example. So we cannot just use "cur.forceBufferUpdate()" here.
964 cur.buffer()->updateBuffer();
966 // tell tabular that a recent copy happened
967 dirtyTabularStack(false);
970 if (cur.inMathed()) {
971 if (cur.selBegin().idx() != cur.selEnd().idx()) {
972 // The current selection spans more than one cell.
974 cur.recordUndoInset();
976 // Record only the current cell to avoid a jumping
988 void cutSelection(Cursor & cur, bool realcut)
990 cutSelectionHelper(cur, theCuts, realcut, true);
994 void cutSelectionToTemp(Cursor & cur, bool realcut)
996 cutSelectionHelper(cur, tempCut, realcut, false);
1000 void copySelection(Cursor const & cur)
1002 copySelection(cur, cur.selectionAsString(true, true));
1006 void copyInset(Cursor const & cur, Inset * inset, docstring const & plaintext)
1010 BufferParams const & bp = cur.buffer()->params();
1011 par.setLayout(bp.documentClass().plainLayout());
1012 Font font(inherit_font, bp.language);
1013 par.insertInset(0, inset, font, Change(Change::UNCHANGED));
1014 pars.push_back(par);
1015 theCuts.push(make_pair(pars, bp.documentClassPtr()));
1017 // stuff the selection onto the X clipboard, from an explicit copy request
1018 putClipboard(theCuts[0].first, theCuts[0].second, plaintext, bp);
1024 void copySelectionToStack(CursorData const & cur, CutStack & cutstack)
1026 // this doesn't make sense, if there is no selection
1027 if (!cur.selection())
1030 // copySelection can not yet handle the case of cross idx selection
1031 if (cur.selBegin().idx() != cur.selEnd().idx())
1034 if (cur.inTexted()) {
1035 Text * text = cur.text();
1037 // ok we have a selection. This is always between cur.selBegin()
1038 // and sel_end cursor
1039 copySelectionHelper(*cur.buffer(), *text,
1040 cur.selBegin().pit(), cur.selEnd().pit(),
1041 cur.selBegin().pos(), cur.selEnd().pos(),
1042 cur.buffer()->params().documentClassPtr(),
1044 // Reset the dirty_tabular_stack_ flag only when something
1045 // is copied to the clipboard (not to the selectionBuffer).
1046 if (&cutstack == &theCuts)
1047 dirtyTabularStack(false);
1050 if (cur.inMathed()) {
1051 //lyxerr << "copySelection in mathed" << endl;
1054 BufferParams const & bp = cur.buffer()->params();
1055 // FIXME This should be the plain layout...right?
1056 par.setLayout(bp.documentClass().plainLayout());
1057 // For pasting into text, we set the language to the paragraph language
1058 // (rather than the default_language which is always English; see #2596)
1059 par.insert(0, grabSelection(cur), Font(sane_font, par.getParLanguage(bp)),
1060 Change(Change::UNCHANGED));
1061 pars.push_back(par);
1062 cutstack.push(make_pair(pars, bp.documentClassPtr()));
1069 void copySelectionToStack()
1071 if (!selectionBuffer.empty())
1072 theCuts.push(selectionBuffer[0]);
1076 void copySelectionToTemp(Cursor const & cur)
1078 copySelectionToStack(cur, tempCut);
1082 void copySelection(Cursor const & cur, docstring const & plaintext)
1084 // In tablemode, because copy and paste actually use a special table stack,
1085 // we need to go through the cells and collect the paragraphs.
1086 // In math matrices, we generate a plain text version.
1087 if (cur.selBegin().idx() != cur.selEnd().idx()) {
1089 BufferParams const & bp = cur.buffer()->params();
1090 if (cur.inMathed()) {
1092 par.setLayout(bp.documentClass().plainLayout());
1093 // Replace (column-separating) tabs by space (#4449)
1094 docstring const clean_text = subst(plaintext, '\t', ' ');
1095 // For pasting into text, we set the language to the paragraph language
1096 // (rather than the default_language which is always English; see #11898)
1097 par.insert(0, clean_text, Font(sane_font, par.getParLanguage(bp)),
1098 Change(Change::UNCHANGED));
1099 pars.push_back(par);
1101 // Get paragraphs from all cells
1102 InsetTabular * table = cur.inset().asInsetTabular();
1103 LASSERT(table, return);
1104 ParagraphList tplist = table->asParList(cur.selBegin().idx(), cur.selEnd().idx());
1105 for (auto & cpar : tplist) {
1106 cpar.setLayout(bp.documentClass().plainLayout());
1107 pars.push_back(cpar);
1108 // since the pars are merged later, we separate them by blank
1110 epar.insert(0, from_ascii(" "), Font(sane_font, epar.getParLanguage(bp)),
1111 Change(Change::UNCHANGED));
1112 pars.push_back(epar);
1114 // remove last empty par
1116 // merge all paragraphs to one
1117 while (pars.size() > 1)
1118 mergeParagraph(bp, pars, 0);
1120 theCuts.push(make_pair(pars, bp.documentClassPtr()));
1122 copySelectionToStack(cur, theCuts);
1125 // stuff the selection onto the X clipboard, from an explicit copy request
1126 putClipboard(theCuts[0].first, theCuts[0].second, plaintext,
1127 cur.buffer()->params());
1131 void saveSelection(Cursor const & cur)
1133 // This function is called, not when a selection is formed, but when
1134 // a selection is cleared. Therefore, multiple keyboard selection
1135 // will not repeatively trigger this function (bug 3877).
1137 && cur.selBegin() == cur.bv().cursor().selBegin()
1138 && cur.selEnd() == cur.bv().cursor().selEnd()) {
1139 LYXERR(Debug::SELECTION, "saveSelection: '" << cur.selectionAsString(true, true) << "'");
1140 copySelectionToStack(cur, selectionBuffer);
1147 return !selectionBuffer.empty();
1151 void clearSelection()
1153 selectionBuffer.clear();
1157 void clearCutStack()
1164 docstring selection(size_t sel_index, DocumentClassConstPtr docclass)
1166 if (sel_index >= theCuts.size())
1169 unique_ptr<Buffer> buffer(copyToTempBuffer(theCuts[sel_index].first,
1174 return buffer->paragraphs().back().asString(AS_STR_INSETS | AS_STR_NEWLINES);
1178 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
1179 DocumentClassConstPtr docclass, ErrorList & errorList,
1180 cap::BranchAction branchAction)
1182 if (cur.inTexted()) {
1183 Text * text = cur.text();
1186 PasteReturnValue prv =
1187 pasteSelectionHelper(cur, parlist, docclass, branchAction, errorList);
1188 cur.forceBufferUpdate();
1189 cur.clearSelection();
1190 text->setCursor(cur, prv.pit, prv.pos);
1193 // mathed is handled in InsetMathNest/InsetMathGrid
1194 LATTEST(!cur.inMathed());
1198 bool pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
1200 // this does not make sense, if there is nothing to paste
1201 if (!checkPastePossible(sel_index))
1205 pasteParagraphList(cur, theCuts[sel_index].first,
1206 theCuts[sel_index].second, errorList, BRANCH_ASK);
1211 bool pasteFromTemp(Cursor & cur, ErrorList & errorList)
1213 // this does not make sense, if there is nothing to paste
1214 if (tempCut.empty() || tempCut[0].first.empty())
1218 pasteParagraphList(cur, tempCut[0].first,
1219 tempCut[0].second, errorList, BRANCH_IGNORE);
1224 bool pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs,
1225 Clipboard::TextType type)
1227 // Use internal clipboard if it is the most recent one
1228 // This overrides asParagraphs and type on purpose!
1229 if (theClipboard().isInternal())
1230 return pasteFromStack(cur, errorList, 0);
1232 // First try LyX format
1233 if ((type == Clipboard::LyXTextType ||
1234 type == Clipboard::LyXOrPlainTextType ||
1235 type == Clipboard::AnyTextType) &&
1236 theClipboard().hasTextContents(Clipboard::LyXTextType)) {
1237 string lyx = theClipboard().getAsLyX();
1239 Buffer buffer(string(), false);
1240 buffer.setUnnamed(true);
1241 if (buffer.readString(lyx)) {
1243 pasteParagraphList(cur, buffer.paragraphs(),
1244 buffer.params().documentClassPtr(), errorList);
1250 // Then try TeX and HTML
1251 Clipboard::TextType types[2] = {Clipboard::HtmlTextType, Clipboard::LaTeXTextType};
1252 string names[2] = {"html", "latexclipboard"};
1253 for (int i = 0; i < 2; ++i) {
1254 if (type != types[i] && type != Clipboard::AnyTextType)
1256 bool available = theClipboard().hasTextContents(types[i]);
1258 // If a specific type was explicitly requested, try to
1259 // interpret plain text: The user told us that the clipboard
1260 // contents is in the desired format
1261 if (!available && type == types[i]) {
1262 types[i] = Clipboard::PlainTextType;
1263 available = theClipboard().hasTextContents(types[i]);
1267 docstring text = theClipboard().getAsText(types[i]);
1268 available = !text.empty();
1270 Buffer buffer(string(), false);
1271 buffer.setUnnamed(true);
1272 available = buffer.importString(names[i], text, errorList);
1274 available = !buffer.paragraphs().empty();
1275 if (available && !buffer.paragraphs()[0].empty()) {
1276 // TeX2lyx (also used in the HTML chain) assumes English as document language
1277 // if no language is explicitly set (as is the case here).
1278 // We thus reset the temp buffer's language to the context language
1279 buffer.changeLanguage(buffer.language(), cur.getFont().language());
1281 pasteParagraphList(cur, buffer.paragraphs(),
1282 buffer.params().documentClassPtr(), errorList);
1289 // Then try plain text
1290 docstring const text = theClipboard().getAsText(Clipboard::PlainTextType);
1295 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1297 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1298 cur.forceBufferUpdate();
1303 void pasteSimpleText(Cursor & cur, bool asParagraphs)
1306 // Use internal clipboard if it is the most recent one
1307 if (theClipboard().isInternal()) {
1308 if (!checkPastePossible(0))
1311 ParagraphList const & pars = theCuts[0].first;
1312 ParagraphList::const_iterator it = pars.begin();
1313 for (; it != pars.end(); ++it) {
1314 if (it != pars.begin())
1316 text += (*it).asString();
1318 asParagraphs = false;
1320 // Then try plain text
1321 text = theClipboard().getAsText(Clipboard::PlainTextType);
1328 cutSelection(cur, false);
1330 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1332 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1336 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
1337 Clipboard::GraphicsType preferedType)
1339 LASSERT(theClipboard().hasGraphicsContents(preferedType), return);
1341 // get picture from clipboard
1342 FileName filename = theClipboard().getAsGraphics(cur, preferedType);
1343 if (filename.empty())
1346 // create inset for graphic
1347 InsetGraphics * inset = new InsetGraphics(cur.buffer());
1348 InsetGraphicsParams params;
1349 params.filename = support::DocFileName(filename.absFileName(), false);
1350 inset->setParams(params);
1356 void pasteSelection(Cursor & cur, ErrorList & errorList)
1358 if (selectionBuffer.empty())
1361 pasteParagraphList(cur, selectionBuffer[0].first,
1362 selectionBuffer[0].second, errorList);
1366 void replaceSelectionWithString(Cursor & cur, docstring const & str)
1369 DocIterator selbeg = cur.selectionBegin();
1371 // Get font setting before we cut, we need a copy here, not a bare reference.
1373 selbeg.paragraph().getFontSettings(cur.buffer()->params(), selbeg.pos());
1375 // Insert the new string
1376 pos_type pos = cur.selEnd().pos();
1377 Paragraph & par = cur.selEnd().paragraph();
1378 for (auto const & c : str) {
1379 par.insertChar(pos, c, font, cur.buffer()->params().track_changes);
1383 // Cut the selection
1384 cutSelection(cur, false);
1388 void replaceSelection(Cursor & cur)
1390 if (cur.selection())
1391 cutSelection(cur, false);
1395 void eraseSelection(Cursor & cur)
1397 //lyxerr << "cap::eraseSelection begin: " << cur << endl;
1398 CursorSlice const & i1 = cur.selBegin();
1399 CursorSlice const & i2 = cur.selEnd();
1400 if (!i1.asInsetMath()) {
1401 LYXERR0("Can't erase this selection");
1407 InsetMath * p = i1.asInsetMath();
1408 if (i1.idx() == i2.idx()) {
1409 i1.cell().erase(i1.pos(), i2.pos());
1410 // We may have deleted i1.cell(cur.pos()).
1411 // Make sure that pos is valid.
1412 if (cur.pos() > cur.lastpos())
1413 cur.pos() = cur.lastpos();
1414 } else if (p->nrows() > 0 && p->ncols() > 0) {
1415 // This is a grid, delete a nice square region
1418 region(i1, i2, r1, r2, c1, c2);
1419 for (row_type row = r1; row <= r2; ++row)
1420 for (col_type col = c1; col <= c2; ++col)
1421 p->cell(p->index(row, col)).clear();
1422 // We've deleted the whole cell. Only pos 0 is valid.
1425 idx_type idx1 = i1.idx();
1426 idx_type idx2 = i2.idx();
1429 for (idx_type idx = idx1 ; idx <= idx2; ++idx)
1430 p->cell(idx).clear();
1431 // We've deleted the whole cell. Only pos 0 is valid.
1435 // need a valid cursor. (Lgb)
1436 cur.clearSelection();
1437 //lyxerr << "cap::eraseSelection end: " << cur << endl;
1441 void selDel(Cursor & cur)
1443 //lyxerr << "cap::selDel" << endl;
1444 if (cur.selection())
1445 eraseSelection(cur);
1449 void selClearOrDel(Cursor & cur)
1451 //lyxerr << "cap::selClearOrDel" << endl;
1452 if (lyxrc.auto_region_delete)
1455 cur.selection(false);
1459 docstring grabSelection(CursorData const & cur)
1461 if (!cur.selection())
1465 // grab selection by glueing multiple cells together. This is not what
1466 // we want because selections spanning multiple cells will get "&" and "\\"
1469 for (DocIterator dit = cur.selectionBegin();
1470 dit != cur.selectionEnd(); dit.forwardPos())
1471 os << asString(dit.cell());
1475 CursorSlice i1 = cur.selBegin();
1476 CursorSlice i2 = cur.selEnd();
1478 if (i1.idx() == i2.idx()) {
1479 if (i1.inset().asInsetMath()) {
1480 MathData::const_iterator it = i1.cell().begin();
1481 Buffer * buf = cur.buffer();
1482 return asString(MathData(buf, it + i1.pos(), it + i2.pos()));
1484 return from_ascii("unknown selection 1");
1490 region(i1, i2, r1, r2, c1, c2);
1493 if (i1.inset().asInsetMath()) {
1494 for (row_type row = r1; row <= r2; ++row) {
1497 for (col_type col = c1; col <= c2; ++col) {
1500 data += asString(i1.asInsetMath()->
1501 cell(i1.asInsetMath()->index(row, col)));
1505 data = from_ascii("unknown selection 2");
1511 void dirtyTabularStack(bool b)
1513 dirty_tabular_stack_ = b;
1517 bool tabularStackDirty()
1519 return dirty_tabular_stack_;