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));
1040 void copyInset(Cursor const & cur, Inset * inset, docstring const & plaintext)
1044 BufferParams const & bp = cur.buffer()->params();
1045 par.setLayout(bp.documentClass().plainLayout());
1046 Font font(inherit_font, bp.language);
1047 par.insertInset(0, inset, font, Change(Change::UNCHANGED));
1048 pars.push_back(par);
1049 theCuts.push(make_pair(pars, make_pair(bp.documentClassPtr(), bp.authors())));
1051 // stuff the selection onto the X clipboard, from an explicit copy request
1052 putClipboard(theCuts[0].first, theCuts[0].second, plaintext, bp);
1058 void copySelectionToStack(CursorData const & cur, CutStack & cutstack)
1060 // this doesn't make sense, if there is no selection
1061 if (!cur.selection())
1064 // copySelection can not yet handle the case of cross idx selection
1065 if (cur.selBegin().idx() != cur.selEnd().idx())
1068 if (cur.inTexted()) {
1069 Text * text = cur.text();
1071 // ok we have a selection. This is always between cur.selBegin()
1072 // and sel_end cursor
1073 copySelectionHelper(*cur.buffer(), *text,
1074 cur.selBegin().pit(), cur.selEnd().pit(),
1075 cur.selBegin().pos(), cur.selEnd().pos(),
1076 cur.buffer()->params().documentClassPtr(),
1078 // Reset the dirty_tabular_stack_ flag only when something
1079 // is copied to the clipboard (not to the selectionBuffer).
1080 if (&cutstack == &theCuts)
1081 dirtyTabularStack(false);
1084 if (cur.inMathed()) {
1085 //lyxerr << "copySelection in mathed" << endl;
1088 BufferParams const & bp = cur.buffer()->params();
1089 // FIXME This should be the plain layout...right?
1090 par.setLayout(bp.documentClass().plainLayout());
1091 // For pasting into text, we set the language to the paragraph language
1092 // (rather than the default_language which is always English; see #2596)
1093 par.insert(0, grabSelection(cur), Font(sane_font, par.getParLanguage(bp)),
1094 Change(Change::UNCHANGED));
1095 pars.push_back(par);
1096 cutstack.push(make_pair(pars, make_pair(bp.documentClassPtr(), bp.authors())));
1103 void copySelectionToStack()
1105 if (!selectionBuffer.empty())
1106 theCuts.push(selectionBuffer[0]);
1110 void copySelectionToTemp(Cursor const & cur)
1112 copySelectionToStack(cur, tempCut);
1116 void copySelection(Cursor const & cur, docstring const & plaintext)
1118 // In tablemode, because copy and paste actually use a special table stack,
1119 // we need to go through the cells and collect the paragraphs.
1120 // In math matrices, we generate a plain text version.
1121 if (cur.selBegin().idx() != cur.selEnd().idx()) {
1123 BufferParams const & bp = cur.buffer()->params();
1124 if (cur.inMathed()) {
1126 par.setLayout(bp.documentClass().plainLayout());
1127 // Replace (column-separating) tabs by space (#4449)
1128 docstring const clean_text = subst(plaintext, '\t', ' ');
1129 // For pasting into text, we set the language to the paragraph language
1130 // (rather than the default_language which is always English; see #11898)
1131 par.insert(0, clean_text, Font(sane_font, par.getParLanguage(bp)),
1132 Change(Change::UNCHANGED));
1133 pars.push_back(par);
1135 // Get paragraphs from all cells
1136 InsetTabular * table = cur.inset().asInsetTabular();
1137 LASSERT(table, return);
1138 ParagraphList tplist = table->asParList(cur.selBegin().idx(), cur.selEnd().idx());
1139 for (auto & cpar : tplist) {
1140 cpar.setLayout(bp.documentClass().plainLayout());
1141 pars.push_back(cpar);
1142 // since the pars are merged later, we separate them by blank
1144 epar.insert(0, from_ascii(" "), Font(sane_font, epar.getParLanguage(bp)),
1145 Change(Change::UNCHANGED));
1146 pars.push_back(epar);
1148 // remove last empty par
1150 // merge all paragraphs to one
1151 while (pars.size() > 1)
1152 mergeParagraph(bp, pars, 0);
1154 theCuts.push(make_pair(pars, make_pair(bp.documentClassPtr(), bp.authors())));
1156 copySelectionToStack(cur, theCuts);
1159 // stuff the selection onto the X clipboard, from an explicit copy request
1160 putClipboard(theCuts[0].first, theCuts[0].second, plaintext,
1161 cur.buffer()->params());
1165 void saveSelection(Cursor const & cur)
1167 // This function is called, not when a selection is formed, but when
1168 // a selection is cleared. Therefore, multiple keyboard selection
1169 // will not repeatively trigger this function (bug 3877).
1171 && cur.selBegin() == cur.bv().cursor().selBegin()
1172 && cur.selEnd() == cur.bv().cursor().selEnd()) {
1173 LYXERR(Debug::SELECTION, "saveSelection: '" << cur.selectionAsString(true, true) << "'");
1174 copySelectionToStack(cur, selectionBuffer);
1181 return !selectionBuffer.empty();
1185 void clearSelection()
1187 selectionBuffer.clear();
1191 void clearCutStack()
1198 docstring selection(size_t sel_index, DocInfoPair docinfo, bool for_math)
1200 if (sel_index >= theCuts.size())
1203 unique_ptr<Buffer> buffer(copyToTempBuffer(theCuts[sel_index].first,
1208 int options = AS_STR_INSETS | AS_STR_NEWLINES;
1210 options |= AS_STR_MATHED;
1212 return buffer->paragraphs().back().asString(options);
1216 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
1217 DocumentClassConstPtr docclass, AuthorList const & authors,
1218 ErrorList & errorList,
1219 cap::BranchAction branchAction)
1221 // Copy authors to the params. We need those pointers.
1222 for (Author const & a : authors)
1223 cur.buffer()->params().authors().record(a);
1225 if (cur.inTexted()) {
1226 Text * text = cur.text();
1229 PasteReturnValue prv =
1230 pasteSelectionHelper(cur, parlist, docclass, branchAction, errorList);
1231 cur.forceBufferUpdate();
1232 cur.clearSelection();
1233 text->setCursor(cur, prv.pit, prv.pos);
1236 // mathed is handled in InsetMathNest/InsetMathGrid
1237 LATTEST(!cur.inMathed());
1241 bool pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
1243 // this does not make sense, if there is nothing to paste
1244 if (!checkPastePossible(sel_index))
1248 pasteParagraphList(cur, theCuts[sel_index].first,
1249 theCuts[sel_index].second.first, theCuts[sel_index].second.second,
1250 errorList, BRANCH_ASK);
1255 bool pasteFromTemp(Cursor & cur, ErrorList & errorList)
1257 // this does not make sense, if there is nothing to paste
1258 if (tempCut.empty() || tempCut[0].first.empty())
1262 pasteParagraphList(cur, tempCut[0].first,
1263 tempCut[0].second.first, tempCut[0].second.second,
1264 errorList, BRANCH_IGNORE);
1269 bool pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs,
1270 Clipboard::TextType type)
1272 // Use internal clipboard if it is the most recent one
1273 // This overrides asParagraphs and type on purpose!
1274 if (theClipboard().isInternal())
1275 return pasteFromStack(cur, errorList, 0);
1277 // First try LyX format
1278 if ((type == Clipboard::LyXTextType ||
1279 type == Clipboard::LyXOrPlainTextType ||
1280 type == Clipboard::AnyTextType) &&
1281 theClipboard().hasTextContents(Clipboard::LyXTextType)) {
1282 string lyx = theClipboard().getAsLyX();
1284 Buffer buffer(string(), false);
1285 buffer.setInternal(true);
1286 buffer.setUnnamed(true);
1287 if (buffer.readString(lyx)) {
1289 pasteParagraphList(cur, buffer.paragraphs(),
1290 buffer.params().documentClassPtr(),
1291 buffer.params().authors(),
1298 // Then try TeX and HTML
1299 Clipboard::TextType types[2] = {Clipboard::HtmlTextType, Clipboard::LaTeXTextType};
1300 string names[2] = {"html", "latexclipboard"};
1301 for (int i = 0; i < 2; ++i) {
1302 if (type != types[i] && type != Clipboard::AnyTextType)
1304 bool available = theClipboard().hasTextContents(types[i]);
1306 // If a specific type was explicitly requested, try to
1307 // interpret plain text: The user told us that the clipboard
1308 // contents is in the desired format
1309 if (!available && type == types[i]) {
1310 types[i] = Clipboard::PlainTextType;
1311 available = theClipboard().hasTextContents(types[i]);
1315 docstring text = theClipboard().getAsText(types[i]);
1316 available = !text.empty();
1318 Buffer buffer(string(), false);
1319 buffer.setInternal(true);
1320 buffer.setUnnamed(true);
1321 buffer.params() = cur.buffer()->params();
1322 available = buffer.importString(names[i], text, errorList);
1324 available = !buffer.paragraphs().empty();
1325 if (available && !buffer.paragraphs()[0].empty()) {
1326 // TeX2lyx (also used in the HTML chain) assumes English as document language
1327 // if no language is explicitly set (as is the case here).
1328 // We thus reset the temp buffer's language to the context language
1329 buffer.changeLanguage(buffer.language(), cur.getFont().language());
1331 pasteParagraphList(cur, buffer.paragraphs(),
1332 buffer.params().documentClassPtr(),
1333 buffer.params().authors(),
1341 // Then try plain text
1342 docstring const text = theClipboard().getAsText(Clipboard::PlainTextType);
1347 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1349 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1350 cur.forceBufferUpdate();
1355 void pasteSimpleText(Cursor & cur, bool asParagraphs)
1358 // Use internal clipboard if it is the most recent one
1359 if (theClipboard().isInternal()) {
1360 if (!checkPastePossible(0))
1363 ParagraphList const & pars = theCuts[0].first;
1364 ParagraphList::const_iterator it = pars.begin();
1365 for (; it != pars.end(); ++it) {
1366 if (it != pars.begin())
1368 text += (*it).asString();
1370 asParagraphs = false;
1372 // Then try plain text
1373 text = theClipboard().getAsText(Clipboard::PlainTextType);
1380 cutSelection(cur, false);
1382 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1384 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1388 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
1389 Clipboard::GraphicsType preferedType)
1391 LASSERT(theClipboard().hasGraphicsContents(preferedType), return);
1393 // get picture from clipboard
1394 FileName filename = theClipboard().getAsGraphics(cur, preferedType);
1395 if (filename.empty())
1398 // create inset for graphic
1399 InsetGraphics * inset = new InsetGraphics(cur.buffer());
1400 InsetGraphicsParams params;
1401 params.filename = support::DocFileName(filename.absFileName(), false);
1402 inset->setParams(params);
1408 void pasteSelection(Cursor & cur, ErrorList & errorList)
1410 if (selectionBuffer.empty())
1413 pasteParagraphList(cur, selectionBuffer[0].first,
1414 selectionBuffer[0].second.first,
1415 selectionBuffer[0].second.second,
1420 void replaceSelectionWithString(Cursor & cur, docstring const & str)
1423 DocIterator selbeg = cur.selectionBegin();
1425 // Get font setting before we cut, we need a copy here, not a bare reference.
1427 selbeg.paragraph().getFontSettings(cur.buffer()->params(), selbeg.pos());
1429 // Insert the new string
1430 pos_type pos = cur.selEnd().pos();
1431 Paragraph & par = cur.selEnd().paragraph();
1432 for (auto const & c : str) {
1433 par.insertChar(pos, c, font, cur.buffer()->params().track_changes);
1437 // Cut the selection
1438 cutSelection(cur, false);
1442 void replaceSelection(Cursor & cur)
1444 if (cur.selection())
1445 cutSelection(cur, false);
1449 void eraseSelection(Cursor & cur)
1451 //lyxerr << "cap::eraseSelection begin: " << cur << endl;
1452 CursorSlice const & i1 = cur.selBegin();
1453 CursorSlice const & i2 = cur.selEnd();
1454 if (!i1.asInsetMath()) {
1455 LYXERR0("Can't erase this selection");
1461 InsetMath * p = i1.asInsetMath();
1462 if (i1.idx() == i2.idx()) {
1463 i1.cell().erase(i1.pos(), i2.pos());
1464 // We may have deleted i1.cell(cur.pos()).
1465 // Make sure that pos is valid.
1466 if (cur.pos() > cur.lastpos())
1467 cur.pos() = cur.lastpos();
1468 } else if (p->nrows() > 0 && p->ncols() > 0) {
1469 // This is a grid, delete a nice square region
1472 region(i1, i2, r1, r2, c1, c2);
1473 for (row_type row = r1; row <= r2; ++row)
1474 for (col_type col = c1; col <= c2; ++col)
1475 p->cell(p->index(row, col)).clear();
1476 // We've deleted the whole cell. Only pos 0 is valid.
1479 idx_type idx1 = i1.idx();
1480 idx_type idx2 = i2.idx();
1483 for (idx_type idx = idx1 ; idx <= idx2; ++idx)
1484 p->cell(idx).clear();
1485 // We've deleted the whole cell. Only pos 0 is valid.
1489 // need a valid cursor. (Lgb)
1490 cur.clearSelection();
1491 //lyxerr << "cap::eraseSelection end: " << cur << endl;
1495 void selDel(Cursor & cur)
1497 //lyxerr << "cap::selDel" << endl;
1498 if (cur.selection())
1499 eraseSelection(cur);
1503 void selClearOrDel(Cursor & cur)
1505 //lyxerr << "cap::selClearOrDel" << endl;
1506 if (lyxrc.auto_region_delete)
1509 cur.selection(false);
1513 docstring grabSelection(CursorData const & cur)
1515 if (!cur.selection())
1519 // grab selection by glueing multiple cells together. This is not what
1520 // we want because selections spanning multiple cells will get "&" and "\\"
1523 for (DocIterator dit = cur.selectionBegin();
1524 dit != cur.selectionEnd(); dit.forwardPos())
1525 os << asString(dit.cell());
1529 CursorSlice i1 = cur.selBegin();
1530 CursorSlice i2 = cur.selEnd();
1532 if (i1.idx() == i2.idx()) {
1533 if (i1.inset().asInsetMath()) {
1534 MathData::const_iterator it = i1.cell().begin();
1535 Buffer * buf = cur.buffer();
1536 return asString(MathData(buf, it + i1.pos(), it + i2.pos()));
1538 return from_ascii("unknown selection 1");
1544 region(i1, i2, r1, r2, c1, c2);
1547 if (i1.inset().asInsetMath()) {
1548 for (row_type row = r1; row <= r2; ++row) {
1551 for (col_type col = c1; col <= c2; ++col) {
1554 data += asString(i1.asInsetMath()->
1555 cell(i1.asInsetMath()->index(row, col)));
1559 data = from_ascii("unknown selection 2");
1565 void dirtyTabularStack(bool b)
1567 dirty_tabular_stack_ = b;
1571 bool tabularStackDirty()
1573 return dirty_tabular_stack_;