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;
80 typedef pair<DocumentClassConstPtr, AuthorList > DocInfoPair;
82 typedef limited_stack<pair<ParagraphList, DocInfoPair > > CutStack;
85 // persistent selection, cleared until the next selection
86 CutStack selectionBuffer(1);
87 // temporary scratch area
90 // store whether the tabular stack is newer than the normal copy stack
91 // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
92 // when we (hopefully) have a one-for-all paste mechanism.
93 bool dirty_tabular_stack_ = false;
96 bool checkPastePossible(int index)
98 return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
102 struct PasteReturnValue {
103 PasteReturnValue(pit_type r_pit, pos_type r_pos, bool r_nu) :
104 pit(r_pit), pos(r_pos), needupdate(r_nu)
113 /// return true if the whole ParagraphList is deleted
114 static bool isFullyDeleted(ParagraphList const & pars)
116 pit_type const pars_size = static_cast<pit_type>(pars.size());
118 // check all paragraphs
119 for (pit_type pit = 0; pit < pars_size; ++pit) {
120 if (!pars[pit].empty()) // prevent assertion failure
121 if (!pars[pit].isDeleted(0, pars[pit].size()))
128 pasteSelectionHelper(DocIterator const & cur, ParagraphList const & parlist,
129 DocumentClassConstPtr oldDocClass, cap::BranchAction branchAction,
130 ErrorList & errorlist)
132 Buffer const & buffer = *cur.buffer();
133 pit_type pit = cur.pit();
134 pos_type pos = cur.pos();
135 bool need_update = false;
138 return PasteReturnValue(pit, pos, need_update);
140 // Check whether we paste into an inset that does not
141 // produce output (needed for label duplicate check)
142 bool in_active_inset = cur.paragraph().inInset().producesOutput();
143 if (in_active_inset) {
144 for (size_type sl = 0 ; sl < cur.depth() ; ++sl) {
145 Paragraph const & outer_par = cur[sl].paragraph();
146 if (!outer_par.inInset().producesOutput()) {
147 in_active_inset = false;
153 InsetText * target_inset = cur.inset().asInsetText();
155 InsetTabular * it = cur.inset().asInsetTabular();
156 target_inset = it ? it->cell(cur.idx())->asInsetText() : nullptr;
158 LASSERT(target_inset, return PasteReturnValue(pit, pos, need_update));
160 ParagraphList & pars = target_inset->paragraphs();
161 LASSERT(pos <= pars[pit].size(),
162 return PasteReturnValue(pit, pos, need_update));
164 // Make a copy of the CaP paragraphs.
165 ParagraphList insertion = parlist;
167 // Now remove all out of the pars which is NOT allowed in the
168 // new environment and set also another font if that is required.
170 // Merge paragraphs that are to be pasted into a text inset
171 // that does not allow multiple pars.
172 InsetText * inset_text = target_inset->asInsetText();
173 if (inset_text && !inset_text->allowMultiPar()) {
174 while (insertion.size() > 1)
175 mergeParagraph(buffer.params(), insertion, 0);
178 // Convert newline to paragraph break in ParbreakIsNewline
179 if (target_inset->getLayout().parbreakIsNewline()
180 || pars[pit].layout().parbreak_is_newline) {
181 for (size_t i = 0; i != insertion.size(); ++i) {
182 for (pos_type j = 0; j != insertion[i].size(); ++j) {
183 if (insertion[i].isNewline(j)) {
184 // do not track deletion of newline
185 insertion[i].eraseChar(j, false);
186 insertion[i].setInsetOwner(target_inset);
187 breakParagraphConservative(
196 // Prevent to paste uncodable characters in verbatim and ERT.
197 // The encoding is inherited from the context here.
198 docstring uncodable_content;
199 if (target_inset->getLayout().isPassThru() && cur.getEncoding()) {
200 odocstringstream res;
201 Encoding const * e = cur.getEncoding();
202 for (size_t i = 0; i != insertion.size(); ++i) {
203 pos_type end = insertion[i].size();
204 for (pos_type j = 0; j != end; ++j) {
206 if (insertion[i].isInset(j))
208 char_type const c = insertion[i].getChar(j);
209 if (!e->encodable(c)) {
210 // do not track deletion
212 insertion[i].eraseChar(j, false);
218 docstring const uncodable = res.str();
219 if (!uncodable.empty()) {
220 if (uncodable.size() == 1)
221 uncodable_content = bformat(_("The character \"%1$s\" is uncodable in this verbatim context "
222 "and thus has not been pasted."),
225 uncodable_content = bformat(_("The characters \"%1$s\" are uncodable in this verbatim context "
226 "and thus have not been pasted."),
231 // set the paragraphs to plain layout if necessary
232 DocumentClassConstPtr newDocClass = buffer.params().documentClassPtr();
233 Layout const & plainLayout = newDocClass->plainLayout();
234 Layout const & defaultLayout = newDocClass->defaultLayout();
235 if (cur.inset().usePlainLayout()) {
236 bool forcePlainLayout = target_inset->forcePlainLayout();
237 for (auto & par : insertion) {
238 Layout const & parLayout = par.layout();
239 if (forcePlainLayout || parLayout == defaultLayout)
240 par.setLayout(plainLayout);
243 // check if we need to reset from plain layout
244 for (auto & par : insertion) {
245 Layout const & parLayout = par.layout();
246 if (parLayout == plainLayout)
247 par.setLayout(defaultLayout);
251 InsetText in(cur.buffer());
252 // Make sure there is no class difference.
253 in.paragraphs().clear();
254 // This works without copying any paragraph data because we have
255 // a specialized swap method for ParagraphList. This is important
256 // since we store pointers to insets at some places and we don't
257 // want to invalidate them.
258 insertion.swap(in.paragraphs());
259 cap::switchBetweenClasses(oldDocClass, newDocClass, in, errorlist);
260 // Do this here since switchBetweenClasses clears the errorlist
261 if (!uncodable_content.empty())
262 errorlist.push_back(ErrorItem(_("Uncodable content"), uncodable_content));
263 insertion.swap(in.paragraphs());
265 ParagraphList::iterator tmpbuf = insertion.begin();
266 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
268 depth_type max_depth = pars[pit].getMaxDepthAfter();
270 for (; tmpbuf != insertion.end(); ++tmpbuf) {
271 // If we have a negative jump so that the depth would
272 // go below 0 depth then we have to redo the delta to
273 // this new max depth level so that subsequent
274 // paragraphs are aligned correctly to this paragraph
276 if (int(tmpbuf->params().depth()) + depth_delta < 0)
279 // Set the right depth so that we are not too deep or shallow.
280 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
281 if (tmpbuf->params().depth() > max_depth)
282 tmpbuf->params().depth(max_depth);
284 // Set max_depth for the next paragraph
285 max_depth = tmpbuf->getMaxDepthAfter();
287 // Set the inset owner of this paragraph.
288 tmpbuf->setInsetOwner(target_inset);
289 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
290 // do not track deletion of invalid insets
291 if (Inset * inset = tmpbuf->getInset(i))
292 if (!target_inset->insetAllowed(inset->lyxCode()))
293 tmpbuf->eraseChar(i--, false);
297 bool const target_empty = pars[pit].empty();
298 // Use the paste content's layout, if...
299 bool const paste_layout =
300 // if target paragraph is empty
302 // ... and its layout is default
303 && (pars[pit].layout() == defaultLayout
305 || pars[pit].layout() == plainLayout
306 // ... or the paste content spans several paragraphs
307 || insertion.size() > 1))
308 // or if pasting is done at the beginning of paragraph
310 // and the paste content spans several paragraphs
311 && insertion.size() > 1);
313 // Give the first paragraph to insert the same layout as the
315 insertion.begin()->makeSameLayout(pars[pit]);
317 // Prepare the paragraphs and insets for insertion.
318 insertion.swap(in.paragraphs());
320 InsetIterator const i_end = end(in);
321 for (InsetIterator it = begin(in); it != i_end; ++it) {
322 // Even though this will also be done later, it has to be done here
323 // since some inset might try to access the buffer() member.
324 it->setBuffer(const_cast<Buffer &>(buffer));
325 switch (it->lyxCode()) {
327 case MATH_HULL_CODE: {
328 // check for equation labels and resolve duplicates
329 InsetMathHull * ins = it->asInsetMath()->asHullInset();
330 std::vector<InsetLabel *> labels = ins->getLabels();
331 for (size_t i = 0; i != labels.size(); ++i) {
334 InsetLabel * lab = labels[i];
335 docstring const oldname = lab->getParam("name");
336 lab->updateLabel(oldname, in_active_inset);
337 // We need to update the buffer reference cache.
339 docstring const newname = lab->getParam("name");
340 if (oldname == newname)
342 // adapt the references
343 for (InsetIterator itt = begin(in);
344 itt != i_end; ++itt) {
345 if (itt->lyxCode() == REF_CODE) {
346 InsetCommand * ref = itt->asInsetCommand();
347 if (ref->getParam("reference") == oldname)
348 ref->setParam("reference", newname);
349 } else if (itt->lyxCode() == MATH_REF_CODE) {
350 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
351 // this is necessary to prevent an uninitialized
352 // buffer when the RefInset is in a MathBox.
353 // FIXME audit setBuffer calls
354 mi->setBuffer(const_cast<Buffer &>(buffer));
355 if (mi->getTarget() == oldname)
356 mi->changeTarget(newname);
364 // check for duplicates
365 InsetLabel & lab = static_cast<InsetLabel &>(*it);
366 docstring const oldname = lab.getParam("name");
367 lab.updateLabel(oldname, in_active_inset);
368 // We need to update the buffer reference cache.
370 docstring const newname = lab.getParam("name");
371 if (oldname == newname)
373 // adapt the references
374 for (InsetIterator itt = begin(in); itt != i_end; ++itt) {
375 if (itt->lyxCode() == REF_CODE) {
376 InsetCommand & ref = static_cast<InsetCommand &>(*itt);
377 if (ref.getParam("reference") == oldname)
378 ref.setParam("reference", newname);
379 } else if (itt->lyxCode() == MATH_REF_CODE) {
380 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
381 // this is necessary to prevent an uninitialized
382 // buffer when the RefInset is in a MathBox.
383 // FIXME audit setBuffer calls
384 mi->setBuffer(const_cast<Buffer &>(buffer));
385 if (mi->getTarget() == oldname)
386 mi->changeTarget(newname);
393 InsetInclude & inc = static_cast<InsetInclude &>(*it);
395 // We need to update the list of included files.
401 InsetCitation & cit = static_cast<InsetCitation &>(*it);
402 // This actually only needs to be done if the cite engine
403 // differs, but we do it in general.
405 // We need to update the list of citations.
411 // check for duplicates
412 InsetBibitem & bib = static_cast<InsetBibitem &>(*it);
413 docstring const oldkey = bib.getParam("key");
414 bib.updateCommand(oldkey, false);
415 // We need to update the buffer reference cache.
417 docstring const newkey = bib.getParam("key");
418 if (oldkey == newkey)
420 // adapt the references
421 for (InsetIterator itt = begin(in);
422 itt != i_end; ++itt) {
423 if (itt->lyxCode() == CITE_CODE) {
424 InsetCommand * ref = itt->asInsetCommand();
425 if (ref->getParam("key") == oldkey)
426 ref->setParam("key", newkey);
433 // check if branch is known to target buffer
435 InsetBranch & br = static_cast<InsetBranch &>(*it);
436 docstring const name = br.branch();
439 bool const is_child = (&buffer != buffer.masterBuffer());
440 BranchList branchlist = buffer.params().branchlist();
441 if ((!is_child && branchlist.find(name))
442 || (is_child && (branchlist.find(name)
443 || buffer.masterBuffer()->params().branchlist().find(name))))
445 switch(branchAction) {
446 case cap::BRANCH_ADD: {
447 // This is for a temporary buffer, so simply create the branch.
448 // Must not use lyx::dispatch(), since tmpbuffer has no view.
450 const_cast<Buffer&>(buffer).dispatch(FuncRequest(LFUN_BRANCH_ADD, name), dr);
453 case cap::BRANCH_ASK: {
454 docstring text = bformat(
455 _("The pasted branch \"%1$s\" is undefined.\n"
456 "Do you want to add it to the document's branch list?"),
458 if (frontend::Alert::prompt(_("Unknown branch"),
459 text, 0, 1, _("&Add"), _("&Don't Add")) != 0)
461 lyx::dispatch(FuncRequest(LFUN_BRANCH_ADD, name));
464 case cap::BRANCH_IGNORE:
467 // We need to update the list of branches.
476 insertion.swap(in.paragraphs());
478 // We need to do this here, after the inset handling above,
479 // as acceptChanges() and rejectChanges() might access inset buffers.
480 tmpbuf = insertion.begin();
481 for (; tmpbuf != insertion.end(); ++tmpbuf) {
482 if (lyxrc.ct_markup_copied) {
483 // Only remove deleted text and change
484 // the rest to inserted if ct is active,
485 // otherwise leave markup as is
486 if (buffer.params().track_changes) {
487 if (tmpbuf->size() > 0) {
488 if (!isFullyDeleted(insertion))
489 tmpbuf->acceptChanges(0, tmpbuf->size());
491 tmpbuf->rejectChanges(0, tmpbuf->size());
493 tmpbuf->setChange(Change(Change::INSERTED));
496 // Resolve all markup to inserted or unchanged
497 // Deleted text has already been removed on copy
498 // (copySelectionHelper)
499 tmpbuf->setChange(Change(buffer.params().track_changes ?
500 Change::INSERTED : Change::UNCHANGED));
503 // Split the paragraph for inserting the buf if necessary.
505 breakParagraphConservative(buffer.params(), pars, pit, pos);
507 // If multiple paragraphs are inserted before the target paragraph,
508 // the cursor is now in a new paragraph before it,
509 // so use layout from paste content in that case.
510 if (pos == 0 && insertion.size() > 1)
511 pars[pit].makeSameLayout(* insertion.begin());
515 pars.insert(pars.iterator_at(pit),
516 insertion.begin(), insertion.end());
518 // merge the empty par with the last par of the insertion
519 mergeParagraph(buffer.params(), pars,
520 pit + insertion.size() - 1);
522 pars.insert(pars.iterator_at(pit + 1),
523 insertion.begin(), insertion.end());
525 // merge the first par of the insertion with the current par
526 mergeParagraph(buffer.params(), pars, pit);
529 // Store the new cursor position.
530 pit_type last_paste = pit + insertion.size() - 1;
531 pit_type startpit = pit;
533 pos = pars[last_paste].size();
535 // FIXME Should we do it here, or should we let updateBuffer() do it?
536 // Set paragraph buffers. It's important to do this right away
537 // before something calls Inset::buffer() and causes a crash.
538 for (pit_type p = startpit; p <= pit; ++p)
539 pars[p].setInsetBuffers(const_cast<Buffer &>(buffer));
541 // Join (conditionally) last pasted paragraph with next one, i.e.,
542 // the tail of the spliced document paragraph
543 if (!target_empty && last_paste + 1 != pit_type(pars.size())) {
544 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
545 mergeParagraph(buffer.params(), pars, last_paste);
546 } else if (pars[last_paste + 1].empty()) {
547 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
548 mergeParagraph(buffer.params(), pars, last_paste);
549 } else if (pars[last_paste].empty()) {
550 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
551 mergeParagraph(buffer.params(), pars, last_paste);
553 pars[last_paste + 1].stripLeadingSpaces(buffer.params().track_changes);
558 return PasteReturnValue(pit, pos, need_update);
562 PitPosPair eraseSelectionHelper(BufferParams const & params,
563 ParagraphList & pars,
564 pit_type startpit, pit_type endpit,
565 int startpos, int endpos)
567 // Start of selection is really invalid.
568 if (startpit == pit_type(pars.size()) ||
569 (startpos > pars[startpit].size()))
570 return PitPosPair(endpit, endpos);
572 // Start and end is inside same paragraph
573 if (endpit == pit_type(pars.size()) || startpit == endpit) {
574 endpos -= pars[startpit].eraseChars(startpos, endpos, params.track_changes);
575 return PitPosPair(endpit, endpos);
578 for (pit_type pit = startpit; pit != endpit + 1;) {
579 pos_type const left = (pit == startpit ? startpos : 0);
580 pos_type right = (pit == endpit ? endpos : pars[pit].size() + 1);
581 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.track_changes);
583 // Logically erase only, including the end-of-paragraph character
584 pars[pit].eraseChars(left, right, params.track_changes);
586 // Separate handling of paragraph break:
587 if (merge && pit != endpit) {
588 if (pit + 1 == endpit)
589 endpos += pars[pit].size();
590 mergeParagraph(params, pars, pit);
596 // Ensure legal cursor pos:
599 return PitPosPair(endpit, endpos);
603 Buffer * copyToTempBuffer(ParagraphList const & paragraphs, DocumentClassConstPtr docclass)
605 // This used to need to be static to avoid a memory leak. It no longer needs
606 // to be so, but the alternative is to construct a new one of these (with a
607 // new temporary directory, etc) every time, and then to destroy it. So maybe
608 // it's worth just keeping this one around.
609 static TempFile tempfile("clipboard.internal");
610 tempfile.setAutoRemove(false);
611 // The initialization of staticbuffer is thread-safe. Using a lambda
612 // guarantees that the properties are set only once.
613 static Buffer * staticbuffer = [&](){
615 theBufferList().newInternalBuffer(tempfile.name().absFileName());
617 b->inset().setBuffer(*b);
618 //initialize staticbuffer with b
621 // Use a clone for the complicated stuff so that we do not need to clean
622 // up in order to avoid a crash.
623 Buffer * buffer = staticbuffer->cloneBufferOnly();
624 LASSERT(buffer, return nullptr);
626 // This needs doing every time.
627 // Since setDocumentClass() causes deletion of the old document class
628 // we need to reset all layout pointers in paragraphs (otherwise they
629 // would be dangling).
630 ParIterator const end = buffer->par_iterator_end();
631 for (ParIterator it = buffer->par_iterator_begin(); it != end; ++it) {
632 docstring const name = it->layout().name();
633 if (docclass->hasLayout(name))
634 it->setLayout((*docclass)[name]);
636 it->setPlainOrDefaultLayout(*docclass);
638 buffer->params().setDocumentClass(docclass);
640 // we will use pasteSelectionHelper to copy the paragraphs into the
641 // temporary Buffer, since it does a lot of things to fix them up.
642 DocIterator dit = doc_iterator_begin(buffer, &buffer->inset());
644 pasteSelectionHelper(dit, paragraphs, docclass, cap::BRANCH_ADD, el);
650 void putClipboard(ParagraphList const & paragraphs,
651 DocInfoPair docinfo, docstring const & plaintext,
652 BufferParams const & bp)
654 Buffer * buffer = copyToTempBuffer(paragraphs, docinfo.first);
655 if (!buffer) // already asserted in copyToTempBuffer()
658 // We don't want to produce images that are not used. Therefore,
659 // output formulas as MathML. Even if this is not understood by all
660 // applications, the number that can parse it should go up in the future.
661 buffer->params().html_math_output = BufferParams::MathML;
663 // Copy authors to the params. We need those pointers.
664 for (Author const & a : bp.authors())
665 buffer->params().authors().record(a);
667 // Make sure MarkAsExporting is deleted before buffer is
669 // The Buffer is being used to export. This is necessary so that the
670 // updateMacros call will record the needed information.
671 MarkAsExporting mex(buffer);
673 buffer->updateBuffer(Buffer::UpdateMaster, OutputUpdate);
674 buffer->updateMacros();
675 buffer->updateMacroInstances(OutputUpdate);
680 if (buffer->write(oslyx))
684 odocstringstream oshtml;
685 OutputParams runparams(encodings.fromLyXName("utf8"));
686 // We do not need to produce images, etc.
687 runparams.dryrun = true;
688 // We are not interested in errors (bug 8866)
689 runparams.silent = true;
690 buffer->writeLyXHTMLSource(oshtml, runparams, Buffer::FullSource);
692 theClipboard().put(lyx, oshtml.str(), plaintext);
700 void copySelectionHelper(Buffer const & buf, Text const & text,
701 pit_type startpit, pit_type endpit,
702 int start, int end, DocumentClassConstPtr dc, CutStack & cutstack)
704 ParagraphList const & pars = text.paragraphs();
706 // In most of these cases, we can try to recover.
707 LASSERT(0 <= start, start = 0);
708 LASSERT(start <= pars[startpit].size(), start = pars[startpit].size());
709 LASSERT(0 <= end, end = 0);
710 LASSERT(end <= pars[endpit].size(), end = pars[endpit].size());
711 LASSERT(startpit != endpit || start <= end, return);
713 // Clone the paragraphs within the selection.
714 ParagraphList copy_pars(pars.iterator_at(startpit),
715 pars.iterator_at(endpit + 1));
717 // Remove the end of the last paragraph; afterwards, remove the
718 // beginning of the first paragraph. Keep this order - there may only
719 // be one paragraph! Do not track deletions here; this is an internal
720 // action not visible to the user
722 Paragraph & back = copy_pars.back();
723 back.eraseChars(end, back.size(), false);
724 Paragraph & front = copy_pars.front();
725 front.eraseChars(0, start, false);
727 for (auto & par : copy_pars) {
728 // Since we have a copy of the paragraphs, the insets
729 // do not have a proper buffer reference. It makes
730 // sense to add them temporarily, because the
731 // operations below depend on that (acceptChanges included).
732 par.setInsetBuffers(const_cast<Buffer &>(buf));
733 // PassThru paragraphs have the Language
734 // latex_language. This is invalid for others, so we
735 // need to change it to the buffer language.
736 if (par.isPassThru())
737 par.changeLanguage(buf.params(),
738 latex_language, buf.language());
741 // do not copy text (also nested in insets) which is marked as
742 // deleted, unless the whole selection was deleted
743 if (!lyxrc.ct_markup_copied) {
744 if (!isFullyDeleted(copy_pars))
745 acceptChanges(copy_pars, buf.params());
747 rejectChanges(copy_pars, buf.params());
751 // do some final cleanup now, to make sure that the paragraphs
752 // are not linked to something else.
753 for (auto & par : copy_pars) {
755 par.setInsetOwner(nullptr);
758 cutstack.push(make_pair(copy_pars, make_pair(dc, buf.params().authors())));
766 void region(CursorSlice const & i1, CursorSlice const & i2,
767 row_type & r1, row_type & r2,
768 col_type & c1, col_type & c2)
770 Inset const & p = i1.inset();
771 c1 = p.col(i1.idx());
772 c2 = p.col(i2.idx());
775 r1 = p.row(i1.idx());
776 r2 = p.row(i2.idx());
782 docstring grabAndEraseSelection(Cursor & cur)
784 if (!cur.selection())
786 docstring res = grabSelection(cur);
792 bool reduceSelectionToOneCell(CursorData & cur)
794 if (!cur.selection() || !cur.inMathed())
797 CursorSlice i1 = cur.selBegin();
798 CursorSlice i2 = cur.selEnd();
799 if (!i1.inset().asInsetMath())
802 // the easy case: do nothing if only one cell is selected
803 if (i1.idx() == i2.idx())
808 cur.top().pos() = cur.top().lastpos();
814 bool multipleCellsSelected(CursorData const & cur)
816 if (!cur.selection() || !cur.inMathed())
819 CursorSlice i1 = cur.selBegin();
820 CursorSlice i2 = cur.selEnd();
821 if (!i1.inset().asInsetMath())
824 if (i1.idx() == i2.idx())
831 void switchBetweenClasses(DocumentClassConstPtr oldone,
832 DocumentClassConstPtr newone, InsetText & in) {
834 switchBetweenClasses(oldone, newone, in, el);
838 void switchBetweenClasses(DocumentClassConstPtr oldone,
839 DocumentClassConstPtr newone, InsetText & in, ErrorList & errorlist)
843 LBUFERR(!in.paragraphs().empty());
844 if (oldone == newone)
847 DocumentClass const & oldtc = *oldone;
848 DocumentClass const & newtc = *newone;
851 ParIterator it = par_iterator_begin(in);
852 ParIterator pend = par_iterator_end(in);
853 // for remembering which layouts we've had to add
854 set<docstring> newlayouts;
855 for (; it != pend; ++it) {
856 docstring const name = it->layout().name();
858 // the pasted text will keep their own layout name. If this layout does
859 // not exist in the new document, it will behave like a standard layout.
860 bool const added_one = newtc.addLayoutIfNeeded(name);
862 newlayouts.insert(name);
864 if (added_one || newlayouts.find(name) != newlayouts.end()) {
866 docstring const s = bformat(_("Layout `%1$s' was not found."), name);
867 errorlist.push_back(ErrorItem(_("Layout Not Found"), s,
868 {it->id(), 0}, {it->id(), -1}));
871 if (in.usePlainLayout())
872 it->setLayout(newtc.plainLayout());
874 it->setLayout(newtc[name]);
877 // character styles and hidden table cells
878 InsetIterator const i_end = end(in);
879 for (InsetIterator iit = begin(in); iit != i_end; ++iit) {
880 InsetCode const code = iit->lyxCode();
881 if (code == FLEX_CODE) {
882 // FIXME: Should we verify all InsetCollapsible?
883 docstring const layoutName = iit->layoutName();
884 docstring const & n = newone->insetLayout(layoutName).name();
885 bool const is_undefined = n.empty() ||
886 n == InsetLayout::undefined().name();
887 docstring const & oldn = oldone->insetLayout(layoutName).name();
888 bool const was_undefined = oldn.empty() ||
889 oldn == InsetLayout::undefined().name();
890 if (!is_undefined || was_undefined)
893 // The flex inset is undefined in newtc
894 docstring const oldname = from_utf8(oldtc.name());
895 docstring const newname = from_utf8(newtc.name());
897 if (oldname == newname)
898 s = bformat(_("Flex inset %1$s is undefined after "
899 "reloading `%2$s' layout."), layoutName, oldname);
901 s = bformat(_("Flex inset %1$s is undefined because of "
902 "conversion from `%2$s' layout to `%3$s'."),
903 layoutName, oldname, newname);
904 // To warn the user that something had to be done.
905 errorlist.push_back(ErrorItem(
906 _("Undefined flex inset"), s,
907 {iit.paragraph().id(), iit.pos()},
908 {iit.paragraph().id(), iit.pos() + 1}));
909 } else if (code == TABULAR_CODE) {
910 // The recursion above does not catch paragraphs in "hidden" cells,
911 // i.e., ones that are part of a multirow or multicolum. So we need
912 // to handle those separately.
913 // This is the cause of bug #9049.
914 InsetTabular * table = iit->asInsetTabular();
915 table->setLayoutForHiddenCells(newtc);
921 vector<docstring> availableSelections(Buffer const * buf)
923 vector<docstring> selList;
927 for (auto const & cut : theCuts) {
928 ParagraphList const & pars = cut.first;
930 for (auto const & para : pars) {
931 Paragraph par(para, 0, 46);
932 // adapt paragraph to current buffer.
933 par.setInsetBuffers(const_cast<Buffer &>(*buf));
934 textSel += par.asString(AS_STR_INSETS);
935 if (textSel.size() > 45) {
936 support::truncateWithEllipsis(textSel,45);
940 selList.push_back(textSel);
947 size_type numberOfSelections()
949 return theCuts.size();
954 void cutSelectionHelper(Cursor & cur, CutStack & cuts, bool realcut, bool putclip)
956 // This doesn't make sense, if there is no selection
957 if (!cur.selection())
960 // OK, we have a selection. This is always between cur.selBegin()
963 if (cur.inTexted()) {
964 Text * text = cur.text();
969 // make sure that the depth behind the selection are restored, too
970 cur.recordUndoSelection();
971 pit_type begpit = cur.selBegin().pit();
972 pit_type endpit = cur.selEnd().pit();
974 int endpos = cur.selEnd().pos();
976 BufferParams const & bp = cur.buffer()->params();
978 copySelectionHelper(*cur.buffer(),
981 cur.selBegin().pos(), endpos,
982 bp.documentClassPtr(), cuts);
983 // Stuff what we got on the clipboard.
984 // Even if there is no selection.
986 putClipboard(cuts[0].first, cuts[0].second,
987 cur.selectionAsString(true, true), bp);
990 if (begpit != endpit)
991 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
993 cur.screenUpdateFlags(Update::SinglePar | Update::FitCursor);
995 tie(endpit, endpos) =
996 eraseSelectionHelper(bp, text->paragraphs(), begpit, endpit,
997 cur.selBegin().pos(), endpos);
999 // cutSelection can invalidate the cursor so we need to set
1001 // we prefer the end for when tracking changes
1005 // need a valid cursor. (Lgb)
1006 cur.clearSelection();
1008 // After a cut operation, we must make sure that the Buffer is updated
1009 // because some further operation might need updated label information for
1010 // example. So we cannot just use "cur.forceBufferUpdate()" here.
1011 // This fixes #7071.
1012 cur.buffer()->updateBuffer();
1014 // tell tabular that a recent copy happened
1015 dirtyTabularStack(false);
1018 if (cur.inMathed()) {
1019 if (cur.selBegin().idx() != cur.selEnd().idx()) {
1020 // The current selection spans more than one cell.
1022 cur.recordUndoInset();
1024 // Record only the current cell to avoid a jumping
1025 // cursor after undo
1030 eraseSelection(cur);
1036 void cutSelection(Cursor & cur, bool realcut)
1038 cutSelectionHelper(cur, theCuts, realcut, true);
1042 void cutSelectionToTemp(Cursor & cur, bool realcut)
1044 cutSelectionHelper(cur, tempCut, realcut, false);
1048 void copySelection(Cursor const & cur)
1050 copySelection(cur, cur.selectionAsString(true, true));
1056 void copyInsetToStack(Cursor const & cur, CutStack & cutstack, Inset * inset)
1060 BufferParams const & bp = cur.buffer()->params();
1061 par.setLayout(bp.documentClass().plainLayout());
1062 Font font(inherit_font, bp.language);
1063 par.insertInset(0, inset, font, Change(Change::UNCHANGED));
1064 pars.push_back(par);
1065 cutstack.push(make_pair(pars, make_pair(bp.documentClassPtr(), bp.authors())));
1071 void copyInset(Cursor const & cur, Inset * inset, docstring const & plaintext)
1073 copyInsetToStack(cur, theCuts, inset);
1075 // stuff the selection onto the X clipboard, from an explicit copy request
1076 BufferParams const & bp = cur.buffer()->params();
1077 putClipboard(theCuts[0].first, theCuts[0].second, plaintext, bp);
1081 void copyInsetToTemp(Cursor const & cur, Inset * inset)
1083 copyInsetToStack(cur, tempCut, inset);
1089 void copySelectionToStack(CursorData const & cur, CutStack & cutstack)
1091 // this doesn't make sense, if there is no selection
1092 if (!cur.selection())
1095 // copySelection can not yet handle the case of cross idx selection
1096 if (cur.selBegin().idx() != cur.selEnd().idx())
1099 if (cur.inTexted()) {
1100 Text * text = cur.text();
1102 // ok we have a selection. This is always between cur.selBegin()
1103 // and sel_end cursor
1104 copySelectionHelper(*cur.buffer(), *text,
1105 cur.selBegin().pit(), cur.selEnd().pit(),
1106 cur.selBegin().pos(), cur.selEnd().pos(),
1107 cur.buffer()->params().documentClassPtr(),
1109 // Reset the dirty_tabular_stack_ flag only when something
1110 // is copied to the clipboard (not to the selectionBuffer).
1111 if (&cutstack == &theCuts)
1112 dirtyTabularStack(false);
1115 if (cur.inMathed()) {
1116 //lyxerr << "copySelection in mathed" << endl;
1119 BufferParams const & bp = cur.buffer()->params();
1120 // FIXME This should be the plain layout...right?
1121 par.setLayout(bp.documentClass().plainLayout());
1122 // For pasting into text, we set the language to the paragraph language
1123 // (rather than the default_language which is always English; see #2596)
1124 par.insert(0, grabSelection(cur), Font(sane_font, par.getParLanguage(bp)),
1125 Change(Change::UNCHANGED));
1126 pars.push_back(par);
1127 cutstack.push(make_pair(pars, make_pair(bp.documentClassPtr(), bp.authors())));
1134 void copySelectionToStack()
1136 if (!selectionBuffer.empty())
1137 theCuts.push(selectionBuffer[0]);
1141 void copySelectionToTemp(Cursor const & cur)
1143 copySelectionToStack(cur, tempCut);
1147 void copySelection(Cursor const & cur, docstring const & plaintext)
1149 // In tablemode, because copy and paste actually use a special table stack,
1150 // we need to go through the cells and collect the paragraphs.
1151 // In math matrices, we generate a plain text version.
1152 if (cur.selBegin().idx() != cur.selEnd().idx()) {
1154 BufferParams const & bp = cur.buffer()->params();
1155 if (cur.inMathed()) {
1157 par.setLayout(bp.documentClass().plainLayout());
1158 // Replace (column-separating) tabs by space (#4449)
1159 docstring const clean_text = subst(plaintext, '\t', ' ');
1160 // For pasting into text, we set the language to the paragraph language
1161 // (rather than the default_language which is always English; see #11898)
1162 par.insert(0, clean_text, Font(sane_font, par.getParLanguage(bp)),
1163 Change(Change::UNCHANGED));
1164 pars.push_back(par);
1166 // Get paragraphs from all cells
1167 InsetTabular * table = cur.inset().asInsetTabular();
1168 LASSERT(table, return);
1169 ParagraphList tplist = table->asParList(cur.selBegin().idx(), cur.selEnd().idx());
1170 for (auto & cpar : tplist) {
1171 cpar.setLayout(bp.documentClass().plainLayout());
1172 pars.push_back(cpar);
1173 // since the pars are merged later, we separate them by blank
1175 epar.insert(0, from_ascii(" "), Font(sane_font, epar.getParLanguage(bp)),
1176 Change(Change::UNCHANGED));
1177 pars.push_back(epar);
1179 // remove last empty par
1181 // merge all paragraphs to one
1182 while (pars.size() > 1)
1183 mergeParagraph(bp, pars, 0);
1185 theCuts.push(make_pair(pars, make_pair(bp.documentClassPtr(), bp.authors())));
1187 copySelectionToStack(cur, theCuts);
1190 // stuff the selection onto the X clipboard, from an explicit copy request
1191 putClipboard(theCuts[0].first, theCuts[0].second, plaintext,
1192 cur.buffer()->params());
1196 void saveSelection(Cursor const & cur)
1198 // This function is called, not when a selection is formed, but when
1199 // a selection is cleared. Therefore, multiple keyboard selection
1200 // will not repeatively trigger this function (bug 3877).
1202 && cur.selBegin() == cur.bv().cursor().selBegin()
1203 && cur.selEnd() == cur.bv().cursor().selEnd()) {
1204 LYXERR(Debug::SELECTION, "saveSelection: '" << cur.selectionAsString(true, true) << "'");
1205 copySelectionToStack(cur, selectionBuffer);
1212 return !selectionBuffer.empty();
1216 void clearSelection()
1218 selectionBuffer.clear();
1222 void clearCutStack()
1229 docstring selection(size_t sel_index, DocInfoPair docinfo, bool for_math)
1231 if (sel_index >= theCuts.size())
1234 unique_ptr<Buffer> buffer(copyToTempBuffer(theCuts[sel_index].first,
1239 int options = AS_STR_INSETS | AS_STR_NEWLINES;
1241 options |= AS_STR_MATHED;
1243 return buffer->paragraphs().back().asString(options);
1247 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
1248 DocumentClassConstPtr docclass, AuthorList const & authors,
1249 ErrorList & errorList,
1250 cap::BranchAction branchAction)
1252 // Copy authors to the params. We need those pointers.
1253 for (Author const & a : authors)
1254 cur.buffer()->params().authors().record(a);
1256 if (cur.inTexted()) {
1257 Text * text = cur.text();
1260 PasteReturnValue prv =
1261 pasteSelectionHelper(cur, parlist, docclass, branchAction, errorList);
1262 cur.forceBufferUpdate();
1263 cur.clearSelection();
1264 text->setCursor(cur, prv.pit, prv.pos);
1267 // mathed is handled in InsetMathNest/InsetMathGrid
1268 LATTEST(!cur.inMathed());
1272 bool pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
1274 // this does not make sense, if there is nothing to paste
1275 if (!checkPastePossible(sel_index))
1279 pasteParagraphList(cur, theCuts[sel_index].first,
1280 theCuts[sel_index].second.first, theCuts[sel_index].second.second,
1281 errorList, BRANCH_ASK);
1286 bool pasteFromTemp(Cursor & cur, ErrorList & errorList)
1288 // this does not make sense, if there is nothing to paste
1289 if (tempCut.empty() || tempCut[0].first.empty())
1293 pasteParagraphList(cur, tempCut[0].first,
1294 tempCut[0].second.first, tempCut[0].second.second,
1295 errorList, BRANCH_IGNORE);
1300 bool pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs,
1301 Clipboard::TextType type)
1303 // Use internal clipboard if it is the most recent one
1304 // This overrides asParagraphs and type on purpose!
1305 if (theClipboard().isInternal())
1306 return pasteFromStack(cur, errorList, 0);
1308 // First try LyX format
1309 if ((type == Clipboard::LyXTextType ||
1310 type == Clipboard::LyXOrPlainTextType ||
1311 type == Clipboard::AnyTextType) &&
1312 theClipboard().hasTextContents(Clipboard::LyXTextType)) {
1313 string lyx = theClipboard().getAsLyX();
1315 Buffer buffer(string(), false);
1316 buffer.setInternal(true);
1317 buffer.setUnnamed(true);
1318 if (buffer.readString(lyx)) {
1320 pasteParagraphList(cur, buffer.paragraphs(),
1321 buffer.params().documentClassPtr(),
1322 buffer.params().authors(),
1329 // Then try TeX and HTML
1330 Clipboard::TextType types[2] = {Clipboard::HtmlTextType, Clipboard::LaTeXTextType};
1331 string names[2] = {"html", "latexclipboard"};
1332 for (int i = 0; i < 2; ++i) {
1333 if (type != types[i] && type != Clipboard::AnyTextType)
1335 bool available = theClipboard().hasTextContents(types[i]);
1337 // If a specific type was explicitly requested, try to
1338 // interpret plain text: The user told us that the clipboard
1339 // contents is in the desired format
1340 if (!available && type == types[i]) {
1341 types[i] = Clipboard::PlainTextType;
1342 available = theClipboard().hasTextContents(types[i]);
1346 docstring text = theClipboard().getAsText(types[i]);
1347 available = !text.empty();
1349 Buffer buffer(string(), false);
1350 buffer.setInternal(true);
1351 buffer.setUnnamed(true);
1352 buffer.params() = cur.buffer()->params();
1353 available = buffer.importString(names[i], text, errorList);
1355 available = !buffer.paragraphs().empty();
1356 if (available && !buffer.paragraphs()[0].empty()) {
1357 // TeX2lyx (also used in the HTML chain) assumes English as document language
1358 // if no language is explicitly set (as is the case here).
1359 // We thus reset the temp buffer's language to the context language
1360 buffer.changeLanguage(buffer.language(), cur.getFont().language());
1362 pasteParagraphList(cur, buffer.paragraphs(),
1363 buffer.params().documentClassPtr(),
1364 buffer.params().authors(),
1372 // Then try plain text
1373 docstring const text = theClipboard().getAsText(Clipboard::PlainTextType);
1378 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1380 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1381 cur.forceBufferUpdate();
1386 void pasteSimpleText(Cursor & cur, bool asParagraphs)
1389 // Use internal clipboard if it is the most recent one
1390 if (theClipboard().isInternal()) {
1391 if (!checkPastePossible(0))
1394 ParagraphList const & pars = theCuts[0].first;
1395 ParagraphList::const_iterator it = pars.begin();
1396 for (; it != pars.end(); ++it) {
1397 if (it != pars.begin())
1399 text += (*it).asString();
1401 asParagraphs = false;
1403 // Then try plain text
1404 text = theClipboard().getAsText(Clipboard::PlainTextType);
1411 cutSelection(cur, false);
1413 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1415 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1419 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
1420 Clipboard::GraphicsType preferedType)
1422 LASSERT(theClipboard().hasGraphicsContents(preferedType), return);
1424 // get picture from clipboard
1425 FileName filename = theClipboard().getAsGraphics(cur, preferedType);
1426 if (filename.empty())
1429 // create inset for graphic
1430 InsetGraphics * inset = new InsetGraphics(cur.buffer());
1431 InsetGraphicsParams params;
1432 params.filename = support::DocFileName(filename.absFileName(), false);
1433 inset->setParams(params);
1439 void pasteSelection(Cursor & cur, ErrorList & errorList)
1441 if (selectionBuffer.empty())
1444 pasteParagraphList(cur, selectionBuffer[0].first,
1445 selectionBuffer[0].second.first,
1446 selectionBuffer[0].second.second,
1451 void replaceSelectionWithString(Cursor & cur, docstring const & str)
1454 DocIterator selbeg = cur.selectionBegin();
1456 // Get font setting before we cut, we need a copy here, not a bare reference.
1458 selbeg.paragraph().getFontSettings(cur.buffer()->params(), selbeg.pos());
1460 // Insert the new string
1461 pos_type pos = cur.selEnd().pos();
1462 Paragraph & par = cur.selEnd().paragraph();
1463 for (auto const & c : str) {
1464 par.insertChar(pos, c, font, cur.buffer()->params().track_changes);
1468 // Cut the selection
1469 cutSelection(cur, false);
1473 void replaceSelection(Cursor & cur)
1475 if (cur.selection())
1476 cutSelection(cur, false);
1480 void eraseSelection(Cursor & cur)
1482 //lyxerr << "cap::eraseSelection begin: " << cur << endl;
1483 CursorSlice const & i1 = cur.selBegin();
1484 CursorSlice const & i2 = cur.selEnd();
1485 if (!i1.asInsetMath()) {
1486 LYXERR0("Can't erase this selection");
1492 InsetMath * p = i1.asInsetMath();
1493 if (i1.idx() == i2.idx()) {
1494 i1.cell().erase(i1.pos(), i2.pos());
1495 // We may have deleted i1.cell(cur.pos()).
1496 // Make sure that pos is valid.
1497 if (cur.pos() > cur.lastpos())
1498 cur.pos() = cur.lastpos();
1499 } else if (p->nrows() > 0 && p->ncols() > 0) {
1500 // This is a grid, delete a nice square region
1503 region(i1, i2, r1, r2, c1, c2);
1504 for (row_type row = r1; row <= r2; ++row)
1505 for (col_type col = c1; col <= c2; ++col)
1506 p->cell(p->index(row, col)).clear();
1507 // We've deleted the whole cell. Only pos 0 is valid.
1510 idx_type idx1 = i1.idx();
1511 idx_type idx2 = i2.idx();
1514 for (idx_type idx = idx1 ; idx <= idx2; ++idx)
1515 p->cell(idx).clear();
1516 // We've deleted the whole cell. Only pos 0 is valid.
1520 // need a valid cursor. (Lgb)
1521 cur.clearSelection();
1522 //lyxerr << "cap::eraseSelection end: " << cur << endl;
1526 void selDel(Cursor & cur)
1528 //lyxerr << "cap::selDel" << endl;
1529 if (cur.selection())
1530 eraseSelection(cur);
1534 void selClearOrDel(Cursor & cur)
1536 //lyxerr << "cap::selClearOrDel" << endl;
1537 if (lyxrc.auto_region_delete)
1540 cur.selection(false);
1544 docstring grabSelection(CursorData const & cur)
1546 if (!cur.selection())
1550 // grab selection by glueing multiple cells together. This is not what
1551 // we want because selections spanning multiple cells will get "&" and "\\"
1554 for (DocIterator dit = cur.selectionBegin();
1555 dit != cur.selectionEnd(); dit.forwardPos())
1556 os << asString(dit.cell());
1560 CursorSlice i1 = cur.selBegin();
1561 CursorSlice i2 = cur.selEnd();
1563 if (i1.idx() == i2.idx()) {
1564 if (i1.inset().asInsetMath()) {
1565 MathData::const_iterator it = i1.cell().begin();
1566 Buffer * buf = cur.buffer();
1567 return asString(MathData(buf, it + i1.pos(), it + i2.pos()));
1569 return from_ascii("unknown selection 1");
1575 region(i1, i2, r1, r2, c1, c2);
1578 if (i1.inset().asInsetMath()) {
1579 for (row_type row = r1; row <= r2; ++row) {
1582 for (col_type col = c1; col <= c2; ++col) {
1585 data += asString(i1.asInsetMath()->
1586 cell(i1.asInsetMath()->index(row, col)));
1590 data = from_ascii("unknown selection 2");
1596 void dirtyTabularStack(bool b)
1598 dirty_tabular_stack_ = b;
1602 bool tabularStackDirty()
1604 return dirty_tabular_stack_;