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);
296 if (lyxrc.ct_markup_copied) {
297 // Only remove deleted text and change
298 // the rest to inserted if ct is active,
299 // otherwise leave markup as is
300 if (buffer.params().track_changes) {
301 if (tmpbuf->size() > 0) {
302 if (!isFullyDeleted(insertion))
303 tmpbuf->acceptChanges(0, tmpbuf->size());
305 tmpbuf->rejectChanges(0, tmpbuf->size());
307 tmpbuf->setChange(Change(Change::INSERTED));
310 // Resolve all markup to inserted or unchanged
311 // Deleted text has already been removed on copy
312 // (copySelectionHelper)
313 tmpbuf->setChange(Change(buffer.params().track_changes ?
314 Change::INSERTED : Change::UNCHANGED));
317 bool const target_empty = pars[pit].empty();
318 // Use the paste content's layout, if...
319 bool const paste_layout =
320 // if target paragraph is empty
322 // ... and its layout is default
323 && (pars[pit].layout() == defaultLayout
325 || pars[pit].layout() == plainLayout
326 // ... or the paste content spans several paragraphs
327 || insertion.size() > 1))
328 // or if pasting is done at the beginning of paragraph
330 // and the paste content spans several paragraphs
331 && insertion.size() > 1);
333 // Give the first paragraph to insert the same layout as the
335 insertion.begin()->makeSameLayout(pars[pit]);
337 // Prepare the paragraphs and insets for insertion.
338 insertion.swap(in.paragraphs());
340 InsetIterator const i_end = end(in);
341 for (InsetIterator it = begin(in); it != i_end; ++it) {
342 // Even though this will also be done later, it has to be done here
343 // since some inset might try to access the buffer() member.
344 it->setBuffer(const_cast<Buffer &>(buffer));
345 switch (it->lyxCode()) {
347 case MATH_HULL_CODE: {
348 // check for equation labels and resolve duplicates
349 InsetMathHull * ins = it->asInsetMath()->asHullInset();
350 std::vector<InsetLabel *> labels = ins->getLabels();
351 for (size_t i = 0; i != labels.size(); ++i) {
354 InsetLabel * lab = labels[i];
355 docstring const oldname = lab->getParam("name");
356 lab->updateLabel(oldname, in_active_inset);
357 // We need to update the buffer reference cache.
359 docstring const newname = lab->getParam("name");
360 if (oldname == newname)
362 // adapt the references
363 for (InsetIterator itt = begin(in);
364 itt != i_end; ++itt) {
365 if (itt->lyxCode() == REF_CODE) {
366 InsetCommand * ref = itt->asInsetCommand();
367 if (ref->getParam("reference") == oldname)
368 ref->setParam("reference", newname);
369 } else if (itt->lyxCode() == MATH_REF_CODE) {
370 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
371 // this is necessary to prevent an uninitialized
372 // buffer when the RefInset is in a MathBox.
373 // FIXME audit setBuffer calls
374 mi->setBuffer(const_cast<Buffer &>(buffer));
375 if (mi->getTarget() == oldname)
376 mi->changeTarget(newname);
384 // check for duplicates
385 InsetLabel & lab = static_cast<InsetLabel &>(*it);
386 docstring const oldname = lab.getParam("name");
387 lab.updateLabel(oldname, in_active_inset);
388 // We need to update the buffer reference cache.
390 docstring const newname = lab.getParam("name");
391 if (oldname == newname)
393 // adapt the references
394 for (InsetIterator itt = begin(in); itt != i_end; ++itt) {
395 if (itt->lyxCode() == REF_CODE) {
396 InsetCommand & ref = static_cast<InsetCommand &>(*itt);
397 if (ref.getParam("reference") == oldname)
398 ref.setParam("reference", newname);
399 } else if (itt->lyxCode() == MATH_REF_CODE) {
400 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
401 // this is necessary to prevent an uninitialized
402 // buffer when the RefInset is in a MathBox.
403 // FIXME audit setBuffer calls
404 mi->setBuffer(const_cast<Buffer &>(buffer));
405 if (mi->getTarget() == oldname)
406 mi->changeTarget(newname);
413 InsetInclude & inc = static_cast<InsetInclude &>(*it);
415 // We need to update the list of included files.
421 InsetCitation & cit = static_cast<InsetCitation &>(*it);
422 // This actually only needs to be done if the cite engine
423 // differs, but we do it in general.
425 // We need to update the list of citations.
431 // check for duplicates
432 InsetBibitem & bib = static_cast<InsetBibitem &>(*it);
433 docstring const oldkey = bib.getParam("key");
434 bib.updateCommand(oldkey, false);
435 // We need to update the buffer reference cache.
437 docstring const newkey = bib.getParam("key");
438 if (oldkey == newkey)
440 // adapt the references
441 for (InsetIterator itt = begin(in);
442 itt != i_end; ++itt) {
443 if (itt->lyxCode() == CITE_CODE) {
444 InsetCommand * ref = itt->asInsetCommand();
445 if (ref->getParam("key") == oldkey)
446 ref->setParam("key", newkey);
453 // check if branch is known to target buffer
455 InsetBranch & br = static_cast<InsetBranch &>(*it);
456 docstring const name = br.branch();
459 bool const is_child = (&buffer != buffer.masterBuffer());
460 BranchList branchlist = buffer.params().branchlist();
461 if ((!is_child && branchlist.find(name))
462 || (is_child && (branchlist.find(name)
463 || buffer.masterBuffer()->params().branchlist().find(name))))
465 switch(branchAction) {
466 case cap::BRANCH_ADD: {
467 // This is for a temporary buffer, so simply create the branch.
468 // Must not use lyx::dispatch(), since tmpbuffer has no view.
470 const_cast<Buffer&>(buffer).dispatch(FuncRequest(LFUN_BRANCH_ADD, name), dr);
473 case cap::BRANCH_ASK: {
474 docstring text = bformat(
475 _("The pasted branch \"%1$s\" is undefined.\n"
476 "Do you want to add it to the document's branch list?"),
478 if (frontend::Alert::prompt(_("Unknown branch"),
479 text, 0, 1, _("&Add"), _("&Don't Add")) != 0)
481 lyx::dispatch(FuncRequest(LFUN_BRANCH_ADD, name));
484 case cap::BRANCH_IGNORE:
487 // We need to update the list of branches.
496 insertion.swap(in.paragraphs());
498 // Split the paragraph for inserting the buf if necessary.
500 breakParagraphConservative(buffer.params(), pars, pit, pos);
502 // If multiple paragraphs are inserted before the target paragraph,
503 // the cursor is now in a new paragraph before it,
504 // so use layout from paste content in that case.
505 if (pos == 0 && insertion.size() > 1)
506 pars[pit].makeSameLayout(* insertion.begin());
510 pars.insert(pars.iterator_at(pit),
511 insertion.begin(), insertion.end());
513 // merge the empty par with the last par of the insertion
514 mergeParagraph(buffer.params(), pars,
515 pit + insertion.size() - 1);
517 pars.insert(pars.iterator_at(pit + 1),
518 insertion.begin(), insertion.end());
520 // merge the first par of the insertion with the current par
521 mergeParagraph(buffer.params(), pars, pit);
524 // Store the new cursor position.
525 pit_type last_paste = pit + insertion.size() - 1;
526 pit_type startpit = pit;
528 pos = pars[last_paste].size();
530 // FIXME Should we do it here, or should we let updateBuffer() do it?
531 // Set paragraph buffers. It's important to do this right away
532 // before something calls Inset::buffer() and causes a crash.
533 for (pit_type p = startpit; p <= pit; ++p)
534 pars[p].setInsetBuffers(const_cast<Buffer &>(buffer));
536 // Join (conditionally) last pasted paragraph with next one, i.e.,
537 // the tail of the spliced document paragraph
538 if (!target_empty && last_paste + 1 != pit_type(pars.size())) {
539 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
540 mergeParagraph(buffer.params(), pars, last_paste);
541 } else if (pars[last_paste + 1].empty()) {
542 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
543 mergeParagraph(buffer.params(), pars, last_paste);
544 } else if (pars[last_paste].empty()) {
545 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
546 mergeParagraph(buffer.params(), pars, last_paste);
548 pars[last_paste + 1].stripLeadingSpaces(buffer.params().track_changes);
553 return PasteReturnValue(pit, pos, need_update);
557 PitPosPair eraseSelectionHelper(BufferParams const & params,
558 ParagraphList & pars,
559 pit_type startpit, pit_type endpit,
560 int startpos, int endpos)
562 // Start of selection is really invalid.
563 if (startpit == pit_type(pars.size()) ||
564 (startpos > pars[startpit].size()))
565 return PitPosPair(endpit, endpos);
567 // Start and end is inside same paragraph
568 if (endpit == pit_type(pars.size()) || startpit == endpit) {
569 endpos -= pars[startpit].eraseChars(startpos, endpos, params.track_changes);
570 return PitPosPair(endpit, endpos);
573 for (pit_type pit = startpit; pit != endpit + 1;) {
574 pos_type const left = (pit == startpit ? startpos : 0);
575 pos_type right = (pit == endpit ? endpos : pars[pit].size() + 1);
576 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.track_changes);
578 // Logically erase only, including the end-of-paragraph character
579 pars[pit].eraseChars(left, right, params.track_changes);
581 // Separate handling of paragraph break:
582 if (merge && pit != endpit) {
583 if (pit + 1 == endpit)
584 endpos += pars[pit].size();
585 mergeParagraph(params, pars, pit);
591 // Ensure legal cursor pos:
594 return PitPosPair(endpit, endpos);
598 Buffer * copyToTempBuffer(ParagraphList const & paragraphs, DocumentClassConstPtr docclass)
600 // This used to need to be static to avoid a memory leak. It no longer needs
601 // to be so, but the alternative is to construct a new one of these (with a
602 // new temporary directory, etc) every time, and then to destroy it. So maybe
603 // it's worth just keeping this one around.
604 static TempFile tempfile("clipboard.internal");
605 tempfile.setAutoRemove(false);
606 // The initialization of staticbuffer is thread-safe. Using a lambda
607 // guarantees that the properties are set only once.
608 static Buffer * staticbuffer = [&](){
610 theBufferList().newInternalBuffer(tempfile.name().absFileName());
612 b->inset().setBuffer(*b);
613 //initialize staticbuffer with b
616 // Use a clone for the complicated stuff so that we do not need to clean
617 // up in order to avoid a crash.
618 Buffer * buffer = staticbuffer->cloneBufferOnly();
619 LASSERT(buffer, return nullptr);
621 // This needs doing every time.
622 // Since setDocumentClass() causes deletion of the old document class
623 // we need to reset all layout pointers in paragraphs (otherwise they
624 // would be dangling).
625 ParIterator const end = buffer->par_iterator_end();
626 for (ParIterator it = buffer->par_iterator_begin(); it != end; ++it) {
627 docstring const name = it->layout().name();
628 if (docclass->hasLayout(name))
629 it->setLayout((*docclass)[name]);
631 it->setPlainOrDefaultLayout(*docclass);
633 buffer->params().setDocumentClass(docclass);
635 // we will use pasteSelectionHelper to copy the paragraphs into the
636 // temporary Buffer, since it does a lot of things to fix them up.
637 DocIterator dit = doc_iterator_begin(buffer, &buffer->inset());
639 pasteSelectionHelper(dit, paragraphs, docclass, cap::BRANCH_ADD, el);
645 void putClipboard(ParagraphList const & paragraphs,
646 DocInfoPair docinfo, docstring const & plaintext,
647 BufferParams const & bp)
649 Buffer * buffer = copyToTempBuffer(paragraphs, docinfo.first);
650 if (!buffer) // already asserted in copyToTempBuffer()
653 // We don't want to produce images that are not used. Therefore,
654 // output formulas as MathML. Even if this is not understood by all
655 // applications, the number that can parse it should go up in the future.
656 buffer->params().html_math_output = BufferParams::MathML;
658 // Copy authors to the params. We need those pointers.
659 for (Author const & a : bp.authors())
660 buffer->params().authors().record(a);
662 // Make sure MarkAsExporting is deleted before buffer is
664 // The Buffer is being used to export. This is necessary so that the
665 // updateMacros call will record the needed information.
666 MarkAsExporting mex(buffer);
668 buffer->updateBuffer(Buffer::UpdateMaster, OutputUpdate);
669 buffer->updateMacros();
670 buffer->updateMacroInstances(OutputUpdate);
675 if (buffer->write(oslyx))
679 odocstringstream oshtml;
680 OutputParams runparams(encodings.fromLyXName("utf8"));
681 // We do not need to produce images, etc.
682 runparams.dryrun = true;
683 // We are not interested in errors (bug 8866)
684 runparams.silent = true;
685 buffer->writeLyXHTMLSource(oshtml, runparams, Buffer::FullSource);
687 theClipboard().put(lyx, oshtml.str(), plaintext);
695 void copySelectionHelper(Buffer const & buf, Text const & text,
696 pit_type startpit, pit_type endpit,
697 int start, int end, DocumentClassConstPtr dc, CutStack & cutstack)
699 ParagraphList const & pars = text.paragraphs();
701 // In most of these cases, we can try to recover.
702 LASSERT(0 <= start, start = 0);
703 LASSERT(start <= pars[startpit].size(), start = pars[startpit].size());
704 LASSERT(0 <= end, end = 0);
705 LASSERT(end <= pars[endpit].size(), end = pars[endpit].size());
706 LASSERT(startpit != endpit || start <= end, return);
708 // Clone the paragraphs within the selection.
709 ParagraphList copy_pars(pars.iterator_at(startpit),
710 pars.iterator_at(endpit + 1));
712 // Remove the end of the last paragraph; afterwards, remove the
713 // beginning of the first paragraph. Keep this order - there may only
714 // be one paragraph! Do not track deletions here; this is an internal
715 // action not visible to the user
717 Paragraph & back = copy_pars.back();
718 back.eraseChars(end, back.size(), false);
719 Paragraph & front = copy_pars.front();
720 front.eraseChars(0, start, false);
722 for (auto & par : copy_pars) {
723 // Since we have a copy of the paragraphs, the insets
724 // do not have a proper buffer reference. It makes
725 // sense to add them temporarily, because the
726 // operations below depend on that (acceptChanges included).
727 par.setInsetBuffers(const_cast<Buffer &>(buf));
728 // PassThru paragraphs have the Language
729 // latex_language. This is invalid for others, so we
730 // need to change it to the buffer language.
731 if (par.isPassThru())
732 par.changeLanguage(buf.params(),
733 latex_language, buf.language());
736 // do not copy text (also nested in insets) which is marked as
737 // deleted, unless the whole selection was deleted
738 if (!lyxrc.ct_markup_copied) {
739 if (!isFullyDeleted(copy_pars))
740 acceptChanges(copy_pars, buf.params());
742 rejectChanges(copy_pars, buf.params());
746 // do some final cleanup now, to make sure that the paragraphs
747 // are not linked to something else.
748 for (auto & par : copy_pars) {
750 par.setInsetOwner(nullptr);
753 cutstack.push(make_pair(copy_pars, make_pair(dc, buf.params().authors())));
761 void region(CursorSlice const & i1, CursorSlice const & i2,
762 row_type & r1, row_type & r2,
763 col_type & c1, col_type & c2)
765 Inset const & p = i1.inset();
766 c1 = p.col(i1.idx());
767 c2 = p.col(i2.idx());
770 r1 = p.row(i1.idx());
771 r2 = p.row(i2.idx());
777 docstring grabAndEraseSelection(Cursor & cur)
779 if (!cur.selection())
781 docstring res = grabSelection(cur);
787 bool reduceSelectionToOneCell(CursorData & cur)
789 if (!cur.selection() || !cur.inMathed())
792 CursorSlice i1 = cur.selBegin();
793 CursorSlice i2 = cur.selEnd();
794 if (!i1.inset().asInsetMath())
797 // the easy case: do nothing if only one cell is selected
798 if (i1.idx() == i2.idx())
803 cur.top().pos() = cur.top().lastpos();
809 bool multipleCellsSelected(CursorData const & cur)
811 if (!cur.selection() || !cur.inMathed())
814 CursorSlice i1 = cur.selBegin();
815 CursorSlice i2 = cur.selEnd();
816 if (!i1.inset().asInsetMath())
819 if (i1.idx() == i2.idx())
826 void switchBetweenClasses(DocumentClassConstPtr oldone,
827 DocumentClassConstPtr newone, InsetText & in) {
829 switchBetweenClasses(oldone, newone, in, el);
833 void switchBetweenClasses(DocumentClassConstPtr oldone,
834 DocumentClassConstPtr newone, InsetText & in, ErrorList & errorlist)
838 LBUFERR(!in.paragraphs().empty());
839 if (oldone == newone)
842 DocumentClass const & oldtc = *oldone;
843 DocumentClass const & newtc = *newone;
846 ParIterator it = par_iterator_begin(in);
847 ParIterator pend = par_iterator_end(in);
848 // for remembering which layouts we've had to add
849 set<docstring> newlayouts;
850 for (; it != pend; ++it) {
851 docstring const name = it->layout().name();
853 // the pasted text will keep their own layout name. If this layout does
854 // not exist in the new document, it will behave like a standard layout.
855 bool const added_one = newtc.addLayoutIfNeeded(name);
857 newlayouts.insert(name);
859 if (added_one || newlayouts.find(name) != newlayouts.end()) {
861 docstring const s = bformat(_("Layout `%1$s' was not found."), name);
862 errorlist.push_back(ErrorItem(_("Layout Not Found"), s,
863 {it->id(), 0}, {it->id(), -1}));
866 if (in.usePlainLayout())
867 it->setLayout(newtc.plainLayout());
869 it->setLayout(newtc[name]);
872 // character styles and hidden table cells
873 InsetIterator const i_end = end(in);
874 for (InsetIterator iit = begin(in); iit != i_end; ++iit) {
875 InsetCode const code = iit->lyxCode();
876 if (code == FLEX_CODE) {
877 // FIXME: Should we verify all InsetCollapsible?
878 docstring const layoutName = iit->layoutName();
879 docstring const & n = newone->insetLayout(layoutName).name();
880 bool const is_undefined = n.empty() ||
881 n == DocumentClass::plainInsetLayout().name();
882 docstring const & oldn = oldone->insetLayout(layoutName).name();
883 bool const was_undefined = oldn.empty() ||
884 oldn == DocumentClass::plainInsetLayout().name();
885 if (!is_undefined || was_undefined)
888 // The flex inset is undefined in newtc
889 docstring const oldname = from_utf8(oldtc.name());
890 docstring const newname = from_utf8(newtc.name());
892 if (oldname == newname)
893 s = bformat(_("Flex inset %1$s is undefined after "
894 "reloading `%2$s' layout."), layoutName, oldname);
896 s = bformat(_("Flex inset %1$s is undefined because of "
897 "conversion from `%2$s' layout to `%3$s'."),
898 layoutName, oldname, newname);
899 // To warn the user that something had to be done.
900 errorlist.push_back(ErrorItem(
901 _("Undefined flex inset"), s,
902 {iit.paragraph().id(), iit.pos()},
903 {iit.paragraph().id(), iit.pos() + 1}));
904 } else if (code == TABULAR_CODE) {
905 // The recursion above does not catch paragraphs in "hidden" cells,
906 // i.e., ones that are part of a multirow or multicolum. So we need
907 // to handle those separately.
908 // This is the cause of bug #9049.
909 InsetTabular * table = iit->asInsetTabular();
910 table->setLayoutForHiddenCells(newtc);
916 vector<docstring> availableSelections(Buffer const * buf)
918 vector<docstring> selList;
922 for (auto const & cut : theCuts) {
923 ParagraphList const & pars = cut.first;
925 for (auto const & para : pars) {
926 Paragraph par(para, 0, 46);
927 // adapt paragraph to current buffer.
928 par.setInsetBuffers(const_cast<Buffer &>(*buf));
929 textSel += par.asString(AS_STR_INSETS);
930 if (textSel.size() > 45) {
931 support::truncateWithEllipsis(textSel,45);
935 selList.push_back(textSel);
942 size_type numberOfSelections()
944 return theCuts.size();
949 void cutSelectionHelper(Cursor & cur, CutStack & cuts, bool realcut, bool putclip)
951 // This doesn't make sense, if there is no selection
952 if (!cur.selection())
955 // OK, we have a selection. This is always between cur.selBegin()
958 if (cur.inTexted()) {
959 Text * text = cur.text();
964 // make sure that the depth behind the selection are restored, too
965 cur.recordUndoSelection();
966 pit_type begpit = cur.selBegin().pit();
967 pit_type endpit = cur.selEnd().pit();
969 int endpos = cur.selEnd().pos();
971 BufferParams const & bp = cur.buffer()->params();
973 copySelectionHelper(*cur.buffer(),
976 cur.selBegin().pos(), endpos,
977 bp.documentClassPtr(), cuts);
978 // Stuff what we got on the clipboard.
979 // Even if there is no selection.
981 putClipboard(cuts[0].first, cuts[0].second,
982 cur.selectionAsString(true, true), bp);
985 if (begpit != endpit)
986 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
988 tie(endpit, endpos) =
989 eraseSelectionHelper(bp, text->paragraphs(), begpit, endpit,
990 cur.selBegin().pos(), endpos);
992 // cutSelection can invalidate the cursor so we need to set
994 // we prefer the end for when tracking changes
998 // need a valid cursor. (Lgb)
999 cur.clearSelection();
1001 // After a cut operation, we must make sure that the Buffer is updated
1002 // because some further operation might need updated label information for
1003 // example. So we cannot just use "cur.forceBufferUpdate()" here.
1004 // This fixes #7071.
1005 cur.buffer()->updateBuffer();
1007 // tell tabular that a recent copy happened
1008 dirtyTabularStack(false);
1011 if (cur.inMathed()) {
1012 if (cur.selBegin().idx() != cur.selEnd().idx()) {
1013 // The current selection spans more than one cell.
1015 cur.recordUndoInset();
1017 // Record only the current cell to avoid a jumping
1018 // cursor after undo
1023 eraseSelection(cur);
1029 void cutSelection(Cursor & cur, bool realcut)
1031 cutSelectionHelper(cur, theCuts, realcut, true);
1035 void cutSelectionToTemp(Cursor & cur, bool realcut)
1037 cutSelectionHelper(cur, tempCut, realcut, false);
1041 void copySelection(Cursor const & cur)
1043 copySelection(cur, cur.selectionAsString(true, true));
1049 void copyInsetToStack(Cursor const & cur, CutStack & cutstack, Inset * inset)
1053 BufferParams const & bp = cur.buffer()->params();
1054 par.setLayout(bp.documentClass().plainLayout());
1055 Font font(inherit_font, bp.language);
1056 par.insertInset(0, inset, font, Change(Change::UNCHANGED));
1057 pars.push_back(par);
1058 cutstack.push(make_pair(pars, make_pair(bp.documentClassPtr(), bp.authors())));
1064 void copyInset(Cursor const & cur, Inset * inset, docstring const & plaintext)
1066 copyInsetToStack(cur, theCuts, inset);
1068 // stuff the selection onto the X clipboard, from an explicit copy request
1069 BufferParams const & bp = cur.buffer()->params();
1070 putClipboard(theCuts[0].first, theCuts[0].second, plaintext, bp);
1074 void copyInsetToTemp(Cursor const & cur, Inset * inset)
1076 copyInsetToStack(cur, tempCut, inset);
1082 void copySelectionToStack(CursorData const & cur, CutStack & cutstack)
1084 // this doesn't make sense, if there is no selection
1085 if (!cur.selection())
1088 // copySelection can not yet handle the case of cross idx selection
1089 if (cur.selBegin().idx() != cur.selEnd().idx())
1092 if (cur.inTexted()) {
1093 Text * text = cur.text();
1095 // ok we have a selection. This is always between cur.selBegin()
1096 // and sel_end cursor
1097 copySelectionHelper(*cur.buffer(), *text,
1098 cur.selBegin().pit(), cur.selEnd().pit(),
1099 cur.selBegin().pos(), cur.selEnd().pos(),
1100 cur.buffer()->params().documentClassPtr(),
1102 // Reset the dirty_tabular_stack_ flag only when something
1103 // is copied to the clipboard (not to the selectionBuffer).
1104 if (&cutstack == &theCuts)
1105 dirtyTabularStack(false);
1108 if (cur.inMathed()) {
1109 //lyxerr << "copySelection in mathed" << endl;
1112 BufferParams const & bp = cur.buffer()->params();
1113 // FIXME This should be the plain layout...right?
1114 par.setLayout(bp.documentClass().plainLayout());
1115 // For pasting into text, we set the language to the paragraph language
1116 // (rather than the default_language which is always English; see #2596)
1117 par.insert(0, grabSelection(cur), Font(sane_font, par.getParLanguage(bp)),
1118 Change(Change::UNCHANGED));
1119 pars.push_back(par);
1120 cutstack.push(make_pair(pars, make_pair(bp.documentClassPtr(), bp.authors())));
1127 void copySelectionToStack()
1129 if (!selectionBuffer.empty())
1130 theCuts.push(selectionBuffer[0]);
1134 void copySelectionToTemp(Cursor const & cur)
1136 copySelectionToStack(cur, tempCut);
1140 void copySelection(Cursor const & cur, docstring const & plaintext)
1142 // In tablemode, because copy and paste actually use a special table stack,
1143 // we need to go through the cells and collect the paragraphs.
1144 // In math matrices, we generate a plain text version.
1145 if (cur.selBegin().idx() != cur.selEnd().idx()) {
1147 BufferParams const & bp = cur.buffer()->params();
1148 if (cur.inMathed()) {
1150 par.setLayout(bp.documentClass().plainLayout());
1151 // Replace (column-separating) tabs by space (#4449)
1152 docstring const clean_text = subst(plaintext, '\t', ' ');
1153 // For pasting into text, we set the language to the paragraph language
1154 // (rather than the default_language which is always English; see #11898)
1155 par.insert(0, clean_text, Font(sane_font, par.getParLanguage(bp)),
1156 Change(Change::UNCHANGED));
1157 pars.push_back(par);
1159 // Get paragraphs from all cells
1160 InsetTabular * table = cur.inset().asInsetTabular();
1161 LASSERT(table, return);
1162 ParagraphList tplist = table->asParList(cur.selBegin().idx(), cur.selEnd().idx());
1163 for (auto & cpar : tplist) {
1164 cpar.setLayout(bp.documentClass().plainLayout());
1165 pars.push_back(cpar);
1166 // since the pars are merged later, we separate them by blank
1168 epar.insert(0, from_ascii(" "), Font(sane_font, epar.getParLanguage(bp)),
1169 Change(Change::UNCHANGED));
1170 pars.push_back(epar);
1172 // remove last empty par
1174 // merge all paragraphs to one
1175 while (pars.size() > 1)
1176 mergeParagraph(bp, pars, 0);
1178 theCuts.push(make_pair(pars, make_pair(bp.documentClassPtr(), bp.authors())));
1180 copySelectionToStack(cur, theCuts);
1183 // stuff the selection onto the X clipboard, from an explicit copy request
1184 putClipboard(theCuts[0].first, theCuts[0].second, plaintext,
1185 cur.buffer()->params());
1189 void saveSelection(Cursor const & cur)
1191 // This function is called, not when a selection is formed, but when
1192 // a selection is cleared. Therefore, multiple keyboard selection
1193 // will not repeatively trigger this function (bug 3877).
1195 && cur.selBegin() == cur.bv().cursor().selBegin()
1196 && cur.selEnd() == cur.bv().cursor().selEnd()) {
1197 LYXERR(Debug::SELECTION, "saveSelection: '" << cur.selectionAsString(true, true) << "'");
1198 copySelectionToStack(cur, selectionBuffer);
1205 return !selectionBuffer.empty();
1209 void clearSelection()
1211 selectionBuffer.clear();
1215 void clearCutStack()
1222 docstring selection(size_t sel_index, DocInfoPair docinfo, bool for_math)
1224 if (sel_index >= theCuts.size())
1227 unique_ptr<Buffer> buffer(copyToTempBuffer(theCuts[sel_index].first,
1232 int options = AS_STR_INSETS | AS_STR_NEWLINES;
1234 options |= AS_STR_MATHED;
1236 return buffer->paragraphs().back().asString(options);
1240 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
1241 DocumentClassConstPtr docclass, AuthorList const & authors,
1242 ErrorList & errorList,
1243 cap::BranchAction branchAction)
1245 // Copy authors to the params. We need those pointers.
1246 for (Author const & a : authors)
1247 cur.buffer()->params().authors().record(a);
1249 if (cur.inTexted()) {
1250 Text * text = cur.text();
1253 PasteReturnValue prv =
1254 pasteSelectionHelper(cur, parlist, docclass, branchAction, errorList);
1255 cur.forceBufferUpdate();
1256 cur.clearSelection();
1257 text->setCursor(cur, prv.pit, prv.pos);
1260 // mathed is handled in InsetMathNest/InsetMathGrid
1261 LATTEST(!cur.inMathed());
1265 bool pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
1267 // this does not make sense, if there is nothing to paste
1268 if (!checkPastePossible(sel_index))
1272 pasteParagraphList(cur, theCuts[sel_index].first,
1273 theCuts[sel_index].second.first, theCuts[sel_index].second.second,
1274 errorList, BRANCH_ASK);
1279 bool pasteFromTemp(Cursor & cur, ErrorList & errorList)
1281 // this does not make sense, if there is nothing to paste
1282 if (tempCut.empty() || tempCut[0].first.empty())
1286 pasteParagraphList(cur, tempCut[0].first,
1287 tempCut[0].second.first, tempCut[0].second.second,
1288 errorList, BRANCH_IGNORE);
1293 bool pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs,
1294 Clipboard::TextType type)
1296 // Use internal clipboard if it is the most recent one
1297 // This overrides asParagraphs and type on purpose!
1298 if (theClipboard().isInternal())
1299 return pasteFromStack(cur, errorList, 0);
1301 // First try LyX format
1302 if ((type == Clipboard::LyXTextType ||
1303 type == Clipboard::LyXOrPlainTextType ||
1304 type == Clipboard::AnyTextType) &&
1305 theClipboard().hasTextContents(Clipboard::LyXTextType)) {
1306 string lyx = theClipboard().getAsLyX();
1308 Buffer buffer(string(), false);
1309 buffer.setInternal(true);
1310 buffer.setUnnamed(true);
1311 if (buffer.readString(lyx)) {
1313 pasteParagraphList(cur, buffer.paragraphs(),
1314 buffer.params().documentClassPtr(),
1315 buffer.params().authors(),
1322 // Then try TeX and HTML
1323 Clipboard::TextType types[2] = {Clipboard::HtmlTextType, Clipboard::LaTeXTextType};
1324 string names[2] = {"html", "latexclipboard"};
1325 for (int i = 0; i < 2; ++i) {
1326 if (type != types[i] && type != Clipboard::AnyTextType)
1328 bool available = theClipboard().hasTextContents(types[i]);
1330 // If a specific type was explicitly requested, try to
1331 // interpret plain text: The user told us that the clipboard
1332 // contents is in the desired format
1333 if (!available && type == types[i]) {
1334 types[i] = Clipboard::PlainTextType;
1335 available = theClipboard().hasTextContents(types[i]);
1339 docstring text = theClipboard().getAsText(types[i]);
1340 available = !text.empty();
1342 Buffer buffer(string(), false);
1343 buffer.setInternal(true);
1344 buffer.setUnnamed(true);
1345 buffer.params() = cur.buffer()->params();
1346 available = buffer.importString(names[i], text, errorList);
1348 available = !buffer.paragraphs().empty();
1349 if (available && !buffer.paragraphs()[0].empty()) {
1350 // TeX2lyx (also used in the HTML chain) assumes English as document language
1351 // if no language is explicitly set (as is the case here).
1352 // We thus reset the temp buffer's language to the context language
1353 buffer.changeLanguage(buffer.language(), cur.getFont().language());
1355 pasteParagraphList(cur, buffer.paragraphs(),
1356 buffer.params().documentClassPtr(),
1357 buffer.params().authors(),
1365 // Then try plain text
1366 docstring const text = theClipboard().getAsText(Clipboard::PlainTextType);
1371 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1373 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1374 cur.forceBufferUpdate();
1379 void pasteSimpleText(Cursor & cur, bool asParagraphs)
1382 // Use internal clipboard if it is the most recent one
1383 if (theClipboard().isInternal()) {
1384 if (!checkPastePossible(0))
1387 ParagraphList const & pars = theCuts[0].first;
1388 ParagraphList::const_iterator it = pars.begin();
1389 for (; it != pars.end(); ++it) {
1390 if (it != pars.begin())
1392 text += (*it).asString();
1394 asParagraphs = false;
1396 // Then try plain text
1397 text = theClipboard().getAsText(Clipboard::PlainTextType);
1404 cutSelection(cur, false);
1406 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1408 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1412 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
1413 Clipboard::GraphicsType preferedType)
1415 LASSERT(theClipboard().hasGraphicsContents(preferedType), return);
1417 // get picture from clipboard
1418 FileName filename = theClipboard().getAsGraphics(cur, preferedType);
1419 if (filename.empty())
1422 // create inset for graphic
1423 InsetGraphics * inset = new InsetGraphics(cur.buffer());
1424 InsetGraphicsParams params;
1425 params.filename = support::DocFileName(filename.absFileName(), false);
1426 inset->setParams(params);
1432 void pasteSelection(Cursor & cur, ErrorList & errorList)
1434 if (selectionBuffer.empty())
1437 pasteParagraphList(cur, selectionBuffer[0].first,
1438 selectionBuffer[0].second.first,
1439 selectionBuffer[0].second.second,
1444 void replaceSelectionWithString(Cursor & cur, docstring const & str)
1447 DocIterator selbeg = cur.selectionBegin();
1449 // Get font setting before we cut, we need a copy here, not a bare reference.
1451 selbeg.paragraph().getFontSettings(cur.buffer()->params(), selbeg.pos());
1453 // Insert the new string
1454 pos_type pos = cur.selEnd().pos();
1455 Paragraph & par = cur.selEnd().paragraph();
1456 for (auto const & c : str) {
1457 par.insertChar(pos, c, font, cur.buffer()->params().track_changes);
1461 // Cut the selection
1462 cutSelection(cur, false);
1466 void replaceSelection(Cursor & cur)
1468 if (cur.selection())
1469 cutSelection(cur, false);
1473 void eraseSelection(Cursor & cur)
1475 //lyxerr << "cap::eraseSelection begin: " << cur << endl;
1476 CursorSlice const & i1 = cur.selBegin();
1477 CursorSlice const & i2 = cur.selEnd();
1478 if (!i1.asInsetMath()) {
1479 LYXERR0("Can't erase this selection");
1485 InsetMath * p = i1.asInsetMath();
1486 if (i1.idx() == i2.idx()) {
1487 i1.cell().erase(i1.pos(), i2.pos());
1488 // We may have deleted i1.cell(cur.pos()).
1489 // Make sure that pos is valid.
1490 if (cur.pos() > cur.lastpos())
1491 cur.pos() = cur.lastpos();
1492 } else if (p->nrows() > 0 && p->ncols() > 0) {
1493 // This is a grid, delete a nice square region
1496 region(i1, i2, r1, r2, c1, c2);
1497 for (row_type row = r1; row <= r2; ++row)
1498 for (col_type col = c1; col <= c2; ++col)
1499 p->cell(p->index(row, col)).clear();
1500 // We've deleted the whole cell. Only pos 0 is valid.
1503 idx_type idx1 = i1.idx();
1504 idx_type idx2 = i2.idx();
1507 for (idx_type idx = idx1 ; idx <= idx2; ++idx)
1508 p->cell(idx).clear();
1509 // We've deleted the whole cell. Only pos 0 is valid.
1513 // need a valid cursor. (Lgb)
1514 cur.clearSelection();
1515 //lyxerr << "cap::eraseSelection end: " << cur << endl;
1519 void selDel(Cursor & cur)
1521 //lyxerr << "cap::selDel" << endl;
1522 if (cur.selection())
1523 eraseSelection(cur);
1527 void selClearOrDel(Cursor & cur)
1529 //lyxerr << "cap::selClearOrDel" << endl;
1530 if (lyxrc.auto_region_delete)
1533 cur.selection(false);
1537 docstring grabSelection(CursorData const & cur)
1539 if (!cur.selection())
1543 // grab selection by glueing multiple cells together. This is not what
1544 // we want because selections spanning multiple cells will get "&" and "\\"
1547 for (DocIterator dit = cur.selectionBegin();
1548 dit != cur.selectionEnd(); dit.forwardPos())
1549 os << asString(dit.cell());
1553 CursorSlice i1 = cur.selBegin();
1554 CursorSlice i2 = cur.selEnd();
1556 if (i1.idx() == i2.idx()) {
1557 if (i1.inset().asInsetMath()) {
1558 MathData::const_iterator it = i1.cell().begin();
1559 Buffer * buf = cur.buffer();
1560 return asString(MathData(buf, it + i1.pos(), it + i2.pos()));
1562 return from_ascii("unknown selection 1");
1568 region(i1, i2, r1, r2, c1, c2);
1571 if (i1.inset().asInsetMath()) {
1572 for (row_type row = r1; row <= r2; ++row) {
1575 for (col_type col = c1; col <= c2; ++col) {
1578 data += asString(i1.asInsetMath()->
1579 cell(i1.asInsetMath()->index(row, col)));
1583 data = from_ascii("unknown selection 2");
1589 void dirtyTabularStack(bool b)
1591 dirty_tabular_stack_ = b;
1595 bool tabularStackDirty()
1597 return dirty_tabular_stack_;