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/InsetCitation.h"
44 #include "insets/InsetCommand.h"
45 #include "insets/InsetFlex.h"
46 #include "insets/InsetGraphics.h"
47 #include "insets/InsetGraphicsParams.h"
48 #include "insets/InsetInclude.h"
49 #include "insets/InsetLabel.h"
50 #include "insets/InsetTabular.h"
52 #include "mathed/MathData.h"
53 #include "mathed/InsetMath.h"
54 #include "mathed/InsetMathHull.h"
55 #include "mathed/InsetMathRef.h"
56 #include "mathed/MathSupport.h"
58 #include "support/debug.h"
59 #include "support/docstream.h"
60 #include "support/gettext.h"
61 #include "support/lassert.h"
62 #include "support/limited_stack.h"
63 #include "support/lstrings.h"
64 #include "support/lyxalgo.h"
65 #include "support/TempFile.h"
66 #include "support/unique_ptr.h"
68 #include "frontends/alert.h"
69 #include "frontends/Clipboard.h"
70 #include "frontends/Selection.h"
76 using namespace lyx::support;
77 using lyx::frontend::Clipboard;
83 typedef pair<pit_type, int> PitPosPair;
85 typedef limited_stack<pair<ParagraphList, DocumentClassConstPtr> > CutStack;
88 // persistent selection, cleared until the next selection
89 CutStack selectionBuffer(1);
90 // temporary scratch area
93 // store whether the tabular stack is newer than the normal copy stack
94 // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
95 // when we (hopefully) have a one-for-all paste mechanism.
96 bool dirty_tabular_stack_ = false;
99 bool checkPastePossible(int index)
101 return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
105 struct PasteReturnValue {
106 PasteReturnValue(pit_type r_pit, pos_type r_pos, bool r_nu) :
107 pit(r_pit), pos(r_pos), needupdate(r_nu)
116 pasteSelectionHelper(DocIterator const & cur, ParagraphList const & parlist,
117 DocumentClassConstPtr oldDocClass, cap::BranchAction branchAction,
118 ErrorList & errorlist)
120 Buffer const & buffer = *cur.buffer();
121 pit_type pit = cur.pit();
122 pos_type pos = cur.pos();
123 bool need_update = false;
126 return PasteReturnValue(pit, pos, need_update);
128 // Check whether we paste into an inset that does not
129 // produce output (needed for label duplicate check)
130 bool in_active_inset = cur.paragraph().inInset().producesOutput();
131 if (in_active_inset) {
132 for (size_type sl = 0 ; sl < cur.depth() ; ++sl) {
133 Paragraph const & outer_par = cur[sl].paragraph();
134 if (!outer_par.inInset().producesOutput()) {
135 in_active_inset = false;
141 InsetText * target_inset = cur.inset().asInsetText();
143 InsetTabular * it = cur.inset().asInsetTabular();
144 target_inset = it ? it->cell(cur.idx())->asInsetText() : nullptr;
146 LASSERT(target_inset, return PasteReturnValue(pit, pos, need_update));
148 ParagraphList & pars = target_inset->paragraphs();
149 LASSERT(pos <= pars[pit].size(),
150 return PasteReturnValue(pit, pos, need_update));
152 // Make a copy of the CaP paragraphs.
153 ParagraphList insertion = parlist;
155 // Now remove all out of the pars which is NOT allowed in the
156 // new environment and set also another font if that is required.
158 // Merge paragraphs that are to be pasted into a text inset
159 // that does not allow multiple pars.
160 InsetText * inset_text = target_inset->asInsetText();
161 if (inset_text && !inset_text->allowMultiPar()) {
162 while (insertion.size() > 1)
163 mergeParagraph(buffer.params(), insertion, 0);
166 // Convert newline to paragraph break in ParbreakIsNewline
167 if (target_inset->getLayout().parbreakIsNewline()
168 || pars[pit].layout().parbreak_is_newline) {
169 for (size_t i = 0; i != insertion.size(); ++i) {
170 for (pos_type j = 0; j != insertion[i].size(); ++j) {
171 if (insertion[i].isNewline(j)) {
172 // do not track deletion of newline
173 insertion[i].eraseChar(j, false);
174 insertion[i].setInsetOwner(target_inset);
175 breakParagraphConservative(
184 // Prevent to paste uncodable characters in verbatim and ERT.
185 // The encoding is inherited from the context here.
186 docstring uncodable_content;
187 if (target_inset->getLayout().isPassThru() && cur.getEncoding()) {
188 odocstringstream res;
189 Encoding const * e = cur.getEncoding();
190 for (size_t i = 0; i != insertion.size(); ++i) {
191 pos_type end = insertion[i].size();
192 for (pos_type j = 0; j != end; ++j) {
194 if (insertion[i].isInset(j))
196 char_type const c = insertion[i].getChar(j);
197 if (!e->encodable(c)) {
198 // do not track deletion
200 insertion[i].eraseChar(j, false);
206 docstring const uncodable = res.str();
207 if (!uncodable.empty()) {
208 if (uncodable.size() == 1)
209 uncodable_content = bformat(_("The character \"%1$s\" is uncodable in this verbatim context "
210 "and thus has not been pasted."),
213 uncodable_content = bformat(_("The characters \"%1$s\" are uncodable in this verbatim context "
214 "and thus have not been pasted."),
219 // set the paragraphs to plain layout if necessary
220 DocumentClassConstPtr newDocClass = buffer.params().documentClassPtr();
221 Layout const & plainLayout = newDocClass->plainLayout();
222 Layout const & defaultLayout = newDocClass->defaultLayout();
223 if (cur.inset().usePlainLayout()) {
224 bool forcePlainLayout = target_inset->forcePlainLayout();
225 for (auto & par : insertion) {
226 Layout const & parLayout = par.layout();
227 if (forcePlainLayout || parLayout == defaultLayout)
228 par.setLayout(plainLayout);
231 // check if we need to reset from plain layout
232 for (auto & par : insertion) {
233 Layout const & parLayout = par.layout();
234 if (parLayout == plainLayout)
235 par.setLayout(defaultLayout);
239 InsetText in(cur.buffer());
240 // Make sure there is no class difference.
241 in.paragraphs().clear();
242 // This works without copying any paragraph data because we have
243 // a specialized swap method for ParagraphList. This is important
244 // since we store pointers to insets at some places and we don't
245 // want to invalidate them.
246 insertion.swap(in.paragraphs());
247 cap::switchBetweenClasses(oldDocClass, newDocClass, in, errorlist);
248 // Do this here since switchBetweenClasses clears the errorlist
249 if (!uncodable_content.empty())
250 errorlist.push_back(ErrorItem(_("Uncodable content"), uncodable_content));
251 insertion.swap(in.paragraphs());
253 ParagraphList::iterator tmpbuf = insertion.begin();
254 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
256 depth_type max_depth = pars[pit].getMaxDepthAfter();
258 for (; tmpbuf != insertion.end(); ++tmpbuf) {
259 // If we have a negative jump so that the depth would
260 // go below 0 depth then we have to redo the delta to
261 // this new max depth level so that subsequent
262 // paragraphs are aligned correctly to this paragraph
264 if (int(tmpbuf->params().depth()) + depth_delta < 0)
267 // Set the right depth so that we are not too deep or shallow.
268 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
269 if (tmpbuf->params().depth() > max_depth)
270 tmpbuf->params().depth(max_depth);
272 // Set max_depth for the next paragraph
273 max_depth = tmpbuf->getMaxDepthAfter();
275 // Set the inset owner of this paragraph.
276 tmpbuf->setInsetOwner(target_inset);
277 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
278 // do not track deletion of invalid insets
279 if (Inset * inset = tmpbuf->getInset(i))
280 if (!target_inset->insetAllowed(inset->lyxCode()))
281 tmpbuf->eraseChar(i--, false);
284 if (lyxrc.ct_markup_copied)
285 tmpbuf->setChange(Change(buffer.params().track_changes ?
286 Change::INSERTED : Change::UNCHANGED));
289 bool const empty = pars[pit].empty();
291 // Make the buf exactly the same layout as the cursor
293 insertion.begin()->makeSameLayout(pars[pit]);
296 // Prepare the paragraphs and insets for insertion.
297 insertion.swap(in.paragraphs());
299 InsetIterator const i_end = inset_iterator_end(in);
300 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
301 // Even though this will also be done later, it has to be done here
302 // since some inset might try to access the buffer() member.
303 it->setBuffer(const_cast<Buffer &>(buffer));
304 switch (it->lyxCode()) {
306 case MATH_HULL_CODE: {
307 // check for equation labels and resolve duplicates
308 InsetMathHull * ins = it->asInsetMath()->asHullInset();
309 std::vector<InsetLabel *> labels = ins->getLabels();
310 for (size_t i = 0; i != labels.size(); ++i) {
313 InsetLabel * lab = labels[i];
314 docstring const oldname = lab->getParam("name");
315 lab->updateLabel(oldname, in_active_inset);
316 // We need to update the buffer reference cache.
318 docstring const newname = lab->getParam("name");
319 if (oldname == newname)
321 // adapt the references
322 for (InsetIterator itt = inset_iterator_begin(in);
323 itt != i_end; ++itt) {
324 if (itt->lyxCode() == REF_CODE) {
325 InsetCommand * ref = itt->asInsetCommand();
326 if (ref->getParam("reference") == oldname)
327 ref->setParam("reference", newname);
328 } else if (itt->lyxCode() == MATH_REF_CODE) {
329 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
330 // this is necessary to prevent an uninitialized
331 // buffer when the RefInset is in a MathBox.
332 // FIXME audit setBuffer calls
333 mi->setBuffer(const_cast<Buffer &>(buffer));
334 if (mi->getTarget() == oldname)
335 mi->changeTarget(newname);
343 // check for duplicates
344 InsetLabel & lab = static_cast<InsetLabel &>(*it);
345 docstring const oldname = lab.getParam("name");
346 lab.updateLabel(oldname, in_active_inset);
347 // We need to update the buffer reference cache.
349 docstring const newname = lab.getParam("name");
350 if (oldname == newname)
352 // adapt the references
353 for (InsetIterator itt = inset_iterator_begin(in); itt != i_end; ++itt) {
354 if (itt->lyxCode() == REF_CODE) {
355 InsetCommand & ref = static_cast<InsetCommand &>(*itt);
356 if (ref.getParam("reference") == oldname)
357 ref.setParam("reference", newname);
358 } else if (itt->lyxCode() == MATH_REF_CODE) {
359 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
360 // this is necessary to prevent an uninitialized
361 // buffer when the RefInset is in a MathBox.
362 // FIXME audit setBuffer calls
363 mi->setBuffer(const_cast<Buffer &>(buffer));
364 if (mi->getTarget() == oldname)
365 mi->changeTarget(newname);
372 InsetInclude & inc = static_cast<InsetInclude &>(*it);
374 // We need to update the list of included files.
380 InsetCitation & cit = static_cast<InsetCitation &>(*it);
381 // This actually only needs to be done if the cite engine
382 // differs, but we do it in general.
384 // We need to update the list of citations.
390 // check for duplicates
391 InsetBibitem & bib = static_cast<InsetBibitem &>(*it);
392 docstring const oldkey = bib.getParam("key");
393 bib.updateCommand(oldkey, false);
394 // We need to update the buffer reference cache.
396 docstring const newkey = bib.getParam("key");
397 if (oldkey == newkey)
399 // adapt the references
400 for (InsetIterator itt = inset_iterator_begin(in);
401 itt != i_end; ++itt) {
402 if (itt->lyxCode() == CITE_CODE) {
403 InsetCommand * ref = itt->asInsetCommand();
404 if (ref->getParam("key") == oldkey)
405 ref->setParam("key", newkey);
412 // check if branch is known to target buffer
414 InsetBranch & br = static_cast<InsetBranch &>(*it);
415 docstring const name = br.branch();
418 bool const is_child = (&buffer != buffer.masterBuffer());
419 BranchList branchlist = buffer.params().branchlist();
420 if ((!is_child && branchlist.find(name))
421 || (is_child && (branchlist.find(name)
422 || buffer.masterBuffer()->params().branchlist().find(name))))
424 switch(branchAction) {
425 case cap::BRANCH_ADD: {
426 // This is for a temporary buffer, so simply create the branch.
427 // Must not use lyx::dispatch(), since tmpbuffer has no view.
429 const_cast<Buffer&>(buffer).dispatch(FuncRequest(LFUN_BRANCH_ADD, name), dr);
432 case cap::BRANCH_ASK: {
433 docstring text = bformat(
434 _("The pasted branch \"%1$s\" is undefined.\n"
435 "Do you want to add it to the document's branch list?"),
437 if (frontend::Alert::prompt(_("Unknown branch"),
438 text, 0, 1, _("&Add"), _("&Don't Add")) != 0)
440 lyx::dispatch(FuncRequest(LFUN_BRANCH_ADD, name));
443 case cap::BRANCH_IGNORE:
446 // We need to update the list of branches.
455 insertion.swap(in.paragraphs());
457 // Split the paragraph for inserting the buf if necessary.
459 breakParagraphConservative(buffer.params(), pars, pit, pos);
463 pars.insert(pars.iterator_at(pit),
464 insertion.begin(), insertion.end());
466 // merge the empty par with the last par of the insertion
467 mergeParagraph(buffer.params(), pars,
468 pit + insertion.size() - 1);
470 pars.insert(pars.iterator_at(pit + 1),
471 insertion.begin(), insertion.end());
473 // merge the first par of the insertion with the current par
474 mergeParagraph(buffer.params(), pars, pit);
477 // Store the new cursor position.
478 pit_type last_paste = pit + insertion.size() - 1;
479 pit_type startpit = pit;
481 pos = pars[last_paste].size();
483 // FIXME Should we do it here, or should we let updateBuffer() do it?
484 // Set paragraph buffers. It's important to do this right away
485 // before something calls Inset::buffer() and causes a crash.
486 for (pit_type p = startpit; p <= pit; ++p)
487 pars[p].setInsetBuffers(const_cast<Buffer &>(buffer));
489 // Join (conditionally) last pasted paragraph with next one, i.e.,
490 // the tail of the spliced document paragraph
491 if (!empty && last_paste + 1 != pit_type(pars.size())) {
492 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
493 mergeParagraph(buffer.params(), pars, last_paste);
494 } else if (pars[last_paste + 1].empty()) {
495 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
496 mergeParagraph(buffer.params(), pars, last_paste);
497 } else if (pars[last_paste].empty()) {
498 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
499 mergeParagraph(buffer.params(), pars, last_paste);
501 pars[last_paste + 1].stripLeadingSpaces(buffer.params().track_changes);
506 return PasteReturnValue(pit, pos, need_update);
510 PitPosPair eraseSelectionHelper(BufferParams const & params,
511 ParagraphList & pars,
512 pit_type startpit, pit_type endpit,
513 int startpos, int endpos)
515 // Start of selection is really invalid.
516 if (startpit == pit_type(pars.size()) ||
517 (startpos > pars[startpit].size()))
518 return PitPosPair(endpit, endpos);
520 // Start and end is inside same paragraph
521 if (endpit == pit_type(pars.size()) || startpit == endpit) {
522 endpos -= pars[startpit].eraseChars(startpos, endpos, params.track_changes);
523 return PitPosPair(endpit, endpos);
526 for (pit_type pit = startpit; pit != endpit + 1;) {
527 pos_type const left = (pit == startpit ? startpos : 0);
528 pos_type right = (pit == endpit ? endpos : pars[pit].size() + 1);
529 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.track_changes);
531 // Logically erase only, including the end-of-paragraph character
532 pars[pit].eraseChars(left, right, params.track_changes);
534 // Separate handling of paragraph break:
535 if (merge && pit != endpit &&
537 || pars[pit].hasSameLayout(pars[endpit])
538 || pars[endpit].size() == endpos)) {
539 if (pit + 1 == endpit)
540 endpos += pars[pit].size();
541 mergeParagraph(params, pars, pit);
547 // Ensure legal cursor pos:
550 return PitPosPair(endpit, endpos);
554 Buffer * copyToTempBuffer(ParagraphList const & paragraphs, DocumentClassConstPtr docclass)
556 // This used to need to be static to avoid a memory leak. It no longer needs
557 // to be so, but the alternative is to construct a new one of these (with a
558 // new temporary directory, etc) every time, and then to destroy it. So maybe
559 // it's worth just keeping this one around.
560 static TempFile tempfile("clipboard.internal");
561 tempfile.setAutoRemove(false);
562 // The initialization of staticbuffer is thread-safe. Using a lambda
563 // guarantees that the properties are set only once.
564 static Buffer * staticbuffer = [&](){
566 theBufferList().newInternalBuffer(tempfile.name().absFileName());
568 b->inset().setBuffer(*b);
569 //initialize staticbuffer with b
572 // Use a clone for the complicated stuff so that we do not need to clean
573 // up in order to avoid a crash.
574 Buffer * buffer = staticbuffer->cloneBufferOnly();
575 LASSERT(buffer, return nullptr);
577 // This needs doing every time.
578 // Since setDocumentClass() causes deletion of the old document class
579 // we need to reset all layout pointers in paragraphs (otherwise they
580 // would be dangling).
581 ParIterator const end = buffer->par_iterator_end();
582 for (ParIterator it = buffer->par_iterator_begin(); it != end; ++it) {
583 docstring const name = it->layout().name();
584 if (docclass->hasLayout(name))
585 it->setLayout((*docclass)[name]);
587 it->setPlainOrDefaultLayout(*docclass);
589 buffer->params().setDocumentClass(docclass);
591 // we will use pasteSelectionHelper to copy the paragraphs into the
592 // temporary Buffer, since it does a lot of things to fix them up.
593 DocIterator dit = doc_iterator_begin(buffer, &buffer->inset());
595 pasteSelectionHelper(dit, paragraphs, docclass, cap::BRANCH_ADD, el);
601 void putClipboard(ParagraphList const & paragraphs,
602 DocumentClassConstPtr docclass, docstring const & plaintext,
603 BufferParams const & bp)
605 Buffer * buffer = copyToTempBuffer(paragraphs, docclass);
606 if (!buffer) // already asserted in copyToTempBuffer()
609 // We don't want to produce images that are not used. Therefore,
610 // output formulas as MathML. Even if this is not understood by all
611 // applications, the number that can parse it should go up in the future.
612 buffer->params().html_math_output = BufferParams::MathML;
614 if (lyxrc.ct_markup_copied) {
615 // Copy authors to the params. We need those pointers.
616 for (Author const & a : bp.authors())
617 buffer->params().authors().record(a);
620 // Make sure MarkAsExporting is deleted before buffer is
622 // The Buffer is being used to export. This is necessary so that the
623 // updateMacros call will record the needed information.
624 MarkAsExporting mex(buffer);
626 buffer->updateBuffer(Buffer::UpdateMaster, OutputUpdate);
627 buffer->updateMacros();
628 buffer->updateMacroInstances(OutputUpdate);
633 if (buffer->write(oslyx))
637 odocstringstream oshtml;
638 OutputParams runparams(encodings.fromLyXName("utf8"));
639 // We do not need to produce images, etc.
640 runparams.dryrun = true;
641 // We are not interested in errors (bug 8866)
642 runparams.silent = true;
643 buffer->writeLyXHTMLSource(oshtml, runparams, Buffer::FullSource);
645 theClipboard().put(lyx, oshtml.str(), plaintext);
653 /// return true if the whole ParagraphList is deleted
654 static bool isFullyDeleted(ParagraphList const & pars)
656 pit_type const pars_size = static_cast<pit_type>(pars.size());
658 // check all paragraphs
659 for (pit_type pit = 0; pit < pars_size; ++pit) {
660 if (!pars[pit].empty()) // prevent assertion failure
661 if (!pars[pit].isDeleted(0, pars[pit].size()))
668 void copySelectionHelper(Buffer const & buf, Text const & text,
669 pit_type startpit, pit_type endpit,
670 int start, int end, DocumentClassConstPtr dc, CutStack & cutstack)
672 ParagraphList const & pars = text.paragraphs();
674 // In most of these cases, we can try to recover.
675 LASSERT(0 <= start, start = 0);
676 LASSERT(start <= pars[startpit].size(), start = pars[startpit].size());
677 LASSERT(0 <= end, end = 0);
678 LASSERT(end <= pars[endpit].size(), end = pars[endpit].size());
679 LASSERT(startpit != endpit || start <= end, return);
681 // Clone the paragraphs within the selection.
682 ParagraphList copy_pars(pars.iterator_at(startpit),
683 pars.iterator_at(endpit + 1));
685 // Remove the end of the last paragraph; afterwards, remove the
686 // beginning of the first paragraph. Keep this order - there may only
687 // be one paragraph! Do not track deletions here; this is an internal
688 // action not visible to the user
690 Paragraph & back = copy_pars.back();
691 back.eraseChars(end, back.size(), false);
692 Paragraph & front = copy_pars.front();
693 front.eraseChars(0, start, false);
695 for (auto & par : copy_pars) {
696 // Since we have a copy of the paragraphs, the insets
697 // do not have a proper buffer reference. It makes
698 // sense to add them temporarily, because the
699 // operations below depend on that (acceptChanges included).
700 par.setInsetBuffers(const_cast<Buffer &>(buf));
701 // PassThru paragraphs have the Language
702 // latex_language. This is invalid for others, so we
703 // need to change it to the buffer language.
704 if (par.isPassThru())
705 par.changeLanguage(buf.params(),
706 latex_language, buf.language());
709 // do not copy text (also nested in insets) which is marked as
710 // deleted, unless the whole selection was deleted
711 if (!lyxrc.ct_markup_copied) {
712 if (!isFullyDeleted(copy_pars))
713 acceptChanges(copy_pars, buf.params());
715 rejectChanges(copy_pars, buf.params());
719 // do some final cleanup now, to make sure that the paragraphs
720 // are not linked to something else.
721 for (auto & par : copy_pars) {
723 par.setInsetOwner(nullptr);
726 cutstack.push(make_pair(copy_pars, dc));
734 void region(CursorSlice const & i1, CursorSlice const & i2,
735 Inset::row_type & r1, Inset::row_type & r2,
736 Inset::col_type & c1, Inset::col_type & c2)
738 Inset const & p = i1.inset();
739 c1 = p.col(i1.idx());
740 c2 = p.col(i2.idx());
743 r1 = p.row(i1.idx());
744 r2 = p.row(i2.idx());
750 docstring grabAndEraseSelection(Cursor & cur)
752 if (!cur.selection())
754 docstring res = grabSelection(cur);
760 bool reduceSelectionToOneCell(CursorData & cur)
762 if (!cur.selection() || !cur.inMathed())
765 CursorSlice i1 = cur.selBegin();
766 CursorSlice i2 = cur.selEnd();
767 if (!i1.inset().asInsetMath())
770 // the easy case: do nothing if only one cell is selected
771 if (i1.idx() == i2.idx())
776 cur.top().pos() = cur.top().lastpos();
782 bool multipleCellsSelected(CursorData const & cur)
784 if (!cur.selection() || !cur.inMathed())
787 CursorSlice i1 = cur.selBegin();
788 CursorSlice i2 = cur.selEnd();
789 if (!i1.inset().asInsetMath())
792 if (i1.idx() == i2.idx())
799 void switchBetweenClasses(DocumentClassConstPtr oldone,
800 DocumentClassConstPtr newone, InsetText & in, ErrorList & errorlist)
804 LBUFERR(!in.paragraphs().empty());
805 if (oldone == newone)
808 DocumentClass const & oldtc = *oldone;
809 DocumentClass const & newtc = *newone;
812 ParIterator it = par_iterator_begin(in);
813 ParIterator end = par_iterator_end(in);
814 // for remembering which layouts we've had to add
815 set<docstring> newlayouts;
816 for (; it != end; ++it) {
817 docstring const name = it->layout().name();
819 // the pasted text will keep their own layout name. If this layout does
820 // not exist in the new document, it will behave like a standard layout.
821 bool const added_one = newtc.addLayoutIfNeeded(name);
823 newlayouts.insert(name);
825 if (added_one || newlayouts.find(name) != newlayouts.end()) {
827 docstring const s = bformat(_("Layout `%1$s' was not found."), name);
828 errorlist.push_back(ErrorItem(_("Layout Not Found"), s,
829 {it->id(), 0}, {it->id(), -1}));
832 if (in.usePlainLayout())
833 it->setLayout(newtc.plainLayout());
835 it->setLayout(newtc[name]);
838 // character styles and hidden table cells
839 InsetIterator const i_end = inset_iterator_end(in);
840 for (InsetIterator iit = inset_iterator_begin(in); iit != i_end; ++iit) {
841 InsetCode const code = iit->lyxCode();
842 if (code == FLEX_CODE) {
843 // FIXME: Should we verify all InsetCollapsible?
844 docstring const layoutName = iit->layoutName();
845 docstring const & n = newone->insetLayout(layoutName).name();
846 bool const is_undefined = n.empty() ||
847 n == DocumentClass::plainInsetLayout().name();
851 // The flex inset is undefined in newtc
852 docstring const oldname = from_utf8(oldtc.name());
853 docstring const newname = from_utf8(newtc.name());
855 if (oldname == newname)
856 s = bformat(_("Flex inset %1$s is undefined after "
857 "reloading `%2$s' layout."), layoutName, oldname);
859 s = bformat(_("Flex inset %1$s is undefined because of "
860 "conversion from `%2$s' layout to `%3$s'."),
861 layoutName, oldname, newname);
862 // To warn the user that something had to be done.
863 errorlist.push_back(ErrorItem(
864 _("Undefined flex inset"), s,
865 {iit.paragraph().id(), iit.pos()},
866 {iit.paragraph().id(), iit.pos() + 1}));
867 } else if (code == TABULAR_CODE) {
868 // The recursion above does not catch paragraphs in "hidden" cells,
869 // i.e., ones that are part of a multirow or multicolum. So we need
870 // to handle those separately.
871 // This is the cause of bug #9049.
872 InsetTabular * table = iit->asInsetTabular();
873 table->setLayoutForHiddenCells(newtc);
879 vector<docstring> availableSelections(Buffer const * buf)
881 vector<docstring> selList;
885 for (auto const & cut : theCuts) {
886 ParagraphList const & pars = cut.first;
888 for (auto const & para : pars) {
889 Paragraph par(para, 0, 46);
890 // adapt paragraph to current buffer.
891 par.setInsetBuffers(const_cast<Buffer &>(*buf));
892 textSel += par.asString(AS_STR_INSETS);
893 if (textSel.size() > 45) {
894 support::truncateWithEllipsis(textSel,45);
898 selList.push_back(textSel);
905 size_type numberOfSelections()
907 return theCuts.size();
912 void cutSelectionHelper(Cursor & cur, CutStack & cuts, bool realcut, bool putclip)
914 // This doesn't make sense, if there is no selection
915 if (!cur.selection())
918 // OK, we have a selection. This is always between cur.selBegin()
921 if (cur.inTexted()) {
922 Text * text = cur.text();
927 // make sure that the depth behind the selection are restored, too
928 cur.recordUndoSelection();
929 pit_type begpit = cur.selBegin().pit();
930 pit_type endpit = cur.selEnd().pit();
932 int endpos = cur.selEnd().pos();
934 BufferParams const & bp = cur.buffer()->params();
936 copySelectionHelper(*cur.buffer(),
939 cur.selBegin().pos(), endpos,
940 bp.documentClassPtr(), cuts);
941 // Stuff what we got on the clipboard.
942 // Even if there is no selection.
944 putClipboard(cuts[0].first, cuts[0].second,
945 cur.selectionAsString(true, true), bp);
948 if (begpit != endpit)
949 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
951 tie(endpit, endpos) =
952 eraseSelectionHelper(bp, text->paragraphs(), begpit, endpit,
953 cur.selBegin().pos(), endpos);
955 // cutSelection can invalidate the cursor so we need to set
957 // we prefer the end for when tracking changes
961 // need a valid cursor. (Lgb)
962 cur.clearSelection();
964 // After a cut operation, we must make sure that the Buffer is updated
965 // because some further operation might need updated label information for
966 // example. So we cannot just use "cur.forceBufferUpdate()" here.
968 cur.buffer()->updateBuffer();
970 // tell tabular that a recent copy happened
971 dirtyTabularStack(false);
974 if (cur.inMathed()) {
975 if (cur.selBegin().idx() != cur.selEnd().idx()) {
976 // The current selection spans more than one cell.
978 cur.recordUndoInset();
980 // Record only the current cell to avoid a jumping
992 void cutSelection(Cursor & cur, bool realcut)
994 cutSelectionHelper(cur, theCuts, realcut, true);
998 void cutSelectionToTemp(Cursor & cur, bool realcut)
1000 cutSelectionHelper(cur, tempCut, realcut, false);
1004 void copySelection(Cursor const & cur)
1006 copySelection(cur, cur.selectionAsString(true, true));
1010 void copyInset(Cursor const & cur, Inset * inset, docstring const & plaintext)
1014 BufferParams const & bp = cur.buffer()->params();
1015 par.setLayout(bp.documentClass().plainLayout());
1016 Font font(inherit_font, bp.language);
1017 par.insertInset(0, inset, font, Change(Change::UNCHANGED));
1018 pars.push_back(par);
1019 theCuts.push(make_pair(pars, bp.documentClassPtr()));
1021 // stuff the selection onto the X clipboard, from an explicit copy request
1022 putClipboard(theCuts[0].first, theCuts[0].second, plaintext, bp);
1028 void copySelectionToStack(CursorData const & cur, CutStack & cutstack)
1030 // this doesn't make sense, if there is no selection
1031 if (!cur.selection())
1034 // copySelection can not yet handle the case of cross idx selection
1035 if (cur.selBegin().idx() != cur.selEnd().idx())
1038 if (cur.inTexted()) {
1039 Text * text = cur.text();
1041 // ok we have a selection. This is always between cur.selBegin()
1042 // and sel_end cursor
1043 copySelectionHelper(*cur.buffer(), *text,
1044 cur.selBegin().pit(), cur.selEnd().pit(),
1045 cur.selBegin().pos(), cur.selEnd().pos(),
1046 cur.buffer()->params().documentClassPtr(),
1048 // Reset the dirty_tabular_stack_ flag only when something
1049 // is copied to the clipboard (not to the selectionBuffer).
1050 if (&cutstack == &theCuts)
1051 dirtyTabularStack(false);
1054 if (cur.inMathed()) {
1055 //lyxerr << "copySelection in mathed" << endl;
1058 BufferParams const & bp = cur.buffer()->params();
1059 // FIXME This should be the plain layout...right?
1060 par.setLayout(bp.documentClass().plainLayout());
1061 // For pasting into text, we set the language to the paragraph language
1062 // (rather than the default_language which is always English; see #2596)
1063 par.insert(0, grabSelection(cur), Font(sane_font, par.getParLanguage(bp)),
1064 Change(Change::UNCHANGED));
1065 pars.push_back(par);
1066 cutstack.push(make_pair(pars, bp.documentClassPtr()));
1073 void copySelectionToStack()
1075 if (!selectionBuffer.empty())
1076 theCuts.push(selectionBuffer[0]);
1080 void copySelectionToTemp(Cursor const & cur)
1082 copySelectionToStack(cur, tempCut);
1086 void copySelection(Cursor const & cur, docstring const & plaintext)
1088 // In tablemode, because copy and paste actually use a special table stack,
1089 // we need to go through the cells and collect the paragraphs.
1090 // In math matrices, we generate a plain text version.
1091 if (cur.selBegin().idx() != cur.selEnd().idx()) {
1093 BufferParams const & bp = cur.buffer()->params();
1094 if (cur.inMathed()) {
1096 par.setLayout(bp.documentClass().plainLayout());
1097 // Replace (column-separating) tabs by space (#4449)
1098 docstring const clean_text = subst(plaintext, '\t', ' ');
1099 // For pasting into text, we set the language to the paragraph language
1100 // (rather than the default_language which is always English; see #11898)
1101 par.insert(0, clean_text, Font(sane_font, par.getParLanguage(bp)),
1102 Change(Change::UNCHANGED));
1103 pars.push_back(par);
1105 // Get paragraphs from all cells
1106 InsetTabular * table = cur.inset().asInsetTabular();
1107 LASSERT(table, return);
1108 ParagraphList tplist = table->asParList(cur.selBegin().idx(), cur.selEnd().idx());
1109 for (auto & cpar : tplist) {
1110 cpar.setLayout(bp.documentClass().plainLayout());
1111 pars.push_back(cpar);
1112 // since the pars are merged later, we separate them by blank
1114 epar.insert(0, from_ascii(" "), Font(sane_font, epar.getParLanguage(bp)),
1115 Change(Change::UNCHANGED));
1116 pars.push_back(epar);
1118 // remove last empty par
1120 // merge all paragraphs to one
1121 while (pars.size() > 1)
1122 mergeParagraph(bp, pars, 0);
1124 theCuts.push(make_pair(pars, bp.documentClassPtr()));
1126 copySelectionToStack(cur, theCuts);
1129 // stuff the selection onto the X clipboard, from an explicit copy request
1130 putClipboard(theCuts[0].first, theCuts[0].second, plaintext,
1131 cur.buffer()->params());
1135 void saveSelection(Cursor const & cur)
1137 // This function is called, not when a selection is formed, but when
1138 // a selection is cleared. Therefore, multiple keyboard selection
1139 // will not repeatively trigger this function (bug 3877).
1141 && cur.selBegin() == cur.bv().cursor().selBegin()
1142 && cur.selEnd() == cur.bv().cursor().selEnd()) {
1143 LYXERR(Debug::SELECTION, "saveSelection: '" << cur.selectionAsString(true, true) << "'");
1144 copySelectionToStack(cur, selectionBuffer);
1151 return !selectionBuffer.empty();
1155 void clearSelection()
1157 selectionBuffer.clear();
1161 void clearCutStack()
1168 docstring selection(size_t sel_index, DocumentClassConstPtr docclass)
1170 if (sel_index >= theCuts.size())
1173 unique_ptr<Buffer> buffer(copyToTempBuffer(theCuts[sel_index].first,
1178 return buffer->paragraphs().back().asString(AS_STR_INSETS | AS_STR_NEWLINES);
1182 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
1183 DocumentClassConstPtr docclass, ErrorList & errorList,
1184 cap::BranchAction branchAction)
1186 if (cur.inTexted()) {
1187 Text * text = cur.text();
1190 PasteReturnValue prv =
1191 pasteSelectionHelper(cur, parlist, docclass, branchAction, errorList);
1192 cur.forceBufferUpdate();
1193 cur.clearSelection();
1194 text->setCursor(cur, prv.pit, prv.pos);
1197 // mathed is handled in InsetMathNest/InsetMathGrid
1198 LATTEST(!cur.inMathed());
1202 bool pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
1204 // this does not make sense, if there is nothing to paste
1205 if (!checkPastePossible(sel_index))
1209 pasteParagraphList(cur, theCuts[sel_index].first,
1210 theCuts[sel_index].second, errorList, BRANCH_ASK);
1215 bool pasteFromTemp(Cursor & cur, ErrorList & errorList)
1217 // this does not make sense, if there is nothing to paste
1218 if (tempCut.empty() || tempCut[0].first.empty())
1222 pasteParagraphList(cur, tempCut[0].first,
1223 tempCut[0].second, errorList, BRANCH_IGNORE);
1228 bool pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs,
1229 Clipboard::TextType type)
1231 // Use internal clipboard if it is the most recent one
1232 // This overrides asParagraphs and type on purpose!
1233 if (theClipboard().isInternal())
1234 return pasteFromStack(cur, errorList, 0);
1236 // First try LyX format
1237 if ((type == Clipboard::LyXTextType ||
1238 type == Clipboard::LyXOrPlainTextType ||
1239 type == Clipboard::AnyTextType) &&
1240 theClipboard().hasTextContents(Clipboard::LyXTextType)) {
1241 string lyx = theClipboard().getAsLyX();
1243 Buffer buffer(string(), false);
1244 buffer.setUnnamed(true);
1245 if (buffer.readString(lyx)) {
1247 pasteParagraphList(cur, buffer.paragraphs(),
1248 buffer.params().documentClassPtr(), errorList);
1254 // Then try TeX and HTML
1255 Clipboard::TextType types[2] = {Clipboard::HtmlTextType, Clipboard::LaTeXTextType};
1256 string names[2] = {"html", "latexclipboard"};
1257 for (int i = 0; i < 2; ++i) {
1258 if (type != types[i] && type != Clipboard::AnyTextType)
1260 bool available = theClipboard().hasTextContents(types[i]);
1262 // If a specific type was explicitly requested, try to
1263 // interpret plain text: The user told us that the clipboard
1264 // contents is in the desired format
1265 if (!available && type == types[i]) {
1266 types[i] = Clipboard::PlainTextType;
1267 available = theClipboard().hasTextContents(types[i]);
1271 docstring text = theClipboard().getAsText(types[i]);
1272 available = !text.empty();
1274 Buffer buffer(string(), false);
1275 buffer.setUnnamed(true);
1276 available = buffer.importString(names[i], text, errorList);
1278 available = !buffer.paragraphs().empty();
1279 if (available && !buffer.paragraphs()[0].empty()) {
1280 // TeX2lyx (also used in the HTML chain) assumes English as document language
1281 // if no language is explicitly set (as is the case here).
1282 // We thus reset the temp buffer's language to the context language
1283 buffer.changeLanguage(buffer.language(), cur.getFont().language());
1285 pasteParagraphList(cur, buffer.paragraphs(),
1286 buffer.params().documentClassPtr(), errorList);
1293 // Then try plain text
1294 docstring const text = theClipboard().getAsText(Clipboard::PlainTextType);
1299 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1301 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1302 cur.forceBufferUpdate();
1307 void pasteSimpleText(Cursor & cur, bool asParagraphs)
1310 // Use internal clipboard if it is the most recent one
1311 if (theClipboard().isInternal()) {
1312 if (!checkPastePossible(0))
1315 ParagraphList const & pars = theCuts[0].first;
1316 ParagraphList::const_iterator it = pars.begin();
1317 for (; it != pars.end(); ++it) {
1318 if (it != pars.begin())
1320 text += (*it).asString();
1322 asParagraphs = false;
1324 // Then try plain text
1325 text = theClipboard().getAsText(Clipboard::PlainTextType);
1332 cutSelection(cur, false);
1334 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1336 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1340 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
1341 Clipboard::GraphicsType preferedType)
1343 LASSERT(theClipboard().hasGraphicsContents(preferedType), return);
1345 // get picture from clipboard
1346 FileName filename = theClipboard().getAsGraphics(cur, preferedType);
1347 if (filename.empty())
1350 // create inset for graphic
1351 InsetGraphics * inset = new InsetGraphics(cur.buffer());
1352 InsetGraphicsParams params;
1353 params.filename = support::DocFileName(filename.absFileName(), false);
1354 inset->setParams(params);
1360 void pasteSelection(Cursor & cur, ErrorList & errorList)
1362 if (selectionBuffer.empty())
1365 pasteParagraphList(cur, selectionBuffer[0].first,
1366 selectionBuffer[0].second, errorList);
1370 void replaceSelectionWithString(Cursor & cur, docstring const & str)
1373 DocIterator selbeg = cur.selectionBegin();
1375 // Get font setting before we cut, we need a copy here, not a bare reference.
1377 selbeg.paragraph().getFontSettings(cur.buffer()->params(), selbeg.pos());
1379 // Insert the new string
1380 pos_type pos = cur.selEnd().pos();
1381 Paragraph & par = cur.selEnd().paragraph();
1382 for (auto const & c : str) {
1383 par.insertChar(pos, c, font, cur.buffer()->params().track_changes);
1387 // Cut the selection
1388 cutSelection(cur, false);
1392 void replaceSelection(Cursor & cur)
1394 if (cur.selection())
1395 cutSelection(cur, false);
1399 void eraseSelection(Cursor & cur)
1401 //lyxerr << "cap::eraseSelection begin: " << cur << endl;
1402 CursorSlice const & i1 = cur.selBegin();
1403 CursorSlice const & i2 = cur.selEnd();
1404 if (!i1.asInsetMath()) {
1405 LYXERR0("Can't erase this selection");
1411 InsetMath * p = i1.asInsetMath();
1412 if (i1.idx() == i2.idx()) {
1413 i1.cell().erase(i1.pos(), i2.pos());
1414 // We may have deleted i1.cell(cur.pos()).
1415 // Make sure that pos is valid.
1416 if (cur.pos() > cur.lastpos())
1417 cur.pos() = cur.lastpos();
1418 } else if (p->nrows() > 0 && p->ncols() > 0) {
1419 // This is a grid, delete a nice square region
1420 Inset::row_type r1, r2;
1421 Inset::col_type c1, c2;
1422 region(i1, i2, r1, r2, c1, c2);
1423 for (Inset::row_type row = r1; row <= r2; ++row)
1424 for (Inset::col_type col = c1; col <= c2; ++col)
1425 p->cell(p->index(row, col)).clear();
1426 // We've deleted the whole cell. Only pos 0 is valid.
1429 Inset::idx_type idx1 = i1.idx();
1430 Inset::idx_type idx2 = i2.idx();
1433 for (Inset::idx_type idx = idx1 ; idx <= idx2; ++idx)
1434 p->cell(idx).clear();
1435 // We've deleted the whole cell. Only pos 0 is valid.
1439 // need a valid cursor. (Lgb)
1440 cur.clearSelection();
1441 //lyxerr << "cap::eraseSelection end: " << cur << endl;
1445 void selDel(Cursor & cur)
1447 //lyxerr << "cap::selDel" << endl;
1448 if (cur.selection())
1449 eraseSelection(cur);
1453 void selClearOrDel(Cursor & cur)
1455 //lyxerr << "cap::selClearOrDel" << endl;
1456 if (lyxrc.auto_region_delete)
1459 cur.selection(false);
1463 docstring grabSelection(CursorData const & cur)
1465 if (!cur.selection())
1469 // grab selection by glueing multiple cells together. This is not what
1470 // we want because selections spanning multiple cells will get "&" and "\\"
1473 for (DocIterator dit = cur.selectionBegin();
1474 dit != cur.selectionEnd(); dit.forwardPos())
1475 os << asString(dit.cell());
1479 CursorSlice i1 = cur.selBegin();
1480 CursorSlice i2 = cur.selEnd();
1482 if (i1.idx() == i2.idx()) {
1483 if (i1.inset().asInsetMath()) {
1484 MathData::const_iterator it = i1.cell().begin();
1485 Buffer * buf = cur.buffer();
1486 return asString(MathData(buf, it + i1.pos(), it + i2.pos()));
1488 return from_ascii("unknown selection 1");
1492 Inset::row_type r1, r2;
1493 Inset::col_type c1, c2;
1494 region(i1, i2, r1, r2, c1, c2);
1497 if (i1.inset().asInsetMath()) {
1498 for (Inset::row_type row = r1; row <= r2; ++row) {
1501 for (Inset::col_type col = c1; col <= c2; ++col) {
1504 data += asString(i1.asInsetMath()->
1505 cell(i1.asInsetMath()->index(row, col)));
1509 data = from_ascii("unknown selection 2");
1515 void dirtyTabularStack(bool b)
1517 dirty_tabular_stack_ = b;
1521 bool tabularStackDirty()
1523 return dirty_tabular_stack_;