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 target_empty = pars[pit].empty();
293 // Use the paste content's layout, if...
294 bool const paste_layout =
295 // if target paragraph is empty
297 // ... and its layout is default
298 && (pars[pit].layout() == defaultLayout
300 || pars[pit].layout() == plainLayout
301 // ... or the paste content spans several paragraphs
302 || insertion.size() > 1))
303 // or if pasting is done at the beginning of paragraph
305 // and the paste content spans several paragraphs
306 && insertion.size() > 1);
308 // Give the first paragraph to insert the same layout as the
310 insertion.begin()->makeSameLayout(pars[pit]);
312 // Prepare the paragraphs and insets for insertion.
313 insertion.swap(in.paragraphs());
315 InsetIterator const i_end = end(in);
316 for (InsetIterator it = begin(in); it != i_end; ++it) {
317 // Even though this will also be done later, it has to be done here
318 // since some inset might try to access the buffer() member.
319 it->setBuffer(const_cast<Buffer &>(buffer));
320 switch (it->lyxCode()) {
322 case MATH_HULL_CODE: {
323 // check for equation labels and resolve duplicates
324 InsetMathHull * ins = it->asInsetMath()->asHullInset();
325 std::vector<InsetLabel *> labels = ins->getLabels();
326 for (size_t i = 0; i != labels.size(); ++i) {
329 InsetLabel * lab = labels[i];
330 docstring const oldname = lab->getParam("name");
331 lab->updateLabel(oldname, in_active_inset);
332 // We need to update the buffer reference cache.
334 docstring const newname = lab->getParam("name");
335 if (oldname == newname)
337 // adapt the references
338 for (InsetIterator itt = begin(in);
339 itt != i_end; ++itt) {
340 if (itt->lyxCode() == REF_CODE) {
341 InsetCommand * ref = itt->asInsetCommand();
342 if (ref->getParam("reference") == oldname)
343 ref->setParam("reference", newname);
344 } else if (itt->lyxCode() == MATH_REF_CODE) {
345 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
346 // this is necessary to prevent an uninitialized
347 // buffer when the RefInset is in a MathBox.
348 // FIXME audit setBuffer calls
349 mi->setBuffer(const_cast<Buffer &>(buffer));
350 if (mi->getTarget() == oldname)
351 mi->changeTarget(newname);
359 // check for duplicates
360 InsetLabel & lab = static_cast<InsetLabel &>(*it);
361 docstring const oldname = lab.getParam("name");
362 lab.updateLabel(oldname, in_active_inset);
363 // We need to update the buffer reference cache.
365 docstring const newname = lab.getParam("name");
366 if (oldname == newname)
368 // adapt the references
369 for (InsetIterator itt = begin(in); itt != i_end; ++itt) {
370 if (itt->lyxCode() == REF_CODE) {
371 InsetCommand & ref = static_cast<InsetCommand &>(*itt);
372 if (ref.getParam("reference") == oldname)
373 ref.setParam("reference", newname);
374 } else if (itt->lyxCode() == MATH_REF_CODE) {
375 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
376 // this is necessary to prevent an uninitialized
377 // buffer when the RefInset is in a MathBox.
378 // FIXME audit setBuffer calls
379 mi->setBuffer(const_cast<Buffer &>(buffer));
380 if (mi->getTarget() == oldname)
381 mi->changeTarget(newname);
388 InsetInclude & inc = static_cast<InsetInclude &>(*it);
390 // We need to update the list of included files.
396 InsetCitation & cit = static_cast<InsetCitation &>(*it);
397 // This actually only needs to be done if the cite engine
398 // differs, but we do it in general.
400 // We need to update the list of citations.
406 // check for duplicates
407 InsetBibitem & bib = static_cast<InsetBibitem &>(*it);
408 docstring const oldkey = bib.getParam("key");
409 bib.updateCommand(oldkey, false);
410 // We need to update the buffer reference cache.
412 docstring const newkey = bib.getParam("key");
413 if (oldkey == newkey)
415 // adapt the references
416 for (InsetIterator itt = begin(in);
417 itt != i_end; ++itt) {
418 if (itt->lyxCode() == CITE_CODE) {
419 InsetCommand * ref = itt->asInsetCommand();
420 if (ref->getParam("key") == oldkey)
421 ref->setParam("key", newkey);
428 // check if branch is known to target buffer
430 InsetBranch & br = static_cast<InsetBranch &>(*it);
431 docstring const name = br.branch();
434 bool const is_child = (&buffer != buffer.masterBuffer());
435 BranchList branchlist = buffer.params().branchlist();
436 if ((!is_child && branchlist.find(name))
437 || (is_child && (branchlist.find(name)
438 || buffer.masterBuffer()->params().branchlist().find(name))))
440 switch(branchAction) {
441 case cap::BRANCH_ADD: {
442 // This is for a temporary buffer, so simply create the branch.
443 // Must not use lyx::dispatch(), since tmpbuffer has no view.
445 const_cast<Buffer&>(buffer).dispatch(FuncRequest(LFUN_BRANCH_ADD, name), dr);
448 case cap::BRANCH_ASK: {
449 docstring text = bformat(
450 _("The pasted branch \"%1$s\" is undefined.\n"
451 "Do you want to add it to the document's branch list?"),
453 if (frontend::Alert::prompt(_("Unknown branch"),
454 text, 0, 1, _("&Add"), _("&Don't Add")) != 0)
456 lyx::dispatch(FuncRequest(LFUN_BRANCH_ADD, name));
459 case cap::BRANCH_IGNORE:
462 // We need to update the list of branches.
471 insertion.swap(in.paragraphs());
473 // Split the paragraph for inserting the buf if necessary.
475 breakParagraphConservative(buffer.params(), pars, pit, pos);
477 // If multiple paragraphs are inserted before the target paragraph,
478 // the cursor is now in a new paragraph before it,
479 // so use layout from paste content in that case.
480 if (pos == 0 && insertion.size() > 1)
481 pars[pit].makeSameLayout(* insertion.begin());
485 pars.insert(pars.iterator_at(pit),
486 insertion.begin(), insertion.end());
488 // merge the empty par with the last par of the insertion
489 mergeParagraph(buffer.params(), pars,
490 pit + insertion.size() - 1);
492 pars.insert(pars.iterator_at(pit + 1),
493 insertion.begin(), insertion.end());
495 // merge the first par of the insertion with the current par
496 mergeParagraph(buffer.params(), pars, pit);
499 // Store the new cursor position.
500 pit_type last_paste = pit + insertion.size() - 1;
501 pit_type startpit = pit;
503 pos = pars[last_paste].size();
505 // FIXME Should we do it here, or should we let updateBuffer() do it?
506 // Set paragraph buffers. It's important to do this right away
507 // before something calls Inset::buffer() and causes a crash.
508 for (pit_type p = startpit; p <= pit; ++p)
509 pars[p].setInsetBuffers(const_cast<Buffer &>(buffer));
511 // Join (conditionally) last pasted paragraph with next one, i.e.,
512 // the tail of the spliced document paragraph
513 if (!target_empty && last_paste + 1 != pit_type(pars.size())) {
514 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
515 mergeParagraph(buffer.params(), pars, last_paste);
516 } else if (pars[last_paste + 1].empty()) {
517 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
518 mergeParagraph(buffer.params(), pars, last_paste);
519 } else if (pars[last_paste].empty()) {
520 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
521 mergeParagraph(buffer.params(), pars, last_paste);
523 pars[last_paste + 1].stripLeadingSpaces(buffer.params().track_changes);
528 return PasteReturnValue(pit, pos, need_update);
532 PitPosPair eraseSelectionHelper(BufferParams const & params,
533 ParagraphList & pars,
534 pit_type startpit, pit_type endpit,
535 int startpos, int endpos)
537 // Start of selection is really invalid.
538 if (startpit == pit_type(pars.size()) ||
539 (startpos > pars[startpit].size()))
540 return PitPosPair(endpit, endpos);
542 // Start and end is inside same paragraph
543 if (endpit == pit_type(pars.size()) || startpit == endpit) {
544 endpos -= pars[startpit].eraseChars(startpos, endpos, params.track_changes);
545 return PitPosPair(endpit, endpos);
548 for (pit_type pit = startpit; pit != endpit + 1;) {
549 pos_type const left = (pit == startpit ? startpos : 0);
550 pos_type right = (pit == endpit ? endpos : pars[pit].size() + 1);
551 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.track_changes);
553 // Logically erase only, including the end-of-paragraph character
554 pars[pit].eraseChars(left, right, params.track_changes);
556 // Separate handling of paragraph break:
557 if (merge && pit != endpit &&
559 || pars[pit].hasSameLayout(pars[endpit])
560 || pars[endpit].size() == endpos)) {
561 if (pit + 1 == endpit)
562 endpos += pars[pit].size();
563 mergeParagraph(params, pars, pit);
569 // Ensure legal cursor pos:
572 return PitPosPair(endpit, endpos);
576 Buffer * copyToTempBuffer(ParagraphList const & paragraphs, DocumentClassConstPtr docclass)
578 // This used to need to be static to avoid a memory leak. It no longer needs
579 // to be so, but the alternative is to construct a new one of these (with a
580 // new temporary directory, etc) every time, and then to destroy it. So maybe
581 // it's worth just keeping this one around.
582 static TempFile tempfile("clipboard.internal");
583 tempfile.setAutoRemove(false);
584 // The initialization of staticbuffer is thread-safe. Using a lambda
585 // guarantees that the properties are set only once.
586 static Buffer * staticbuffer = [&](){
588 theBufferList().newInternalBuffer(tempfile.name().absFileName());
590 b->inset().setBuffer(*b);
591 //initialize staticbuffer with b
594 // Use a clone for the complicated stuff so that we do not need to clean
595 // up in order to avoid a crash.
596 Buffer * buffer = staticbuffer->cloneBufferOnly();
597 LASSERT(buffer, return nullptr);
599 // This needs doing every time.
600 // Since setDocumentClass() causes deletion of the old document class
601 // we need to reset all layout pointers in paragraphs (otherwise they
602 // would be dangling).
603 ParIterator const end = buffer->par_iterator_end();
604 for (ParIterator it = buffer->par_iterator_begin(); it != end; ++it) {
605 docstring const name = it->layout().name();
606 if (docclass->hasLayout(name))
607 it->setLayout((*docclass)[name]);
609 it->setPlainOrDefaultLayout(*docclass);
611 buffer->params().setDocumentClass(docclass);
613 // we will use pasteSelectionHelper to copy the paragraphs into the
614 // temporary Buffer, since it does a lot of things to fix them up.
615 DocIterator dit = doc_iterator_begin(buffer, &buffer->inset());
617 pasteSelectionHelper(dit, paragraphs, docclass, cap::BRANCH_ADD, el);
623 void putClipboard(ParagraphList const & paragraphs,
624 DocInfoPair docinfo, docstring const & plaintext,
625 BufferParams const & bp)
627 Buffer * buffer = copyToTempBuffer(paragraphs, docinfo.first);
628 if (!buffer) // already asserted in copyToTempBuffer()
631 // We don't want to produce images that are not used. Therefore,
632 // output formulas as MathML. Even if this is not understood by all
633 // applications, the number that can parse it should go up in the future.
634 buffer->params().html_math_output = BufferParams::MathML;
636 // Copy authors to the params. We need those pointers.
637 for (Author const & a : bp.authors())
638 buffer->params().authors().record(a);
640 // Make sure MarkAsExporting is deleted before buffer is
642 // The Buffer is being used to export. This is necessary so that the
643 // updateMacros call will record the needed information.
644 MarkAsExporting mex(buffer);
646 buffer->updateBuffer(Buffer::UpdateMaster, OutputUpdate);
647 buffer->updateMacros();
648 buffer->updateMacroInstances(OutputUpdate);
653 if (buffer->write(oslyx))
657 odocstringstream oshtml;
658 OutputParams runparams(encodings.fromLyXName("utf8"));
659 // We do not need to produce images, etc.
660 runparams.dryrun = true;
661 // We are not interested in errors (bug 8866)
662 runparams.silent = true;
663 buffer->writeLyXHTMLSource(oshtml, runparams, Buffer::FullSource);
665 theClipboard().put(lyx, oshtml.str(), plaintext);
673 /// return true if the whole ParagraphList is deleted
674 static bool isFullyDeleted(ParagraphList const & pars)
676 pit_type const pars_size = static_cast<pit_type>(pars.size());
678 // check all paragraphs
679 for (pit_type pit = 0; pit < pars_size; ++pit) {
680 if (!pars[pit].empty()) // prevent assertion failure
681 if (!pars[pit].isDeleted(0, pars[pit].size()))
688 void copySelectionHelper(Buffer const & buf, Text const & text,
689 pit_type startpit, pit_type endpit,
690 int start, int end, DocumentClassConstPtr dc, CutStack & cutstack)
692 ParagraphList const & pars = text.paragraphs();
694 // In most of these cases, we can try to recover.
695 LASSERT(0 <= start, start = 0);
696 LASSERT(start <= pars[startpit].size(), start = pars[startpit].size());
697 LASSERT(0 <= end, end = 0);
698 LASSERT(end <= pars[endpit].size(), end = pars[endpit].size());
699 LASSERT(startpit != endpit || start <= end, return);
701 // Clone the paragraphs within the selection.
702 ParagraphList copy_pars(pars.iterator_at(startpit),
703 pars.iterator_at(endpit + 1));
705 // Remove the end of the last paragraph; afterwards, remove the
706 // beginning of the first paragraph. Keep this order - there may only
707 // be one paragraph! Do not track deletions here; this is an internal
708 // action not visible to the user
710 Paragraph & back = copy_pars.back();
711 back.eraseChars(end, back.size(), false);
712 Paragraph & front = copy_pars.front();
713 front.eraseChars(0, start, false);
715 for (auto & par : copy_pars) {
716 // Since we have a copy of the paragraphs, the insets
717 // do not have a proper buffer reference. It makes
718 // sense to add them temporarily, because the
719 // operations below depend on that (acceptChanges included).
720 par.setInsetBuffers(const_cast<Buffer &>(buf));
721 // PassThru paragraphs have the Language
722 // latex_language. This is invalid for others, so we
723 // need to change it to the buffer language.
724 if (par.isPassThru())
725 par.changeLanguage(buf.params(),
726 latex_language, buf.language());
729 // do not copy text (also nested in insets) which is marked as
730 // deleted, unless the whole selection was deleted
731 if (!lyxrc.ct_markup_copied) {
732 if (!isFullyDeleted(copy_pars))
733 acceptChanges(copy_pars, buf.params());
735 rejectChanges(copy_pars, buf.params());
739 // do some final cleanup now, to make sure that the paragraphs
740 // are not linked to something else.
741 for (auto & par : copy_pars) {
743 par.setInsetOwner(nullptr);
746 cutstack.push(make_pair(copy_pars, make_pair(dc, buf.params().authors())));
754 void region(CursorSlice const & i1, CursorSlice const & i2,
755 row_type & r1, row_type & r2,
756 col_type & c1, col_type & c2)
758 Inset const & p = i1.inset();
759 c1 = p.col(i1.idx());
760 c2 = p.col(i2.idx());
763 r1 = p.row(i1.idx());
764 r2 = p.row(i2.idx());
770 docstring grabAndEraseSelection(Cursor & cur)
772 if (!cur.selection())
774 docstring res = grabSelection(cur);
780 bool reduceSelectionToOneCell(CursorData & cur)
782 if (!cur.selection() || !cur.inMathed())
785 CursorSlice i1 = cur.selBegin();
786 CursorSlice i2 = cur.selEnd();
787 if (!i1.inset().asInsetMath())
790 // the easy case: do nothing if only one cell is selected
791 if (i1.idx() == i2.idx())
796 cur.top().pos() = cur.top().lastpos();
802 bool multipleCellsSelected(CursorData const & cur)
804 if (!cur.selection() || !cur.inMathed())
807 CursorSlice i1 = cur.selBegin();
808 CursorSlice i2 = cur.selEnd();
809 if (!i1.inset().asInsetMath())
812 if (i1.idx() == i2.idx())
819 void switchBetweenClasses(DocumentClassConstPtr oldone,
820 DocumentClassConstPtr newone, InsetText & in) {
822 switchBetweenClasses(oldone, newone, in, el);
826 void switchBetweenClasses(DocumentClassConstPtr oldone,
827 DocumentClassConstPtr newone, InsetText & in, ErrorList & errorlist)
831 LBUFERR(!in.paragraphs().empty());
832 if (oldone == newone)
835 DocumentClass const & oldtc = *oldone;
836 DocumentClass const & newtc = *newone;
839 ParIterator it = par_iterator_begin(in);
840 ParIterator pend = par_iterator_end(in);
841 // for remembering which layouts we've had to add
842 set<docstring> newlayouts;
843 for (; it != pend; ++it) {
844 docstring const name = it->layout().name();
846 // the pasted text will keep their own layout name. If this layout does
847 // not exist in the new document, it will behave like a standard layout.
848 bool const added_one = newtc.addLayoutIfNeeded(name);
850 newlayouts.insert(name);
852 if (added_one || newlayouts.find(name) != newlayouts.end()) {
854 docstring const s = bformat(_("Layout `%1$s' was not found."), name);
855 errorlist.push_back(ErrorItem(_("Layout Not Found"), s,
856 {it->id(), 0}, {it->id(), -1}));
859 if (in.usePlainLayout())
860 it->setLayout(newtc.plainLayout());
862 it->setLayout(newtc[name]);
865 // character styles and hidden table cells
866 InsetIterator const i_end = end(in);
867 for (InsetIterator iit = begin(in); iit != i_end; ++iit) {
868 InsetCode const code = iit->lyxCode();
869 if (code == FLEX_CODE) {
870 // FIXME: Should we verify all InsetCollapsible?
871 docstring const layoutName = iit->layoutName();
872 docstring const & n = newone->insetLayout(layoutName).name();
873 bool const is_undefined = n.empty() ||
874 n == DocumentClass::plainInsetLayout().name();
875 docstring const & oldn = oldone->insetLayout(layoutName).name();
876 bool const was_undefined = oldn.empty() ||
877 oldn == DocumentClass::plainInsetLayout().name();
878 if (!is_undefined || was_undefined)
881 // The flex inset is undefined in newtc
882 docstring const oldname = from_utf8(oldtc.name());
883 docstring const newname = from_utf8(newtc.name());
885 if (oldname == newname)
886 s = bformat(_("Flex inset %1$s is undefined after "
887 "reloading `%2$s' layout."), layoutName, oldname);
889 s = bformat(_("Flex inset %1$s is undefined because of "
890 "conversion from `%2$s' layout to `%3$s'."),
891 layoutName, oldname, newname);
892 // To warn the user that something had to be done.
893 errorlist.push_back(ErrorItem(
894 _("Undefined flex inset"), s,
895 {iit.paragraph().id(), iit.pos()},
896 {iit.paragraph().id(), iit.pos() + 1}));
897 } else if (code == TABULAR_CODE) {
898 // The recursion above does not catch paragraphs in "hidden" cells,
899 // i.e., ones that are part of a multirow or multicolum. So we need
900 // to handle those separately.
901 // This is the cause of bug #9049.
902 InsetTabular * table = iit->asInsetTabular();
903 table->setLayoutForHiddenCells(newtc);
909 vector<docstring> availableSelections(Buffer const * buf)
911 vector<docstring> selList;
915 for (auto const & cut : theCuts) {
916 ParagraphList const & pars = cut.first;
918 for (auto const & para : pars) {
919 Paragraph par(para, 0, 46);
920 // adapt paragraph to current buffer.
921 par.setInsetBuffers(const_cast<Buffer &>(*buf));
922 textSel += par.asString(AS_STR_INSETS);
923 if (textSel.size() > 45) {
924 support::truncateWithEllipsis(textSel,45);
928 selList.push_back(textSel);
935 size_type numberOfSelections()
937 return theCuts.size();
942 void cutSelectionHelper(Cursor & cur, CutStack & cuts, bool realcut, bool putclip)
944 // This doesn't make sense, if there is no selection
945 if (!cur.selection())
948 // OK, we have a selection. This is always between cur.selBegin()
951 if (cur.inTexted()) {
952 Text * text = cur.text();
957 // make sure that the depth behind the selection are restored, too
958 cur.recordUndoSelection();
959 pit_type begpit = cur.selBegin().pit();
960 pit_type endpit = cur.selEnd().pit();
962 int endpos = cur.selEnd().pos();
964 BufferParams const & bp = cur.buffer()->params();
966 copySelectionHelper(*cur.buffer(),
969 cur.selBegin().pos(), endpos,
970 bp.documentClassPtr(), cuts);
971 // Stuff what we got on the clipboard.
972 // Even if there is no selection.
974 putClipboard(cuts[0].first, cuts[0].second,
975 cur.selectionAsString(true, true), bp);
978 if (begpit != endpit)
979 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
981 tie(endpit, endpos) =
982 eraseSelectionHelper(bp, text->paragraphs(), begpit, endpit,
983 cur.selBegin().pos(), endpos);
985 // cutSelection can invalidate the cursor so we need to set
987 // we prefer the end for when tracking changes
991 // need a valid cursor. (Lgb)
992 cur.clearSelection();
994 // After a cut operation, we must make sure that the Buffer is updated
995 // because some further operation might need updated label information for
996 // example. So we cannot just use "cur.forceBufferUpdate()" here.
998 cur.buffer()->updateBuffer();
1000 // tell tabular that a recent copy happened
1001 dirtyTabularStack(false);
1004 if (cur.inMathed()) {
1005 if (cur.selBegin().idx() != cur.selEnd().idx()) {
1006 // The current selection spans more than one cell.
1008 cur.recordUndoInset();
1010 // Record only the current cell to avoid a jumping
1011 // cursor after undo
1016 eraseSelection(cur);
1022 void cutSelection(Cursor & cur, bool realcut)
1024 cutSelectionHelper(cur, theCuts, realcut, true);
1028 void cutSelectionToTemp(Cursor & cur, bool realcut)
1030 cutSelectionHelper(cur, tempCut, realcut, false);
1034 void copySelection(Cursor const & cur)
1036 copySelection(cur, cur.selectionAsString(true, true));
1042 void copyInsetToStack(Cursor const & cur, CutStack & cutstack, Inset * inset)
1046 BufferParams const & bp = cur.buffer()->params();
1047 par.setLayout(bp.documentClass().plainLayout());
1048 Font font(inherit_font, bp.language);
1049 par.insertInset(0, inset, font, Change(Change::UNCHANGED));
1050 pars.push_back(par);
1051 cutstack.push(make_pair(pars, make_pair(bp.documentClassPtr(), bp.authors())));
1057 void copyInset(Cursor const & cur, Inset * inset, docstring const & plaintext)
1059 copyInsetToStack(cur, theCuts, inset);
1061 // stuff the selection onto the X clipboard, from an explicit copy request
1062 BufferParams const & bp = cur.buffer()->params();
1063 putClipboard(theCuts[0].first, theCuts[0].second, plaintext, bp);
1067 void copyInsetToTemp(Cursor const & cur, Inset * inset)
1069 copyInsetToStack(cur, tempCut, inset);
1075 void copySelectionToStack(CursorData const & cur, CutStack & cutstack)
1077 // this doesn't make sense, if there is no selection
1078 if (!cur.selection())
1081 // copySelection can not yet handle the case of cross idx selection
1082 if (cur.selBegin().idx() != cur.selEnd().idx())
1085 if (cur.inTexted()) {
1086 Text * text = cur.text();
1088 // ok we have a selection. This is always between cur.selBegin()
1089 // and sel_end cursor
1090 copySelectionHelper(*cur.buffer(), *text,
1091 cur.selBegin().pit(), cur.selEnd().pit(),
1092 cur.selBegin().pos(), cur.selEnd().pos(),
1093 cur.buffer()->params().documentClassPtr(),
1095 // Reset the dirty_tabular_stack_ flag only when something
1096 // is copied to the clipboard (not to the selectionBuffer).
1097 if (&cutstack == &theCuts)
1098 dirtyTabularStack(false);
1101 if (cur.inMathed()) {
1102 //lyxerr << "copySelection in mathed" << endl;
1105 BufferParams const & bp = cur.buffer()->params();
1106 // FIXME This should be the plain layout...right?
1107 par.setLayout(bp.documentClass().plainLayout());
1108 // For pasting into text, we set the language to the paragraph language
1109 // (rather than the default_language which is always English; see #2596)
1110 par.insert(0, grabSelection(cur), Font(sane_font, par.getParLanguage(bp)),
1111 Change(Change::UNCHANGED));
1112 pars.push_back(par);
1113 cutstack.push(make_pair(pars, make_pair(bp.documentClassPtr(), bp.authors())));
1120 void copySelectionToStack()
1122 if (!selectionBuffer.empty())
1123 theCuts.push(selectionBuffer[0]);
1127 void copySelectionToTemp(Cursor const & cur)
1129 copySelectionToStack(cur, tempCut);
1133 void copySelection(Cursor const & cur, docstring const & plaintext)
1135 // In tablemode, because copy and paste actually use a special table stack,
1136 // we need to go through the cells and collect the paragraphs.
1137 // In math matrices, we generate a plain text version.
1138 if (cur.selBegin().idx() != cur.selEnd().idx()) {
1140 BufferParams const & bp = cur.buffer()->params();
1141 if (cur.inMathed()) {
1143 par.setLayout(bp.documentClass().plainLayout());
1144 // Replace (column-separating) tabs by space (#4449)
1145 docstring const clean_text = subst(plaintext, '\t', ' ');
1146 // For pasting into text, we set the language to the paragraph language
1147 // (rather than the default_language which is always English; see #11898)
1148 par.insert(0, clean_text, Font(sane_font, par.getParLanguage(bp)),
1149 Change(Change::UNCHANGED));
1150 pars.push_back(par);
1152 // Get paragraphs from all cells
1153 InsetTabular * table = cur.inset().asInsetTabular();
1154 LASSERT(table, return);
1155 ParagraphList tplist = table->asParList(cur.selBegin().idx(), cur.selEnd().idx());
1156 for (auto & cpar : tplist) {
1157 cpar.setLayout(bp.documentClass().plainLayout());
1158 pars.push_back(cpar);
1159 // since the pars are merged later, we separate them by blank
1161 epar.insert(0, from_ascii(" "), Font(sane_font, epar.getParLanguage(bp)),
1162 Change(Change::UNCHANGED));
1163 pars.push_back(epar);
1165 // remove last empty par
1167 // merge all paragraphs to one
1168 while (pars.size() > 1)
1169 mergeParagraph(bp, pars, 0);
1171 theCuts.push(make_pair(pars, make_pair(bp.documentClassPtr(), bp.authors())));
1173 copySelectionToStack(cur, theCuts);
1176 // stuff the selection onto the X clipboard, from an explicit copy request
1177 putClipboard(theCuts[0].first, theCuts[0].second, plaintext,
1178 cur.buffer()->params());
1182 void saveSelection(Cursor const & cur)
1184 // This function is called, not when a selection is formed, but when
1185 // a selection is cleared. Therefore, multiple keyboard selection
1186 // will not repeatively trigger this function (bug 3877).
1188 && cur.selBegin() == cur.bv().cursor().selBegin()
1189 && cur.selEnd() == cur.bv().cursor().selEnd()) {
1190 LYXERR(Debug::SELECTION, "saveSelection: '" << cur.selectionAsString(true, true) << "'");
1191 copySelectionToStack(cur, selectionBuffer);
1198 return !selectionBuffer.empty();
1202 void clearSelection()
1204 selectionBuffer.clear();
1208 void clearCutStack()
1215 docstring selection(size_t sel_index, DocInfoPair docinfo, bool for_math)
1217 if (sel_index >= theCuts.size())
1220 unique_ptr<Buffer> buffer(copyToTempBuffer(theCuts[sel_index].first,
1225 int options = AS_STR_INSETS | AS_STR_NEWLINES;
1227 options |= AS_STR_MATHED;
1229 return buffer->paragraphs().back().asString(options);
1233 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
1234 DocumentClassConstPtr docclass, AuthorList const & authors,
1235 ErrorList & errorList,
1236 cap::BranchAction branchAction)
1238 // Copy authors to the params. We need those pointers.
1239 for (Author const & a : authors)
1240 cur.buffer()->params().authors().record(a);
1242 if (cur.inTexted()) {
1243 Text * text = cur.text();
1246 PasteReturnValue prv =
1247 pasteSelectionHelper(cur, parlist, docclass, branchAction, errorList);
1248 cur.forceBufferUpdate();
1249 cur.clearSelection();
1250 text->setCursor(cur, prv.pit, prv.pos);
1253 // mathed is handled in InsetMathNest/InsetMathGrid
1254 LATTEST(!cur.inMathed());
1258 bool pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
1260 // this does not make sense, if there is nothing to paste
1261 if (!checkPastePossible(sel_index))
1265 pasteParagraphList(cur, theCuts[sel_index].first,
1266 theCuts[sel_index].second.first, theCuts[sel_index].second.second,
1267 errorList, BRANCH_ASK);
1272 bool pasteFromTemp(Cursor & cur, ErrorList & errorList)
1274 // this does not make sense, if there is nothing to paste
1275 if (tempCut.empty() || tempCut[0].first.empty())
1279 pasteParagraphList(cur, tempCut[0].first,
1280 tempCut[0].second.first, tempCut[0].second.second,
1281 errorList, BRANCH_IGNORE);
1286 bool pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs,
1287 Clipboard::TextType type)
1289 // Use internal clipboard if it is the most recent one
1290 // This overrides asParagraphs and type on purpose!
1291 if (theClipboard().isInternal())
1292 return pasteFromStack(cur, errorList, 0);
1294 // First try LyX format
1295 if ((type == Clipboard::LyXTextType ||
1296 type == Clipboard::LyXOrPlainTextType ||
1297 type == Clipboard::AnyTextType) &&
1298 theClipboard().hasTextContents(Clipboard::LyXTextType)) {
1299 string lyx = theClipboard().getAsLyX();
1301 Buffer buffer(string(), false);
1302 buffer.setInternal(true);
1303 buffer.setUnnamed(true);
1304 if (buffer.readString(lyx)) {
1306 pasteParagraphList(cur, buffer.paragraphs(),
1307 buffer.params().documentClassPtr(),
1308 buffer.params().authors(),
1315 // Then try TeX and HTML
1316 Clipboard::TextType types[2] = {Clipboard::HtmlTextType, Clipboard::LaTeXTextType};
1317 string names[2] = {"html", "latexclipboard"};
1318 for (int i = 0; i < 2; ++i) {
1319 if (type != types[i] && type != Clipboard::AnyTextType)
1321 bool available = theClipboard().hasTextContents(types[i]);
1323 // If a specific type was explicitly requested, try to
1324 // interpret plain text: The user told us that the clipboard
1325 // contents is in the desired format
1326 if (!available && type == types[i]) {
1327 types[i] = Clipboard::PlainTextType;
1328 available = theClipboard().hasTextContents(types[i]);
1332 docstring text = theClipboard().getAsText(types[i]);
1333 available = !text.empty();
1335 Buffer buffer(string(), false);
1336 buffer.setInternal(true);
1337 buffer.setUnnamed(true);
1338 buffer.params() = cur.buffer()->params();
1339 available = buffer.importString(names[i], text, errorList);
1341 available = !buffer.paragraphs().empty();
1342 if (available && !buffer.paragraphs()[0].empty()) {
1343 // TeX2lyx (also used in the HTML chain) assumes English as document language
1344 // if no language is explicitly set (as is the case here).
1345 // We thus reset the temp buffer's language to the context language
1346 buffer.changeLanguage(buffer.language(), cur.getFont().language());
1348 pasteParagraphList(cur, buffer.paragraphs(),
1349 buffer.params().documentClassPtr(),
1350 buffer.params().authors(),
1358 // Then try plain text
1359 docstring const text = theClipboard().getAsText(Clipboard::PlainTextType);
1364 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1366 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1367 cur.forceBufferUpdate();
1372 void pasteSimpleText(Cursor & cur, bool asParagraphs)
1375 // Use internal clipboard if it is the most recent one
1376 if (theClipboard().isInternal()) {
1377 if (!checkPastePossible(0))
1380 ParagraphList const & pars = theCuts[0].first;
1381 ParagraphList::const_iterator it = pars.begin();
1382 for (; it != pars.end(); ++it) {
1383 if (it != pars.begin())
1385 text += (*it).asString();
1387 asParagraphs = false;
1389 // Then try plain text
1390 text = theClipboard().getAsText(Clipboard::PlainTextType);
1397 cutSelection(cur, false);
1399 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1401 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1405 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
1406 Clipboard::GraphicsType preferedType)
1408 LASSERT(theClipboard().hasGraphicsContents(preferedType), return);
1410 // get picture from clipboard
1411 FileName filename = theClipboard().getAsGraphics(cur, preferedType);
1412 if (filename.empty())
1415 // create inset for graphic
1416 InsetGraphics * inset = new InsetGraphics(cur.buffer());
1417 InsetGraphicsParams params;
1418 params.filename = support::DocFileName(filename.absFileName(), false);
1419 inset->setParams(params);
1425 void pasteSelection(Cursor & cur, ErrorList & errorList)
1427 if (selectionBuffer.empty())
1430 pasteParagraphList(cur, selectionBuffer[0].first,
1431 selectionBuffer[0].second.first,
1432 selectionBuffer[0].second.second,
1437 void replaceSelectionWithString(Cursor & cur, docstring const & str)
1440 DocIterator selbeg = cur.selectionBegin();
1442 // Get font setting before we cut, we need a copy here, not a bare reference.
1444 selbeg.paragraph().getFontSettings(cur.buffer()->params(), selbeg.pos());
1446 // Insert the new string
1447 pos_type pos = cur.selEnd().pos();
1448 Paragraph & par = cur.selEnd().paragraph();
1449 for (auto const & c : str) {
1450 par.insertChar(pos, c, font, cur.buffer()->params().track_changes);
1454 // Cut the selection
1455 cutSelection(cur, false);
1459 void replaceSelection(Cursor & cur)
1461 if (cur.selection())
1462 cutSelection(cur, false);
1466 void eraseSelection(Cursor & cur)
1468 //lyxerr << "cap::eraseSelection begin: " << cur << endl;
1469 CursorSlice const & i1 = cur.selBegin();
1470 CursorSlice const & i2 = cur.selEnd();
1471 if (!i1.asInsetMath()) {
1472 LYXERR0("Can't erase this selection");
1478 InsetMath * p = i1.asInsetMath();
1479 if (i1.idx() == i2.idx()) {
1480 i1.cell().erase(i1.pos(), i2.pos());
1481 // We may have deleted i1.cell(cur.pos()).
1482 // Make sure that pos is valid.
1483 if (cur.pos() > cur.lastpos())
1484 cur.pos() = cur.lastpos();
1485 } else if (p->nrows() > 0 && p->ncols() > 0) {
1486 // This is a grid, delete a nice square region
1489 region(i1, i2, r1, r2, c1, c2);
1490 for (row_type row = r1; row <= r2; ++row)
1491 for (col_type col = c1; col <= c2; ++col)
1492 p->cell(p->index(row, col)).clear();
1493 // We've deleted the whole cell. Only pos 0 is valid.
1496 idx_type idx1 = i1.idx();
1497 idx_type idx2 = i2.idx();
1500 for (idx_type idx = idx1 ; idx <= idx2; ++idx)
1501 p->cell(idx).clear();
1502 // We've deleted the whole cell. Only pos 0 is valid.
1506 // need a valid cursor. (Lgb)
1507 cur.clearSelection();
1508 //lyxerr << "cap::eraseSelection end: " << cur << endl;
1512 void selDel(Cursor & cur)
1514 //lyxerr << "cap::selDel" << endl;
1515 if (cur.selection())
1516 eraseSelection(cur);
1520 void selClearOrDel(Cursor & cur)
1522 //lyxerr << "cap::selClearOrDel" << endl;
1523 if (lyxrc.auto_region_delete)
1526 cur.selection(false);
1530 docstring grabSelection(CursorData const & cur)
1532 if (!cur.selection())
1536 // grab selection by glueing multiple cells together. This is not what
1537 // we want because selections spanning multiple cells will get "&" and "\\"
1540 for (DocIterator dit = cur.selectionBegin();
1541 dit != cur.selectionEnd(); dit.forwardPos())
1542 os << asString(dit.cell());
1546 CursorSlice i1 = cur.selBegin();
1547 CursorSlice i2 = cur.selEnd();
1549 if (i1.idx() == i2.idx()) {
1550 if (i1.inset().asInsetMath()) {
1551 MathData::const_iterator it = i1.cell().begin();
1552 Buffer * buf = cur.buffer();
1553 return asString(MathData(buf, it + i1.pos(), it + i2.pos()));
1555 return from_ascii("unknown selection 1");
1561 region(i1, i2, r1, r2, c1, c2);
1564 if (i1.inset().asInsetMath()) {
1565 for (row_type row = r1; row <= r2; ++row) {
1568 for (col_type col = c1; col <= c2; ++col) {
1571 data += asString(i1.asInsetMath()->
1572 cell(i1.asInsetMath()->index(row, col)));
1576 data = from_ascii("unknown selection 2");
1582 void dirtyTabularStack(bool b)
1584 dirty_tabular_stack_ = b;
1588 bool tabularStackDirty()
1590 return dirty_tabular_stack_;