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 pasteSelectionHelper(DocIterator const & cur, ParagraphList const & parlist,
114 DocumentClassConstPtr oldDocClass, cap::BranchAction branchAction,
115 ErrorList & errorlist)
117 Buffer const & buffer = *cur.buffer();
118 pit_type pit = cur.pit();
119 pos_type pos = cur.pos();
120 bool need_update = false;
123 return PasteReturnValue(pit, pos, need_update);
125 // Check whether we paste into an inset that does not
126 // produce output (needed for label duplicate check)
127 bool in_active_inset = cur.paragraph().inInset().producesOutput();
128 if (in_active_inset) {
129 for (size_type sl = 0 ; sl < cur.depth() ; ++sl) {
130 Paragraph const & outer_par = cur[sl].paragraph();
131 if (!outer_par.inInset().producesOutput()) {
132 in_active_inset = false;
138 InsetText * target_inset = cur.inset().asInsetText();
140 InsetTabular * it = cur.inset().asInsetTabular();
141 target_inset = it ? it->cell(cur.idx())->asInsetText() : nullptr;
143 LASSERT(target_inset, return PasteReturnValue(pit, pos, need_update));
145 ParagraphList & pars = target_inset->paragraphs();
146 LASSERT(pos <= pars[pit].size(),
147 return PasteReturnValue(pit, pos, need_update));
149 // Make a copy of the CaP paragraphs.
150 ParagraphList insertion = parlist;
152 // Now remove all out of the pars which is NOT allowed in the
153 // new environment and set also another font if that is required.
155 // Merge paragraphs that are to be pasted into a text inset
156 // that does not allow multiple pars.
157 InsetText * inset_text = target_inset->asInsetText();
158 if (inset_text && !inset_text->allowMultiPar()) {
159 while (insertion.size() > 1)
160 mergeParagraph(buffer.params(), insertion, 0);
163 // Convert newline to paragraph break in ParbreakIsNewline
164 if (target_inset->getLayout().parbreakIsNewline()
165 || pars[pit].layout().parbreak_is_newline) {
166 for (size_t i = 0; i != insertion.size(); ++i) {
167 for (pos_type j = 0; j != insertion[i].size(); ++j) {
168 if (insertion[i].isNewline(j)) {
169 // do not track deletion of newline
170 insertion[i].eraseChar(j, false);
171 insertion[i].setInsetOwner(target_inset);
172 breakParagraphConservative(
181 // Prevent to paste uncodable characters in verbatim and ERT.
182 // The encoding is inherited from the context here.
183 docstring uncodable_content;
184 if (target_inset->getLayout().isPassThru() && cur.getEncoding()) {
185 odocstringstream res;
186 Encoding const * e = cur.getEncoding();
187 for (size_t i = 0; i != insertion.size(); ++i) {
188 pos_type end = insertion[i].size();
189 for (pos_type j = 0; j != end; ++j) {
191 if (insertion[i].isInset(j))
193 char_type const c = insertion[i].getChar(j);
194 if (!e->encodable(c)) {
195 // do not track deletion
197 insertion[i].eraseChar(j, false);
203 docstring const uncodable = res.str();
204 if (!uncodable.empty()) {
205 if (uncodable.size() == 1)
206 uncodable_content = bformat(_("The character \"%1$s\" is uncodable in this verbatim context "
207 "and thus has not been pasted."),
210 uncodable_content = bformat(_("The characters \"%1$s\" are uncodable in this verbatim context "
211 "and thus have not been pasted."),
216 // set the paragraphs to plain layout if necessary
217 DocumentClassConstPtr newDocClass = buffer.params().documentClassPtr();
218 Layout const & plainLayout = newDocClass->plainLayout();
219 Layout const & defaultLayout = newDocClass->defaultLayout();
220 if (cur.inset().usePlainLayout()) {
221 bool forcePlainLayout = target_inset->forcePlainLayout();
222 for (auto & par : insertion) {
223 Layout const & parLayout = par.layout();
224 if (forcePlainLayout || parLayout == defaultLayout)
225 par.setLayout(plainLayout);
228 // check if we need to reset from plain layout
229 for (auto & par : insertion) {
230 Layout const & parLayout = par.layout();
231 if (parLayout == plainLayout)
232 par.setLayout(defaultLayout);
236 InsetText in(cur.buffer());
237 // Make sure there is no class difference.
238 in.paragraphs().clear();
239 // This works without copying any paragraph data because we have
240 // a specialized swap method for ParagraphList. This is important
241 // since we store pointers to insets at some places and we don't
242 // want to invalidate them.
243 insertion.swap(in.paragraphs());
244 cap::switchBetweenClasses(oldDocClass, newDocClass, in, errorlist);
245 // Do this here since switchBetweenClasses clears the errorlist
246 if (!uncodable_content.empty())
247 errorlist.push_back(ErrorItem(_("Uncodable content"), uncodable_content));
248 insertion.swap(in.paragraphs());
250 ParagraphList::iterator tmpbuf = insertion.begin();
251 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
253 depth_type max_depth = pars[pit].getMaxDepthAfter();
255 for (; tmpbuf != insertion.end(); ++tmpbuf) {
256 // If we have a negative jump so that the depth would
257 // go below 0 depth then we have to redo the delta to
258 // this new max depth level so that subsequent
259 // paragraphs are aligned correctly to this paragraph
261 if (int(tmpbuf->params().depth()) + depth_delta < 0)
264 // Set the right depth so that we are not too deep or shallow.
265 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
266 if (tmpbuf->params().depth() > max_depth)
267 tmpbuf->params().depth(max_depth);
269 // Set max_depth for the next paragraph
270 max_depth = tmpbuf->getMaxDepthAfter();
272 // Set the inset owner of this paragraph.
273 tmpbuf->setInsetOwner(target_inset);
274 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
275 // do not track deletion of invalid insets
276 if (Inset * inset = tmpbuf->getInset(i))
277 if (!target_inset->insetAllowed(inset->lyxCode()))
278 tmpbuf->eraseChar(i--, false);
281 if (lyxrc.ct_markup_copied) {
282 // Only change to inserted if ct is active,
283 // otherwise leave markup as is
284 if (buffer.params().track_changes)
285 tmpbuf->setChange(Change(Change::INSERTED));
287 // Resolve all markup to inserted or unchanged
288 tmpbuf->setChange(Change(buffer.params().track_changes ?
289 Change::INSERTED : Change::UNCHANGED));
292 bool const empty = pars[pit].empty();
294 // Make the buf exactly the same layout as the cursor
296 insertion.begin()->makeSameLayout(pars[pit]);
299 // Prepare the paragraphs and insets for insertion.
300 insertion.swap(in.paragraphs());
302 InsetIterator const i_end = end(in);
303 for (InsetIterator it = begin(in); it != i_end; ++it) {
304 // Even though this will also be done later, it has to be done here
305 // since some inset might try to access the buffer() member.
306 it->setBuffer(const_cast<Buffer &>(buffer));
307 switch (it->lyxCode()) {
309 case MATH_HULL_CODE: {
310 // check for equation labels and resolve duplicates
311 InsetMathHull * ins = it->asInsetMath()->asHullInset();
312 std::vector<InsetLabel *> labels = ins->getLabels();
313 for (size_t i = 0; i != labels.size(); ++i) {
316 InsetLabel * lab = labels[i];
317 docstring const oldname = lab->getParam("name");
318 lab->updateLabel(oldname, in_active_inset);
319 // We need to update the buffer reference cache.
321 docstring const newname = lab->getParam("name");
322 if (oldname == newname)
324 // adapt the references
325 for (InsetIterator itt = begin(in);
326 itt != i_end; ++itt) {
327 if (itt->lyxCode() == REF_CODE) {
328 InsetCommand * ref = itt->asInsetCommand();
329 if (ref->getParam("reference") == oldname)
330 ref->setParam("reference", newname);
331 } else if (itt->lyxCode() == MATH_REF_CODE) {
332 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
333 // this is necessary to prevent an uninitialized
334 // buffer when the RefInset is in a MathBox.
335 // FIXME audit setBuffer calls
336 mi->setBuffer(const_cast<Buffer &>(buffer));
337 if (mi->getTarget() == oldname)
338 mi->changeTarget(newname);
346 // check for duplicates
347 InsetLabel & lab = static_cast<InsetLabel &>(*it);
348 docstring const oldname = lab.getParam("name");
349 lab.updateLabel(oldname, in_active_inset);
350 // We need to update the buffer reference cache.
352 docstring const newname = lab.getParam("name");
353 if (oldname == newname)
355 // adapt the references
356 for (InsetIterator itt = begin(in); itt != i_end; ++itt) {
357 if (itt->lyxCode() == REF_CODE) {
358 InsetCommand & ref = static_cast<InsetCommand &>(*itt);
359 if (ref.getParam("reference") == oldname)
360 ref.setParam("reference", newname);
361 } else if (itt->lyxCode() == MATH_REF_CODE) {
362 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
363 // this is necessary to prevent an uninitialized
364 // buffer when the RefInset is in a MathBox.
365 // FIXME audit setBuffer calls
366 mi->setBuffer(const_cast<Buffer &>(buffer));
367 if (mi->getTarget() == oldname)
368 mi->changeTarget(newname);
375 InsetInclude & inc = static_cast<InsetInclude &>(*it);
377 // We need to update the list of included files.
383 InsetCitation & cit = static_cast<InsetCitation &>(*it);
384 // This actually only needs to be done if the cite engine
385 // differs, but we do it in general.
387 // We need to update the list of citations.
393 // check for duplicates
394 InsetBibitem & bib = static_cast<InsetBibitem &>(*it);
395 docstring const oldkey = bib.getParam("key");
396 bib.updateCommand(oldkey, false);
397 // We need to update the buffer reference cache.
399 docstring const newkey = bib.getParam("key");
400 if (oldkey == newkey)
402 // adapt the references
403 for (InsetIterator itt = begin(in);
404 itt != i_end; ++itt) {
405 if (itt->lyxCode() == CITE_CODE) {
406 InsetCommand * ref = itt->asInsetCommand();
407 if (ref->getParam("key") == oldkey)
408 ref->setParam("key", newkey);
415 // check if branch is known to target buffer
417 InsetBranch & br = static_cast<InsetBranch &>(*it);
418 docstring const name = br.branch();
421 bool const is_child = (&buffer != buffer.masterBuffer());
422 BranchList branchlist = buffer.params().branchlist();
423 if ((!is_child && branchlist.find(name))
424 || (is_child && (branchlist.find(name)
425 || buffer.masterBuffer()->params().branchlist().find(name))))
427 switch(branchAction) {
428 case cap::BRANCH_ADD: {
429 // This is for a temporary buffer, so simply create the branch.
430 // Must not use lyx::dispatch(), since tmpbuffer has no view.
432 const_cast<Buffer&>(buffer).dispatch(FuncRequest(LFUN_BRANCH_ADD, name), dr);
435 case cap::BRANCH_ASK: {
436 docstring text = bformat(
437 _("The pasted branch \"%1$s\" is undefined.\n"
438 "Do you want to add it to the document's branch list?"),
440 if (frontend::Alert::prompt(_("Unknown branch"),
441 text, 0, 1, _("&Add"), _("&Don't Add")) != 0)
443 lyx::dispatch(FuncRequest(LFUN_BRANCH_ADD, name));
446 case cap::BRANCH_IGNORE:
449 // We need to update the list of branches.
458 insertion.swap(in.paragraphs());
460 // Split the paragraph for inserting the buf if necessary.
462 breakParagraphConservative(buffer.params(), pars, pit, pos);
466 pars.insert(pars.iterator_at(pit),
467 insertion.begin(), insertion.end());
469 // merge the empty par with the last par of the insertion
470 mergeParagraph(buffer.params(), pars,
471 pit + insertion.size() - 1);
473 pars.insert(pars.iterator_at(pit + 1),
474 insertion.begin(), insertion.end());
476 // merge the first par of the insertion with the current par
477 mergeParagraph(buffer.params(), pars, pit);
480 // Store the new cursor position.
481 pit_type last_paste = pit + insertion.size() - 1;
482 pit_type startpit = pit;
484 pos = pars[last_paste].size();
486 // FIXME Should we do it here, or should we let updateBuffer() do it?
487 // Set paragraph buffers. It's important to do this right away
488 // before something calls Inset::buffer() and causes a crash.
489 for (pit_type p = startpit; p <= pit; ++p)
490 pars[p].setInsetBuffers(const_cast<Buffer &>(buffer));
492 // Join (conditionally) last pasted paragraph with next one, i.e.,
493 // the tail of the spliced document paragraph
494 if (!empty && last_paste + 1 != pit_type(pars.size())) {
495 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
496 mergeParagraph(buffer.params(), pars, last_paste);
497 } else if (pars[last_paste + 1].empty()) {
498 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
499 mergeParagraph(buffer.params(), pars, last_paste);
500 } else if (pars[last_paste].empty()) {
501 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
502 mergeParagraph(buffer.params(), pars, last_paste);
504 pars[last_paste + 1].stripLeadingSpaces(buffer.params().track_changes);
509 return PasteReturnValue(pit, pos, need_update);
513 PitPosPair eraseSelectionHelper(BufferParams const & params,
514 ParagraphList & pars,
515 pit_type startpit, pit_type endpit,
516 int startpos, int endpos)
518 // Start of selection is really invalid.
519 if (startpit == pit_type(pars.size()) ||
520 (startpos > pars[startpit].size()))
521 return PitPosPair(endpit, endpos);
523 // Start and end is inside same paragraph
524 if (endpit == pit_type(pars.size()) || startpit == endpit) {
525 endpos -= pars[startpit].eraseChars(startpos, endpos, params.track_changes);
526 return PitPosPair(endpit, endpos);
529 for (pit_type pit = startpit; pit != endpit + 1;) {
530 pos_type const left = (pit == startpit ? startpos : 0);
531 pos_type right = (pit == endpit ? endpos : pars[pit].size() + 1);
532 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.track_changes);
534 // Logically erase only, including the end-of-paragraph character
535 pars[pit].eraseChars(left, right, params.track_changes);
537 // Separate handling of paragraph break:
538 if (merge && pit != endpit &&
540 || pars[pit].hasSameLayout(pars[endpit])
541 || pars[endpit].size() == endpos)) {
542 if (pit + 1 == endpit)
543 endpos += pars[pit].size();
544 mergeParagraph(params, pars, pit);
550 // Ensure legal cursor pos:
553 return PitPosPair(endpit, endpos);
557 Buffer * copyToTempBuffer(ParagraphList const & paragraphs, DocumentClassConstPtr docclass)
559 // This used to need to be static to avoid a memory leak. It no longer needs
560 // to be so, but the alternative is to construct a new one of these (with a
561 // new temporary directory, etc) every time, and then to destroy it. So maybe
562 // it's worth just keeping this one around.
563 static TempFile tempfile("clipboard.internal");
564 tempfile.setAutoRemove(false);
565 // The initialization of staticbuffer is thread-safe. Using a lambda
566 // guarantees that the properties are set only once.
567 static Buffer * staticbuffer = [&](){
569 theBufferList().newInternalBuffer(tempfile.name().absFileName());
571 b->inset().setBuffer(*b);
572 //initialize staticbuffer with b
575 // Use a clone for the complicated stuff so that we do not need to clean
576 // up in order to avoid a crash.
577 Buffer * buffer = staticbuffer->cloneBufferOnly();
578 LASSERT(buffer, return nullptr);
580 // This needs doing every time.
581 // Since setDocumentClass() causes deletion of the old document class
582 // we need to reset all layout pointers in paragraphs (otherwise they
583 // would be dangling).
584 ParIterator const end = buffer->par_iterator_end();
585 for (ParIterator it = buffer->par_iterator_begin(); it != end; ++it) {
586 docstring const name = it->layout().name();
587 if (docclass->hasLayout(name))
588 it->setLayout((*docclass)[name]);
590 it->setPlainOrDefaultLayout(*docclass);
592 buffer->params().setDocumentClass(docclass);
594 // we will use pasteSelectionHelper to copy the paragraphs into the
595 // temporary Buffer, since it does a lot of things to fix them up.
596 DocIterator dit = doc_iterator_begin(buffer, &buffer->inset());
598 pasteSelectionHelper(dit, paragraphs, docclass, cap::BRANCH_ADD, el);
604 void putClipboard(ParagraphList const & paragraphs,
605 DocInfoPair docinfo, docstring const & plaintext,
606 BufferParams const & bp)
608 Buffer * buffer = copyToTempBuffer(paragraphs, docinfo.first);
609 if (!buffer) // already asserted in copyToTempBuffer()
612 // We don't want to produce images that are not used. Therefore,
613 // output formulas as MathML. Even if this is not understood by all
614 // applications, the number that can parse it should go up in the future.
615 buffer->params().html_math_output = BufferParams::MathML;
617 // Copy authors to the params. We need those pointers.
618 for (Author const & a : bp.authors())
619 buffer->params().authors().record(a);
621 // Make sure MarkAsExporting is deleted before buffer is
623 // The Buffer is being used to export. This is necessary so that the
624 // updateMacros call will record the needed information.
625 MarkAsExporting mex(buffer);
627 buffer->updateBuffer(Buffer::UpdateMaster, OutputUpdate);
628 buffer->updateMacros();
629 buffer->updateMacroInstances(OutputUpdate);
634 if (buffer->write(oslyx))
638 odocstringstream oshtml;
639 OutputParams runparams(encodings.fromLyXName("utf8"));
640 // We do not need to produce images, etc.
641 runparams.dryrun = true;
642 // We are not interested in errors (bug 8866)
643 runparams.silent = true;
644 buffer->writeLyXHTMLSource(oshtml, runparams, Buffer::FullSource);
646 theClipboard().put(lyx, oshtml.str(), plaintext);
654 /// return true if the whole ParagraphList is deleted
655 static bool isFullyDeleted(ParagraphList const & pars)
657 pit_type const pars_size = static_cast<pit_type>(pars.size());
659 // check all paragraphs
660 for (pit_type pit = 0; pit < pars_size; ++pit) {
661 if (!pars[pit].empty()) // prevent assertion failure
662 if (!pars[pit].isDeleted(0, pars[pit].size()))
669 void copySelectionHelper(Buffer const & buf, Text const & text,
670 pit_type startpit, pit_type endpit,
671 int start, int end, DocumentClassConstPtr dc, CutStack & cutstack)
673 ParagraphList const & pars = text.paragraphs();
675 // In most of these cases, we can try to recover.
676 LASSERT(0 <= start, start = 0);
677 LASSERT(start <= pars[startpit].size(), start = pars[startpit].size());
678 LASSERT(0 <= end, end = 0);
679 LASSERT(end <= pars[endpit].size(), end = pars[endpit].size());
680 LASSERT(startpit != endpit || start <= end, return);
682 // Clone the paragraphs within the selection.
683 ParagraphList copy_pars(pars.iterator_at(startpit),
684 pars.iterator_at(endpit + 1));
686 // Remove the end of the last paragraph; afterwards, remove the
687 // beginning of the first paragraph. Keep this order - there may only
688 // be one paragraph! Do not track deletions here; this is an internal
689 // action not visible to the user
691 Paragraph & back = copy_pars.back();
692 back.eraseChars(end, back.size(), false);
693 Paragraph & front = copy_pars.front();
694 front.eraseChars(0, start, false);
696 for (auto & par : copy_pars) {
697 // Since we have a copy of the paragraphs, the insets
698 // do not have a proper buffer reference. It makes
699 // sense to add them temporarily, because the
700 // operations below depend on that (acceptChanges included).
701 par.setInsetBuffers(const_cast<Buffer &>(buf));
702 // PassThru paragraphs have the Language
703 // latex_language. This is invalid for others, so we
704 // need to change it to the buffer language.
705 if (par.isPassThru())
706 par.changeLanguage(buf.params(),
707 latex_language, buf.language());
710 // do not copy text (also nested in insets) which is marked as
711 // deleted, unless the whole selection was deleted
712 if (!lyxrc.ct_markup_copied) {
713 if (!isFullyDeleted(copy_pars))
714 acceptChanges(copy_pars, buf.params());
716 rejectChanges(copy_pars, buf.params());
720 // do some final cleanup now, to make sure that the paragraphs
721 // are not linked to something else.
722 for (auto & par : copy_pars) {
724 par.setInsetOwner(nullptr);
727 cutstack.push(make_pair(copy_pars, make_pair(dc, buf.params().authors())));
735 void region(CursorSlice const & i1, CursorSlice const & i2,
736 row_type & r1, row_type & r2,
737 col_type & c1, col_type & c2)
739 Inset const & p = i1.inset();
740 c1 = p.col(i1.idx());
741 c2 = p.col(i2.idx());
744 r1 = p.row(i1.idx());
745 r2 = p.row(i2.idx());
751 docstring grabAndEraseSelection(Cursor & cur)
753 if (!cur.selection())
755 docstring res = grabSelection(cur);
761 bool reduceSelectionToOneCell(CursorData & cur)
763 if (!cur.selection() || !cur.inMathed())
766 CursorSlice i1 = cur.selBegin();
767 CursorSlice i2 = cur.selEnd();
768 if (!i1.inset().asInsetMath())
771 // the easy case: do nothing if only one cell is selected
772 if (i1.idx() == i2.idx())
777 cur.top().pos() = cur.top().lastpos();
783 bool multipleCellsSelected(CursorData const & cur)
785 if (!cur.selection() || !cur.inMathed())
788 CursorSlice i1 = cur.selBegin();
789 CursorSlice i2 = cur.selEnd();
790 if (!i1.inset().asInsetMath())
793 if (i1.idx() == i2.idx())
800 void switchBetweenClasses(DocumentClassConstPtr oldone,
801 DocumentClassConstPtr newone, InsetText & in) {
803 switchBetweenClasses(oldone, newone, in, el);
807 void switchBetweenClasses(DocumentClassConstPtr oldone,
808 DocumentClassConstPtr newone, InsetText & in, ErrorList & errorlist)
812 LBUFERR(!in.paragraphs().empty());
813 if (oldone == newone)
816 DocumentClass const & oldtc = *oldone;
817 DocumentClass const & newtc = *newone;
820 ParIterator it = par_iterator_begin(in);
821 ParIterator pend = par_iterator_end(in);
822 // for remembering which layouts we've had to add
823 set<docstring> newlayouts;
824 for (; it != pend; ++it) {
825 docstring const name = it->layout().name();
827 // the pasted text will keep their own layout name. If this layout does
828 // not exist in the new document, it will behave like a standard layout.
829 bool const added_one = newtc.addLayoutIfNeeded(name);
831 newlayouts.insert(name);
833 if (added_one || newlayouts.find(name) != newlayouts.end()) {
835 docstring const s = bformat(_("Layout `%1$s' was not found."), name);
836 errorlist.push_back(ErrorItem(_("Layout Not Found"), s,
837 {it->id(), 0}, {it->id(), -1}));
840 if (in.usePlainLayout())
841 it->setLayout(newtc.plainLayout());
843 it->setLayout(newtc[name]);
846 // character styles and hidden table cells
847 InsetIterator const i_end = end(in);
848 for (InsetIterator iit = begin(in); iit != i_end; ++iit) {
849 InsetCode const code = iit->lyxCode();
850 if (code == FLEX_CODE) {
851 // FIXME: Should we verify all InsetCollapsible?
852 docstring const layoutName = iit->layoutName();
853 docstring const & n = newone->insetLayout(layoutName).name();
854 bool const is_undefined = n.empty() ||
855 n == DocumentClass::plainInsetLayout().name();
856 docstring const & oldn = oldone->insetLayout(layoutName).name();
857 bool const was_undefined = oldn.empty() ||
858 oldn == DocumentClass::plainInsetLayout().name();
859 if (!is_undefined || was_undefined)
862 // The flex inset is undefined in newtc
863 docstring const oldname = from_utf8(oldtc.name());
864 docstring const newname = from_utf8(newtc.name());
866 if (oldname == newname)
867 s = bformat(_("Flex inset %1$s is undefined after "
868 "reloading `%2$s' layout."), layoutName, oldname);
870 s = bformat(_("Flex inset %1$s is undefined because of "
871 "conversion from `%2$s' layout to `%3$s'."),
872 layoutName, oldname, newname);
873 // To warn the user that something had to be done.
874 errorlist.push_back(ErrorItem(
875 _("Undefined flex inset"), s,
876 {iit.paragraph().id(), iit.pos()},
877 {iit.paragraph().id(), iit.pos() + 1}));
878 } else if (code == TABULAR_CODE) {
879 // The recursion above does not catch paragraphs in "hidden" cells,
880 // i.e., ones that are part of a multirow or multicolum. So we need
881 // to handle those separately.
882 // This is the cause of bug #9049.
883 InsetTabular * table = iit->asInsetTabular();
884 table->setLayoutForHiddenCells(newtc);
890 vector<docstring> availableSelections(Buffer const * buf)
892 vector<docstring> selList;
896 for (auto const & cut : theCuts) {
897 ParagraphList const & pars = cut.first;
899 for (auto const & para : pars) {
900 Paragraph par(para, 0, 46);
901 // adapt paragraph to current buffer.
902 par.setInsetBuffers(const_cast<Buffer &>(*buf));
903 textSel += par.asString(AS_STR_INSETS);
904 if (textSel.size() > 45) {
905 support::truncateWithEllipsis(textSel,45);
909 selList.push_back(textSel);
916 size_type numberOfSelections()
918 return theCuts.size();
923 void cutSelectionHelper(Cursor & cur, CutStack & cuts, bool realcut, bool putclip)
925 // This doesn't make sense, if there is no selection
926 if (!cur.selection())
929 // OK, we have a selection. This is always between cur.selBegin()
932 if (cur.inTexted()) {
933 Text * text = cur.text();
938 // make sure that the depth behind the selection are restored, too
939 cur.recordUndoSelection();
940 pit_type begpit = cur.selBegin().pit();
941 pit_type endpit = cur.selEnd().pit();
943 int endpos = cur.selEnd().pos();
945 BufferParams const & bp = cur.buffer()->params();
947 copySelectionHelper(*cur.buffer(),
950 cur.selBegin().pos(), endpos,
951 bp.documentClassPtr(), cuts);
952 // Stuff what we got on the clipboard.
953 // Even if there is no selection.
955 putClipboard(cuts[0].first, cuts[0].second,
956 cur.selectionAsString(true, true), bp);
959 if (begpit != endpit)
960 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
962 tie(endpit, endpos) =
963 eraseSelectionHelper(bp, text->paragraphs(), begpit, endpit,
964 cur.selBegin().pos(), endpos);
966 // cutSelection can invalidate the cursor so we need to set
968 // we prefer the end for when tracking changes
972 // need a valid cursor. (Lgb)
973 cur.clearSelection();
975 // After a cut operation, we must make sure that the Buffer is updated
976 // because some further operation might need updated label information for
977 // example. So we cannot just use "cur.forceBufferUpdate()" here.
979 cur.buffer()->updateBuffer();
981 // tell tabular that a recent copy happened
982 dirtyTabularStack(false);
985 if (cur.inMathed()) {
986 if (cur.selBegin().idx() != cur.selEnd().idx()) {
987 // The current selection spans more than one cell.
989 cur.recordUndoInset();
991 // Record only the current cell to avoid a jumping
1003 void cutSelection(Cursor & cur, bool realcut)
1005 cutSelectionHelper(cur, theCuts, realcut, true);
1009 void cutSelectionToTemp(Cursor & cur, bool realcut)
1011 cutSelectionHelper(cur, tempCut, realcut, false);
1015 void copySelection(Cursor const & cur)
1017 copySelection(cur, cur.selectionAsString(true, true));
1021 void copyInset(Cursor const & cur, Inset * inset, docstring const & plaintext)
1025 BufferParams const & bp = cur.buffer()->params();
1026 par.setLayout(bp.documentClass().plainLayout());
1027 Font font(inherit_font, bp.language);
1028 par.insertInset(0, inset, font, Change(Change::UNCHANGED));
1029 pars.push_back(par);
1030 theCuts.push(make_pair(pars, make_pair(bp.documentClassPtr(), bp.authors())));
1032 // stuff the selection onto the X clipboard, from an explicit copy request
1033 putClipboard(theCuts[0].first, theCuts[0].second, plaintext, bp);
1039 void copySelectionToStack(CursorData const & cur, CutStack & cutstack)
1041 // this doesn't make sense, if there is no selection
1042 if (!cur.selection())
1045 // copySelection can not yet handle the case of cross idx selection
1046 if (cur.selBegin().idx() != cur.selEnd().idx())
1049 if (cur.inTexted()) {
1050 Text * text = cur.text();
1052 // ok we have a selection. This is always between cur.selBegin()
1053 // and sel_end cursor
1054 copySelectionHelper(*cur.buffer(), *text,
1055 cur.selBegin().pit(), cur.selEnd().pit(),
1056 cur.selBegin().pos(), cur.selEnd().pos(),
1057 cur.buffer()->params().documentClassPtr(),
1059 // Reset the dirty_tabular_stack_ flag only when something
1060 // is copied to the clipboard (not to the selectionBuffer).
1061 if (&cutstack == &theCuts)
1062 dirtyTabularStack(false);
1065 if (cur.inMathed()) {
1066 //lyxerr << "copySelection in mathed" << endl;
1069 BufferParams const & bp = cur.buffer()->params();
1070 // FIXME This should be the plain layout...right?
1071 par.setLayout(bp.documentClass().plainLayout());
1072 // For pasting into text, we set the language to the paragraph language
1073 // (rather than the default_language which is always English; see #2596)
1074 par.insert(0, grabSelection(cur), Font(sane_font, par.getParLanguage(bp)),
1075 Change(Change::UNCHANGED));
1076 pars.push_back(par);
1077 cutstack.push(make_pair(pars, make_pair(bp.documentClassPtr(), bp.authors())));
1084 void copySelectionToStack()
1086 if (!selectionBuffer.empty())
1087 theCuts.push(selectionBuffer[0]);
1091 void copySelectionToTemp(Cursor const & cur)
1093 copySelectionToStack(cur, tempCut);
1097 void copySelection(Cursor const & cur, docstring const & plaintext)
1099 // In tablemode, because copy and paste actually use a special table stack,
1100 // we need to go through the cells and collect the paragraphs.
1101 // In math matrices, we generate a plain text version.
1102 if (cur.selBegin().idx() != cur.selEnd().idx()) {
1104 BufferParams const & bp = cur.buffer()->params();
1105 if (cur.inMathed()) {
1107 par.setLayout(bp.documentClass().plainLayout());
1108 // Replace (column-separating) tabs by space (#4449)
1109 docstring const clean_text = subst(plaintext, '\t', ' ');
1110 // For pasting into text, we set the language to the paragraph language
1111 // (rather than the default_language which is always English; see #11898)
1112 par.insert(0, clean_text, Font(sane_font, par.getParLanguage(bp)),
1113 Change(Change::UNCHANGED));
1114 pars.push_back(par);
1116 // Get paragraphs from all cells
1117 InsetTabular * table = cur.inset().asInsetTabular();
1118 LASSERT(table, return);
1119 ParagraphList tplist = table->asParList(cur.selBegin().idx(), cur.selEnd().idx());
1120 for (auto & cpar : tplist) {
1121 cpar.setLayout(bp.documentClass().plainLayout());
1122 pars.push_back(cpar);
1123 // since the pars are merged later, we separate them by blank
1125 epar.insert(0, from_ascii(" "), Font(sane_font, epar.getParLanguage(bp)),
1126 Change(Change::UNCHANGED));
1127 pars.push_back(epar);
1129 // remove last empty par
1131 // merge all paragraphs to one
1132 while (pars.size() > 1)
1133 mergeParagraph(bp, pars, 0);
1135 theCuts.push(make_pair(pars, make_pair(bp.documentClassPtr(), bp.authors())));
1137 copySelectionToStack(cur, theCuts);
1140 // stuff the selection onto the X clipboard, from an explicit copy request
1141 putClipboard(theCuts[0].first, theCuts[0].second, plaintext,
1142 cur.buffer()->params());
1146 void saveSelection(Cursor const & cur)
1148 // This function is called, not when a selection is formed, but when
1149 // a selection is cleared. Therefore, multiple keyboard selection
1150 // will not repeatively trigger this function (bug 3877).
1152 && cur.selBegin() == cur.bv().cursor().selBegin()
1153 && cur.selEnd() == cur.bv().cursor().selEnd()) {
1154 LYXERR(Debug::SELECTION, "saveSelection: '" << cur.selectionAsString(true, true) << "'");
1155 copySelectionToStack(cur, selectionBuffer);
1162 return !selectionBuffer.empty();
1166 void clearSelection()
1168 selectionBuffer.clear();
1172 void clearCutStack()
1179 docstring selection(size_t sel_index, DocInfoPair docinfo, bool for_math)
1181 if (sel_index >= theCuts.size())
1184 unique_ptr<Buffer> buffer(copyToTempBuffer(theCuts[sel_index].first,
1189 int options = AS_STR_INSETS | AS_STR_NEWLINES;
1191 options |= AS_STR_MATHED;
1193 return buffer->paragraphs().back().asString(options);
1197 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
1198 DocumentClassConstPtr docclass, AuthorList const & authors,
1199 ErrorList & errorList,
1200 cap::BranchAction branchAction)
1202 // Copy authors to the params. We need those pointers.
1203 for (Author const & a : authors)
1204 cur.buffer()->params().authors().record(a);
1206 if (cur.inTexted()) {
1207 Text * text = cur.text();
1210 PasteReturnValue prv =
1211 pasteSelectionHelper(cur, parlist, docclass, branchAction, errorList);
1212 cur.forceBufferUpdate();
1213 cur.clearSelection();
1214 text->setCursor(cur, prv.pit, prv.pos);
1217 // mathed is handled in InsetMathNest/InsetMathGrid
1218 LATTEST(!cur.inMathed());
1222 bool pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
1224 // this does not make sense, if there is nothing to paste
1225 if (!checkPastePossible(sel_index))
1229 pasteParagraphList(cur, theCuts[sel_index].first,
1230 theCuts[sel_index].second.first, theCuts[sel_index].second.second,
1231 errorList, BRANCH_ASK);
1236 bool pasteFromTemp(Cursor & cur, ErrorList & errorList)
1238 // this does not make sense, if there is nothing to paste
1239 if (tempCut.empty() || tempCut[0].first.empty())
1243 pasteParagraphList(cur, tempCut[0].first,
1244 tempCut[0].second.first, tempCut[0].second.second,
1245 errorList, BRANCH_IGNORE);
1250 bool pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs,
1251 Clipboard::TextType type)
1253 // Use internal clipboard if it is the most recent one
1254 // This overrides asParagraphs and type on purpose!
1255 if (theClipboard().isInternal())
1256 return pasteFromStack(cur, errorList, 0);
1258 // First try LyX format
1259 if ((type == Clipboard::LyXTextType ||
1260 type == Clipboard::LyXOrPlainTextType ||
1261 type == Clipboard::AnyTextType) &&
1262 theClipboard().hasTextContents(Clipboard::LyXTextType)) {
1263 string lyx = theClipboard().getAsLyX();
1265 Buffer buffer(string(), false);
1266 buffer.setInternal(true);
1267 buffer.setUnnamed(true);
1268 if (buffer.readString(lyx)) {
1270 pasteParagraphList(cur, buffer.paragraphs(),
1271 buffer.params().documentClassPtr(),
1272 buffer.params().authors(),
1279 // Then try TeX and HTML
1280 Clipboard::TextType types[2] = {Clipboard::HtmlTextType, Clipboard::LaTeXTextType};
1281 string names[2] = {"html", "latexclipboard"};
1282 for (int i = 0; i < 2; ++i) {
1283 if (type != types[i] && type != Clipboard::AnyTextType)
1285 bool available = theClipboard().hasTextContents(types[i]);
1287 // If a specific type was explicitly requested, try to
1288 // interpret plain text: The user told us that the clipboard
1289 // contents is in the desired format
1290 if (!available && type == types[i]) {
1291 types[i] = Clipboard::PlainTextType;
1292 available = theClipboard().hasTextContents(types[i]);
1296 docstring text = theClipboard().getAsText(types[i]);
1297 available = !text.empty();
1299 Buffer buffer(string(), false);
1300 buffer.setInternal(true);
1301 buffer.setUnnamed(true);
1302 available = buffer.importString(names[i], text, errorList);
1304 available = !buffer.paragraphs().empty();
1305 if (available && !buffer.paragraphs()[0].empty()) {
1306 // TeX2lyx (also used in the HTML chain) assumes English as document language
1307 // if no language is explicitly set (as is the case here).
1308 // We thus reset the temp buffer's language to the context language
1309 buffer.changeLanguage(buffer.language(), cur.getFont().language());
1311 pasteParagraphList(cur, buffer.paragraphs(),
1312 buffer.params().documentClassPtr(),
1313 buffer.params().authors(),
1321 // Then try plain text
1322 docstring const text = theClipboard().getAsText(Clipboard::PlainTextType);
1327 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1329 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1330 cur.forceBufferUpdate();
1335 void pasteSimpleText(Cursor & cur, bool asParagraphs)
1338 // Use internal clipboard if it is the most recent one
1339 if (theClipboard().isInternal()) {
1340 if (!checkPastePossible(0))
1343 ParagraphList const & pars = theCuts[0].first;
1344 ParagraphList::const_iterator it = pars.begin();
1345 for (; it != pars.end(); ++it) {
1346 if (it != pars.begin())
1348 text += (*it).asString();
1350 asParagraphs = false;
1352 // Then try plain text
1353 text = theClipboard().getAsText(Clipboard::PlainTextType);
1360 cutSelection(cur, false);
1362 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1364 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1368 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
1369 Clipboard::GraphicsType preferedType)
1371 LASSERT(theClipboard().hasGraphicsContents(preferedType), return);
1373 // get picture from clipboard
1374 FileName filename = theClipboard().getAsGraphics(cur, preferedType);
1375 if (filename.empty())
1378 // create inset for graphic
1379 InsetGraphics * inset = new InsetGraphics(cur.buffer());
1380 InsetGraphicsParams params;
1381 params.filename = support::DocFileName(filename.absFileName(), false);
1382 inset->setParams(params);
1388 void pasteSelection(Cursor & cur, ErrorList & errorList)
1390 if (selectionBuffer.empty())
1393 pasteParagraphList(cur, selectionBuffer[0].first,
1394 selectionBuffer[0].second.first,
1395 selectionBuffer[0].second.second,
1400 void replaceSelectionWithString(Cursor & cur, docstring const & str)
1403 DocIterator selbeg = cur.selectionBegin();
1405 // Get font setting before we cut, we need a copy here, not a bare reference.
1407 selbeg.paragraph().getFontSettings(cur.buffer()->params(), selbeg.pos());
1409 // Insert the new string
1410 pos_type pos = cur.selEnd().pos();
1411 Paragraph & par = cur.selEnd().paragraph();
1412 for (auto const & c : str) {
1413 par.insertChar(pos, c, font, cur.buffer()->params().track_changes);
1417 // Cut the selection
1418 cutSelection(cur, false);
1422 void replaceSelection(Cursor & cur)
1424 if (cur.selection())
1425 cutSelection(cur, false);
1429 void eraseSelection(Cursor & cur)
1431 //lyxerr << "cap::eraseSelection begin: " << cur << endl;
1432 CursorSlice const & i1 = cur.selBegin();
1433 CursorSlice const & i2 = cur.selEnd();
1434 if (!i1.asInsetMath()) {
1435 LYXERR0("Can't erase this selection");
1441 InsetMath * p = i1.asInsetMath();
1442 if (i1.idx() == i2.idx()) {
1443 i1.cell().erase(i1.pos(), i2.pos());
1444 // We may have deleted i1.cell(cur.pos()).
1445 // Make sure that pos is valid.
1446 if (cur.pos() > cur.lastpos())
1447 cur.pos() = cur.lastpos();
1448 } else if (p->nrows() > 0 && p->ncols() > 0) {
1449 // This is a grid, delete a nice square region
1452 region(i1, i2, r1, r2, c1, c2);
1453 for (row_type row = r1; row <= r2; ++row)
1454 for (col_type col = c1; col <= c2; ++col)
1455 p->cell(p->index(row, col)).clear();
1456 // We've deleted the whole cell. Only pos 0 is valid.
1459 idx_type idx1 = i1.idx();
1460 idx_type idx2 = i2.idx();
1463 for (idx_type idx = idx1 ; idx <= idx2; ++idx)
1464 p->cell(idx).clear();
1465 // We've deleted the whole cell. Only pos 0 is valid.
1469 // need a valid cursor. (Lgb)
1470 cur.clearSelection();
1471 //lyxerr << "cap::eraseSelection end: " << cur << endl;
1475 void selDel(Cursor & cur)
1477 //lyxerr << "cap::selDel" << endl;
1478 if (cur.selection())
1479 eraseSelection(cur);
1483 void selClearOrDel(Cursor & cur)
1485 //lyxerr << "cap::selClearOrDel" << endl;
1486 if (lyxrc.auto_region_delete)
1489 cur.selection(false);
1493 docstring grabSelection(CursorData const & cur)
1495 if (!cur.selection())
1499 // grab selection by glueing multiple cells together. This is not what
1500 // we want because selections spanning multiple cells will get "&" and "\\"
1503 for (DocIterator dit = cur.selectionBegin();
1504 dit != cur.selectionEnd(); dit.forwardPos())
1505 os << asString(dit.cell());
1509 CursorSlice i1 = cur.selBegin();
1510 CursorSlice i2 = cur.selEnd();
1512 if (i1.idx() == i2.idx()) {
1513 if (i1.inset().asInsetMath()) {
1514 MathData::const_iterator it = i1.cell().begin();
1515 Buffer * buf = cur.buffer();
1516 return asString(MathData(buf, it + i1.pos(), it + i2.pos()));
1518 return from_ascii("unknown selection 1");
1524 region(i1, i2, r1, r2, c1, c2);
1527 if (i1.inset().asInsetMath()) {
1528 for (row_type row = r1; row <= r2; ++row) {
1531 for (col_type col = c1; col <= c2; ++col) {
1534 data += asString(i1.asInsetMath()->
1535 cell(i1.asInsetMath()->index(row, col)));
1539 data = from_ascii("unknown selection 2");
1545 void dirtyTabularStack(bool b)
1547 dirty_tabular_stack_ = b;
1551 bool tabularStackDirty()
1553 return dirty_tabular_stack_;