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"
18 #include "BranchList.h"
20 #include "buffer_funcs.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"
31 #include "InsetList.h"
36 #include "Paragraph.h"
37 #include "ParagraphParameters.h"
38 #include "ParIterator.h"
39 #include "TextClass.h"
41 #include "insets/InsetBibitem.h"
42 #include "insets/InsetBranch.h"
43 #include "insets/InsetCitation.h"
44 #include "insets/InsetCommand.h"
45 #include "insets/InsetFlex.h"
46 #include "insets/InsetGraphics.h"
47 #include "insets/InsetGraphicsParams.h"
48 #include "insets/InsetInclude.h"
49 #include "insets/InsetLabel.h"
50 #include "insets/InsetTabular.h"
52 #include "mathed/MathData.h"
53 #include "mathed/InsetMath.h"
54 #include "mathed/InsetMathHull.h"
55 #include "mathed/InsetMathRef.h"
56 #include "mathed/MathSupport.h"
58 #include "support/debug.h"
59 #include "support/docstream.h"
60 #include "support/gettext.h"
61 #include "support/lassert.h"
62 #include "support/limited_stack.h"
63 #include "support/lstrings.h"
64 #include "support/lyxalgo.h"
65 #include "support/TempFile.h"
66 #include "support/unique_ptr.h"
68 #include "frontends/alert.h"
69 #include "frontends/Clipboard.h"
70 #include "frontends/Selection.h"
76 using namespace lyx::support;
77 using lyx::frontend::Clipboard;
83 typedef pair<pit_type, int> PitPosPair;
85 typedef limited_stack<pair<ParagraphList, DocumentClassConstPtr> > CutStack;
88 // persistent selection, cleared until the next selection
89 CutStack selectionBuffer(1);
90 // temporary scratch area
93 // store whether the tabular stack is newer than the normal copy stack
94 // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
95 // when we (hopefully) have a one-for-all paste mechanism.
96 bool dirty_tabular_stack_ = false;
99 bool checkPastePossible(int index)
101 return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
105 struct PasteReturnValue {
106 PasteReturnValue(pit_type r_pit, pos_type r_pos, bool r_nu) :
107 pit(r_pit), pos(r_pos), needupdate(r_nu)
116 pasteSelectionHelper(DocIterator const & cur, ParagraphList const & parlist,
117 DocumentClassConstPtr oldDocClass, cap::BranchAction branchAction,
118 ErrorList & errorlist)
120 Buffer const & buffer = *cur.buffer();
121 pit_type pit = cur.pit();
122 pos_type pos = cur.pos();
123 bool need_update = false;
126 return PasteReturnValue(pit, pos, need_update);
128 // Check whether we paste into an inset that does not
129 // produce output (needed for label duplicate check)
130 bool in_active_inset = cur.paragraph().inInset().producesOutput();
131 if (in_active_inset) {
132 for (size_type sl = 0 ; sl < cur.depth() ; ++sl) {
133 Paragraph const & outer_par = cur[sl].paragraph();
134 if (!outer_par.inInset().producesOutput()) {
135 in_active_inset = false;
141 InsetText * target_inset = cur.inset().asInsetText();
143 InsetTabular * it = cur.inset().asInsetTabular();
144 target_inset = it ? it->cell(cur.idx())->asInsetText() : nullptr;
146 LASSERT(target_inset, return PasteReturnValue(pit, pos, need_update));
148 ParagraphList & pars = target_inset->paragraphs();
149 LASSERT(pos <= pars[pit].size(),
150 return PasteReturnValue(pit, pos, need_update));
152 // Make a copy of the CaP paragraphs.
153 ParagraphList insertion = parlist;
155 // Now remove all out of the pars which is NOT allowed in the
156 // new environment and set also another font if that is required.
158 // Merge paragraphs that are to be pasted into a text inset
159 // that does not allow multiple pars.
160 InsetText * inset_text = target_inset->asInsetText();
161 if (inset_text && !inset_text->allowMultiPar()) {
162 while (insertion.size() > 1)
163 mergeParagraph(buffer.params(), insertion, 0);
166 // Convert newline to paragraph break in ParbreakIsNewline
167 if (target_inset->getLayout().parbreakIsNewline()
168 || pars[pit].layout().parbreak_is_newline) {
169 for (size_t i = 0; i != insertion.size(); ++i) {
170 for (pos_type j = 0; j != insertion[i].size(); ++j) {
171 if (insertion[i].isNewline(j)) {
172 // do not track deletion of newline
173 insertion[i].eraseChar(j, false);
174 insertion[i].setInsetOwner(target_inset);
175 breakParagraphConservative(
184 // Prevent to paste uncodable characters in verbatim and ERT.
185 // The encoding is inherited from the context here.
186 docstring uncodable_content;
187 if (target_inset->getLayout().isPassThru() && cur.getEncoding()) {
188 odocstringstream res;
189 Encoding const * e = cur.getEncoding();
190 for (size_t i = 0; i != insertion.size(); ++i) {
191 pos_type end = insertion[i].size();
192 for (pos_type j = 0; j != end; ++j) {
194 if (insertion[i].isInset(j))
196 char_type const c = insertion[i].getChar(j);
197 if (!e->encodable(c)) {
198 // do not track deletion
200 insertion[i].eraseChar(j, false);
206 docstring const uncodable = res.str();
207 if (!uncodable.empty()) {
208 if (uncodable.size() == 1)
209 uncodable_content = bformat(_("The character \"%1$s\" is uncodable in this verbatim context "
210 "and thus has not been pasted."),
213 uncodable_content = bformat(_("The characters \"%1$s\" are uncodable in this verbatim context "
214 "and thus have not been pasted."),
219 // set the paragraphs to plain layout if necessary
220 DocumentClassConstPtr newDocClass = buffer.params().documentClassPtr();
221 if (cur.inset().usePlainLayout()) {
222 bool forcePlainLayout = target_inset->forcePlainLayout();
223 Layout const & plainLayout = newDocClass->plainLayout();
224 Layout const & defaultLayout = newDocClass->defaultLayout();
225 ParagraphList::iterator const end = insertion.end();
226 ParagraphList::iterator par = insertion.begin();
227 for (; par != end; ++par) {
228 Layout const & parLayout = par->layout();
229 if (forcePlainLayout || parLayout == defaultLayout)
230 par->setLayout(plainLayout);
233 // check if we need to reset from plain layout
234 Layout const & defaultLayout = newDocClass->defaultLayout();
235 Layout const & plainLayout = newDocClass->plainLayout();
236 ParagraphList::iterator const end = insertion.end();
237 ParagraphList::iterator par = insertion.begin();
238 for (; par != end; ++par) {
239 Layout const & parLayout = par->layout();
240 if (parLayout == plainLayout)
241 par->setLayout(defaultLayout);
245 InsetText in(cur.buffer());
246 // Make sure there is no class difference.
247 in.paragraphs().clear();
248 // This works without copying any paragraph data because we have
249 // a specialized swap method for ParagraphList. This is important
250 // since we store pointers to insets at some places and we don't
251 // want to invalidate them.
252 insertion.swap(in.paragraphs());
253 cap::switchBetweenClasses(oldDocClass, newDocClass, in, errorlist);
254 // Do this here since switchBetweenClasses clears the errorlist
255 if (!uncodable_content.empty())
256 errorlist.push_back(ErrorItem(_("Uncodable content"), uncodable_content));
257 insertion.swap(in.paragraphs());
259 ParagraphList::iterator tmpbuf = insertion.begin();
260 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
262 depth_type max_depth = pars[pit].getMaxDepthAfter();
264 for (; tmpbuf != insertion.end(); ++tmpbuf) {
265 // If we have a negative jump so that the depth would
266 // go below 0 depth then we have to redo the delta to
267 // this new max depth level so that subsequent
268 // paragraphs are aligned correctly to this paragraph
270 if (int(tmpbuf->params().depth()) + depth_delta < 0)
273 // Set the right depth so that we are not too deep or shallow.
274 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
275 if (tmpbuf->params().depth() > max_depth)
276 tmpbuf->params().depth(max_depth);
278 // Set max_depth for the next paragraph
279 max_depth = tmpbuf->getMaxDepthAfter();
281 // Set the inset owner of this paragraph.
282 tmpbuf->setInsetOwner(target_inset);
283 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
284 // do not track deletion of invalid insets
285 if (Inset * inset = tmpbuf->getInset(i))
286 if (!target_inset->insetAllowed(inset->lyxCode()))
287 tmpbuf->eraseChar(i--, false);
290 if (lyxrc.ct_markup_copied)
291 tmpbuf->setChange(Change(buffer.params().track_changes ?
292 Change::INSERTED : Change::UNCHANGED));
295 bool const empty = pars[pit].empty();
297 // Make the buf exactly the same layout as the cursor
299 insertion.begin()->makeSameLayout(pars[pit]);
302 // Prepare the paragraphs and insets for insertion.
303 insertion.swap(in.paragraphs());
305 InsetIterator const i_end = inset_iterator_end(in);
306 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
307 // Even though this will also be done later, it has to be done here
308 // since some inset might try to access the buffer() member.
309 it->setBuffer(const_cast<Buffer &>(buffer));
310 switch (it->lyxCode()) {
312 case MATH_HULL_CODE: {
313 // check for equation labels and resolve duplicates
314 InsetMathHull * ins = it->asInsetMath()->asHullInset();
315 std::vector<InsetLabel *> labels = ins->getLabels();
316 for (size_t i = 0; i != labels.size(); ++i) {
319 InsetLabel * lab = labels[i];
320 docstring const oldname = lab->getParam("name");
321 lab->updateLabel(oldname, in_active_inset);
322 // We need to update the buffer reference cache.
324 docstring const newname = lab->getParam("name");
325 if (oldname == newname)
327 // adapt the references
328 for (InsetIterator itt = inset_iterator_begin(in);
329 itt != i_end; ++itt) {
330 if (itt->lyxCode() == REF_CODE) {
331 InsetCommand * ref = itt->asInsetCommand();
332 if (ref->getParam("reference") == oldname)
333 ref->setParam("reference", newname);
334 } else if (itt->lyxCode() == MATH_REF_CODE) {
335 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
336 // this is necessary to prevent an uninitialized
337 // buffer when the RefInset is in a MathBox.
338 // FIXME audit setBuffer calls
339 mi->setBuffer(const_cast<Buffer &>(buffer));
340 if (mi->getTarget() == oldname)
341 mi->changeTarget(newname);
349 // check for duplicates
350 InsetLabel & lab = static_cast<InsetLabel &>(*it);
351 docstring const oldname = lab.getParam("name");
352 lab.updateLabel(oldname, in_active_inset);
353 // We need to update the buffer reference cache.
355 docstring const newname = lab.getParam("name");
356 if (oldname == newname)
358 // adapt the references
359 for (InsetIterator itt = inset_iterator_begin(in); itt != i_end; ++itt) {
360 if (itt->lyxCode() == REF_CODE) {
361 InsetCommand & ref = static_cast<InsetCommand &>(*itt);
362 if (ref.getParam("reference") == oldname)
363 ref.setParam("reference", newname);
364 } else if (itt->lyxCode() == MATH_REF_CODE) {
365 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
366 // this is necessary to prevent an uninitialized
367 // buffer when the RefInset is in a MathBox.
368 // FIXME audit setBuffer calls
369 mi->setBuffer(const_cast<Buffer &>(buffer));
370 if (mi->getTarget() == oldname)
371 mi->changeTarget(newname);
378 InsetInclude & inc = static_cast<InsetInclude &>(*it);
380 // We need to update the list of included files.
386 InsetCitation & cit = static_cast<InsetCitation &>(*it);
387 // This actually only needs to be done if the cite engine
388 // differs, but we do it in general.
390 // We need to update the list of citations.
396 // check for duplicates
397 InsetBibitem & bib = static_cast<InsetBibitem &>(*it);
398 docstring const oldkey = bib.getParam("key");
399 bib.updateCommand(oldkey, false);
400 // We need to update the buffer reference cache.
402 docstring const newkey = bib.getParam("key");
403 if (oldkey == newkey)
405 // adapt the references
406 for (InsetIterator itt = inset_iterator_begin(in);
407 itt != i_end; ++itt) {
408 if (itt->lyxCode() == CITE_CODE) {
409 InsetCommand * ref = itt->asInsetCommand();
410 if (ref->getParam("key") == oldkey)
411 ref->setParam("key", newkey);
418 // check if branch is known to target buffer
420 InsetBranch & br = static_cast<InsetBranch &>(*it);
421 docstring const name = br.branch();
424 bool const is_child = (&buffer != buffer.masterBuffer());
425 BranchList branchlist = buffer.params().branchlist();
426 if ((!is_child && branchlist.find(name))
427 || (is_child && (branchlist.find(name)
428 || buffer.masterBuffer()->params().branchlist().find(name))))
430 switch(branchAction) {
431 case cap::BRANCH_ADD: {
432 // This is for a temporary buffer, so simply create the branch.
433 // Must not use lyx::dispatch(), since tmpbuffer has no view.
435 const_cast<Buffer&>(buffer).dispatch(FuncRequest(LFUN_BRANCH_ADD, name), dr);
438 case cap::BRANCH_ASK: {
439 docstring text = bformat(
440 _("The pasted branch \"%1$s\" is undefined.\n"
441 "Do you want to add it to the document's branch list?"),
443 if (frontend::Alert::prompt(_("Unknown branch"),
444 text, 0, 1, _("&Add"), _("&Don't Add")) != 0)
446 lyx::dispatch(FuncRequest(LFUN_BRANCH_ADD, name));
449 case cap::BRANCH_IGNORE:
452 // We need to update the list of branches.
461 insertion.swap(in.paragraphs());
463 // Split the paragraph for inserting the buf if necessary.
465 breakParagraphConservative(buffer.params(), pars, pit, pos);
469 pars.insert(lyx::next(pars.begin(), pit),
473 // merge the empty par with the last par of the insertion
474 mergeParagraph(buffer.params(), pars,
475 pit + insertion.size() - 1);
477 pars.insert(lyx::next(pars.begin(), pit + 1),
481 // merge the first par of the insertion with the current par
482 mergeParagraph(buffer.params(), pars, pit);
485 // Store the new cursor position.
486 pit_type last_paste = pit + insertion.size() - 1;
487 pit_type startpit = pit;
489 pos = pars[last_paste].size();
491 // FIXME Should we do it here, or should we let updateBuffer() do it?
492 // Set paragraph buffers. It's important to do this right away
493 // before something calls Inset::buffer() and causes a crash.
494 for (pit_type p = startpit; p <= pit; ++p)
495 pars[p].setInsetBuffers(const_cast<Buffer &>(buffer));
497 // Join (conditionally) last pasted paragraph with next one, i.e.,
498 // the tail of the spliced document paragraph
499 if (!empty && last_paste + 1 != pit_type(pars.size())) {
500 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
501 mergeParagraph(buffer.params(), pars, last_paste);
502 } else if (pars[last_paste + 1].empty()) {
503 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
504 mergeParagraph(buffer.params(), pars, last_paste);
505 } else if (pars[last_paste].empty()) {
506 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
507 mergeParagraph(buffer.params(), pars, last_paste);
509 pars[last_paste + 1].stripLeadingSpaces(buffer.params().track_changes);
514 return PasteReturnValue(pit, pos, need_update);
518 PitPosPair eraseSelectionHelper(BufferParams const & params,
519 ParagraphList & pars,
520 pit_type startpit, pit_type endpit,
521 int startpos, int endpos)
523 // Start of selection is really invalid.
524 if (startpit == pit_type(pars.size()) ||
525 (startpos > pars[startpit].size()))
526 return PitPosPair(endpit, endpos);
528 // Start and end is inside same paragraph
529 if (endpit == pit_type(pars.size()) || startpit == endpit) {
530 endpos -= pars[startpit].eraseChars(startpos, endpos, params.track_changes);
531 return PitPosPair(endpit, endpos);
534 for (pit_type pit = startpit; pit != endpit + 1;) {
535 pos_type const left = (pit == startpit ? startpos : 0);
536 pos_type right = (pit == endpit ? endpos : pars[pit].size() + 1);
537 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.track_changes);
539 // Logically erase only, including the end-of-paragraph character
540 pars[pit].eraseChars(left, right, params.track_changes);
542 // Separate handling of paragraph break:
543 if (merge && pit != endpit &&
545 || pars[pit].hasSameLayout(pars[endpit])
546 || pars[endpit].size() == endpos)) {
547 if (pit + 1 == endpit)
548 endpos += pars[pit].size();
549 mergeParagraph(params, pars, pit);
555 // Ensure legal cursor pos:
558 return PitPosPair(endpit, endpos);
562 Buffer * copyToTempBuffer(ParagraphList const & paragraphs, DocumentClassConstPtr docclass)
564 // This used to need to be static to avoid a memory leak. It no longer needs
565 // to be so, but the alternative is to construct a new one of these (with a
566 // new temporary directory, etc) every time, and then to destroy it. So maybe
567 // it's worth just keeping this one around.
568 static TempFile tempfile("clipboard.internal");
569 tempfile.setAutoRemove(false);
570 // The initialization of staticbuffer is thread-safe. Using a lambda
571 // guarantees that the properties are set only once.
572 static Buffer * staticbuffer = [&](){
574 theBufferList().newInternalBuffer(tempfile.name().absFileName());
576 b->inset().setBuffer(*b);
577 //initialize staticbuffer with b
580 // Use a clone for the complicated stuff so that we do not need to clean
581 // up in order to avoid a crash.
582 Buffer * buffer = staticbuffer->cloneBufferOnly();
583 LASSERT(buffer, return nullptr);
585 // This needs doing every time.
586 // Since setDocumentClass() causes deletion of the old document class
587 // we need to reset all layout pointers in paragraphs (otherwise they
588 // would be dangling).
589 ParIterator const end = buffer->par_iterator_end();
590 for (ParIterator it = buffer->par_iterator_begin(); it != end; ++it) {
591 docstring const name = it->layout().name();
592 if (docclass->hasLayout(name))
593 it->setLayout((*docclass)[name]);
595 it->setPlainOrDefaultLayout(*docclass);
597 buffer->params().setDocumentClass(docclass);
599 // we will use pasteSelectionHelper to copy the paragraphs into the
600 // temporary Buffer, since it does a lot of things to fix them up.
601 DocIterator dit = doc_iterator_begin(buffer, &buffer->inset());
603 pasteSelectionHelper(dit, paragraphs, docclass, cap::BRANCH_ADD, el);
609 void putClipboard(ParagraphList const & paragraphs,
610 DocumentClassConstPtr docclass, docstring const & plaintext,
611 BufferParams const bp)
613 Buffer * buffer = copyToTempBuffer(paragraphs, docclass);
614 if (!buffer) // already asserted in copyToTempBuffer()
617 // We don't want to produce images that are not used. Therefore,
618 // output formulas as MathML. Even if this is not understood by all
619 // applications, the number that can parse it should go up in the future.
620 buffer->params().html_math_output = BufferParams::MathML;
622 if (lyxrc.ct_markup_copied) {
623 // Copy authors to the params. We need those pointers.
624 for (Author const & a : bp.authors())
625 buffer->params().authors().record(a);
628 // Make sure MarkAsExporting is deleted before buffer is
630 // The Buffer is being used to export. This is necessary so that the
631 // updateMacros call will record the needed information.
632 MarkAsExporting mex(buffer);
634 buffer->updateBuffer(Buffer::UpdateMaster, OutputUpdate);
635 buffer->updateMacros();
636 buffer->updateMacroInstances(OutputUpdate);
641 if (buffer->write(oslyx))
645 odocstringstream oshtml;
646 OutputParams runparams(encodings.fromLyXName("utf8"));
647 // We do not need to produce images, etc.
648 runparams.dryrun = true;
649 // We are not interested in errors (bug 8866)
650 runparams.silent = true;
651 buffer->writeLyXHTMLSource(oshtml, runparams, Buffer::FullSource);
653 theClipboard().put(lyx, oshtml.str(), plaintext);
661 /// return true if the whole ParagraphList is deleted
662 static bool isFullyDeleted(ParagraphList const & pars)
664 pit_type const pars_size = static_cast<pit_type>(pars.size());
666 // check all paragraphs
667 for (pit_type pit = 0; pit < pars_size; ++pit) {
668 if (!pars[pit].empty()) // prevent assertion failure
669 if (!pars[pit].isDeleted(0, pars[pit].size()))
676 void copySelectionHelper(Buffer const & buf, Text const & text,
677 pit_type startpit, pit_type endpit,
678 int start, int end, DocumentClassConstPtr dc, CutStack & cutstack)
680 ParagraphList const & pars = text.paragraphs();
682 // In most of these cases, we can try to recover.
683 LASSERT(0 <= start, start = 0);
684 LASSERT(start <= pars[startpit].size(), start = pars[startpit].size());
685 LASSERT(0 <= end, end = 0);
686 LASSERT(end <= pars[endpit].size(), end = pars[endpit].size());
687 LASSERT(startpit != endpit || start <= end, return);
689 // Clone the paragraphs within the selection.
690 ParagraphList copy_pars(lyx::next(pars.begin(), startpit),
691 lyx::next(pars.begin(), endpit + 1));
693 // Remove the end of the last paragraph; afterwards, remove the
694 // beginning of the first paragraph. Keep this order - there may only
695 // be one paragraph! Do not track deletions here; this is an internal
696 // action not visible to the user
698 Paragraph & back = copy_pars.back();
699 back.eraseChars(end, back.size(), false);
700 Paragraph & front = copy_pars.front();
701 front.eraseChars(0, start, false);
703 ParagraphList::iterator it = copy_pars.begin();
704 ParagraphList::iterator it_end = copy_pars.end();
706 for (; it != it_end; ++it) {
707 // Since we have a copy of the paragraphs, the insets
708 // do not have a proper buffer reference. It makes
709 // sense to add them temporarily, because the
710 // operations below depend on that (acceptChanges included).
711 it->setInsetBuffers(const_cast<Buffer &>(buf));
712 // PassThru paragraphs have the Language
713 // latex_language. This is invalid for others, so we
714 // need to change it to the buffer language.
715 if (it->isPassThru())
716 it->changeLanguage(buf.params(),
717 latex_language, buf.language());
720 // do not copy text (also nested in insets) which is marked as
721 // deleted, unless the whole selection was deleted
722 if (!lyxrc.ct_markup_copied) {
723 if (!isFullyDeleted(copy_pars))
724 acceptChanges(copy_pars, buf.params());
726 rejectChanges(copy_pars, buf.params());
730 // do some final cleanup now, to make sure that the paragraphs
731 // are not linked to something else.
732 it = copy_pars.begin();
733 for (; it != it_end; ++it) {
735 it->setInsetOwner(nullptr);
738 cutstack.push(make_pair(copy_pars, dc));
746 void region(CursorSlice const & i1, CursorSlice const & i2,
747 Inset::row_type & r1, Inset::row_type & r2,
748 Inset::col_type & c1, Inset::col_type & c2)
750 Inset & p = i1.inset();
751 c1 = p.col(i1.idx());
752 c2 = p.col(i2.idx());
755 r1 = p.row(i1.idx());
756 r2 = p.row(i2.idx());
762 docstring grabAndEraseSelection(Cursor & cur)
764 if (!cur.selection())
766 docstring res = grabSelection(cur);
772 bool reduceSelectionToOneCell(CursorData & cur)
774 if (!cur.selection() || !cur.inMathed())
777 CursorSlice i1 = cur.selBegin();
778 CursorSlice i2 = cur.selEnd();
779 if (!i1.inset().asInsetMath())
782 // the easy case: do nothing if only one cell is selected
783 if (i1.idx() == i2.idx())
788 cur.top().pos() = cur.top().lastpos();
794 bool multipleCellsSelected(CursorData const & cur)
796 if (!cur.selection() || !cur.inMathed())
799 CursorSlice i1 = cur.selBegin();
800 CursorSlice i2 = cur.selEnd();
801 if (!i1.inset().asInsetMath())
804 if (i1.idx() == i2.idx())
811 void switchBetweenClasses(DocumentClassConstPtr oldone,
812 DocumentClassConstPtr newone, InsetText & in, ErrorList & errorlist)
816 LBUFERR(!in.paragraphs().empty());
817 if (oldone == newone)
820 DocumentClass const & oldtc = *oldone;
821 DocumentClass const & newtc = *newone;
824 ParIterator it = par_iterator_begin(in);
825 ParIterator end = par_iterator_end(in);
826 // for remembering which layouts we've had to add
827 set<docstring> newlayouts;
828 for (; it != end; ++it) {
829 docstring const name = it->layout().name();
831 // the pasted text will keep their own layout name. If this layout does
832 // not exist in the new document, it will behave like a standard layout.
833 bool const added_one = newtc.addLayoutIfNeeded(name);
835 newlayouts.insert(name);
837 if (added_one || newlayouts.find(name) != newlayouts.end()) {
839 docstring const s = bformat(_("Layout `%1$s' was not found."), name);
840 errorlist.push_back(ErrorItem(_("Layout Not Found"), s,
841 {it->id(), 0}, {it->id(), -1}));
844 if (in.usePlainLayout())
845 it->setLayout(newtc.plainLayout());
847 it->setLayout(newtc[name]);
850 // character styles and hidden table cells
851 InsetIterator const i_end = inset_iterator_end(in);
852 for (InsetIterator iit = inset_iterator_begin(in); iit != i_end; ++iit) {
853 InsetCode const code = iit->lyxCode();
854 if (code == FLEX_CODE) {
855 // FIXME: Should we verify all InsetCollapsible?
856 docstring const layoutName = iit->layoutName();
857 docstring const & n = newone->insetLayout(layoutName).name();
858 bool const is_undefined = n.empty() ||
859 n == DocumentClass::plainInsetLayout().name();
863 // The flex inset is undefined in newtc
864 docstring const oldname = from_utf8(oldtc.name());
865 docstring const newname = from_utf8(newtc.name());
867 if (oldname == newname)
868 s = bformat(_("Flex inset %1$s is undefined after "
869 "reloading `%2$s' layout."), layoutName, oldname);
871 s = bformat(_("Flex inset %1$s is undefined because of "
872 "conversion from `%2$s' layout to `%3$s'."),
873 layoutName, oldname, newname);
874 // To warn the user that something had to be done.
875 errorlist.push_back(ErrorItem(
876 _("Undefined flex inset"), s,
877 {iit.paragraph().id(), iit.pos()},
878 {iit.paragraph().id(), iit.pos() + 1}));
879 } else if (code == TABULAR_CODE) {
880 // The recursion above does not catch paragraphs in "hidden" cells,
881 // i.e., ones that are part of a multirow or multicolum. So we need
882 // to handle those separately.
883 // This is the cause of bug #9049.
884 InsetTabular * table = iit->asInsetTabular();
885 table->setLayoutForHiddenCells(newtc);
891 vector<docstring> availableSelections(Buffer const * buf)
893 vector<docstring> selList;
897 CutStack::const_iterator cit = theCuts.begin();
898 CutStack::const_iterator end = theCuts.end();
899 for (; cit != end; ++cit) {
900 // we do not use cit-> here because gcc 2.9x does not
902 ParagraphList const & pars = (*cit).first;
904 ParagraphList::const_iterator pit = pars.begin();
905 ParagraphList::const_iterator pend = pars.end();
906 for (; pit != pend; ++pit) {
907 Paragraph par(*pit, 0, 46);
908 // adapt paragraph to current buffer.
909 par.setInsetBuffers(const_cast<Buffer &>(*buf));
910 textSel += par.asString(AS_STR_INSETS);
911 if (textSel.size() > 45) {
912 support::truncateWithEllipsis(textSel,45);
916 selList.push_back(textSel);
923 size_type numberOfSelections()
925 return theCuts.size();
930 void cutSelectionHelper(Cursor & cur, CutStack & cuts, bool realcut, bool putclip)
932 // This doesn't make sense, if there is no selection
933 if (!cur.selection())
936 // OK, we have a selection. This is always between cur.selBegin()
939 if (cur.inTexted()) {
940 Text * text = cur.text();
945 // make sure that the depth behind the selection are restored, too
946 cur.recordUndoSelection();
947 pit_type begpit = cur.selBegin().pit();
948 pit_type endpit = cur.selEnd().pit();
950 int endpos = cur.selEnd().pos();
952 BufferParams const & bp = cur.buffer()->params();
954 copySelectionHelper(*cur.buffer(),
957 cur.selBegin().pos(), endpos,
958 bp.documentClassPtr(), cuts);
959 // Stuff what we got on the clipboard.
960 // Even if there is no selection.
962 putClipboard(cuts[0].first, cuts[0].second,
963 cur.selectionAsString(true, true), bp);
966 if (begpit != endpit)
967 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
969 tie(endpit, endpos) =
970 eraseSelectionHelper(bp, text->paragraphs(), begpit, endpit,
971 cur.selBegin().pos(), endpos);
973 // cutSelection can invalidate the cursor so we need to set
975 // we prefer the end for when tracking changes
979 // need a valid cursor. (Lgb)
980 cur.clearSelection();
982 // After a cut operation, we must make sure that the Buffer is updated
983 // because some further operation might need updated label information for
984 // example. So we cannot just use "cur.forceBufferUpdate()" here.
986 cur.buffer()->updateBuffer();
988 // tell tabular that a recent copy happened
989 dirtyTabularStack(false);
992 if (cur.inMathed()) {
993 if (cur.selBegin().idx() != cur.selEnd().idx()) {
994 // The current selection spans more than one cell.
996 cur.recordUndoInset();
998 // Record only the current cell to avoid a jumping
1004 eraseSelection(cur);
1010 void cutSelection(Cursor & cur, bool realcut)
1012 cutSelectionHelper(cur, theCuts, realcut, true);
1016 void cutSelectionToTemp(Cursor & cur, bool realcut)
1018 cutSelectionHelper(cur, tempCut, realcut, false);
1022 void copySelection(Cursor const & cur)
1024 copySelection(cur, cur.selectionAsString(true, true));
1028 void copyInset(Cursor const & cur, Inset * inset, docstring const & plaintext)
1032 BufferParams const & bp = cur.buffer()->params();
1033 par.setLayout(bp.documentClass().plainLayout());
1034 Font font(inherit_font, bp.language);
1035 par.insertInset(0, inset, font, Change(Change::UNCHANGED));
1036 pars.push_back(par);
1037 theCuts.push(make_pair(pars, bp.documentClassPtr()));
1039 // stuff the selection onto the X clipboard, from an explicit copy request
1040 putClipboard(theCuts[0].first, theCuts[0].second, plaintext, bp);
1046 void copySelectionToStack(CursorData const & cur, CutStack & cutstack)
1048 // this doesn't make sense, if there is no selection
1049 if (!cur.selection())
1052 // copySelection can not yet handle the case of cross idx selection
1053 if (cur.selBegin().idx() != cur.selEnd().idx())
1056 if (cur.inTexted()) {
1057 Text * text = cur.text();
1059 // ok we have a selection. This is always between cur.selBegin()
1060 // and sel_end cursor
1061 copySelectionHelper(*cur.buffer(), *text,
1062 cur.selBegin().pit(), cur.selEnd().pit(),
1063 cur.selBegin().pos(), cur.selEnd().pos(),
1064 cur.buffer()->params().documentClassPtr(),
1066 // Reset the dirty_tabular_stack_ flag only when something
1067 // is copied to the clipboard (not to the selectionBuffer).
1068 if (&cutstack == &theCuts)
1069 dirtyTabularStack(false);
1072 if (cur.inMathed()) {
1073 //lyxerr << "copySelection in mathed" << endl;
1076 BufferParams const & bp = cur.buffer()->params();
1077 // FIXME This should be the plain layout...right?
1078 par.setLayout(bp.documentClass().plainLayout());
1079 // For pasting into text, we set the language to the paragraph language
1080 // (rather than the default_language which is always English; see #2596)
1081 par.insert(0, grabSelection(cur), Font(sane_font, par.getParLanguage(bp)),
1082 Change(Change::UNCHANGED));
1083 pars.push_back(par);
1084 cutstack.push(make_pair(pars, bp.documentClassPtr()));
1091 void copySelectionToStack()
1093 if (!selectionBuffer.empty())
1094 theCuts.push(selectionBuffer[0]);
1098 void copySelectionToTemp(Cursor & cur)
1100 copySelectionToStack(cur, tempCut);
1104 void copySelection(Cursor const & cur, docstring const & plaintext)
1106 // In tablemode, because copy and paste actually use special table stack
1107 // we do not attempt to get selected paragraphs under cursor. Instead, a
1108 // paragraph with the plain text version is generated so that table cells
1109 // can be pasted as pure text somewhere else.
1110 if (cur.selBegin().idx() != cur.selEnd().idx()) {
1113 BufferParams const & bp = cur.buffer()->params();
1114 par.setLayout(bp.documentClass().plainLayout());
1115 par.insert(0, plaintext, Font(), Change(Change::UNCHANGED));
1116 pars.push_back(par);
1117 theCuts.push(make_pair(pars, bp.documentClassPtr()));
1119 copySelectionToStack(cur, theCuts);
1122 // stuff the selection onto the X clipboard, from an explicit copy request
1123 putClipboard(theCuts[0].first, theCuts[0].second, plaintext,
1124 cur.buffer()->params());
1128 void saveSelection(Cursor const & cur)
1130 // This function is called, not when a selection is formed, but when
1131 // a selection is cleared. Therefore, multiple keyboard selection
1132 // will not repeatively trigger this function (bug 3877).
1134 && cur.selBegin() == cur.bv().cursor().selBegin()
1135 && cur.selEnd() == cur.bv().cursor().selEnd()) {
1136 LYXERR(Debug::SELECTION, "saveSelection: '" << cur.selectionAsString(true, true) << "'");
1137 copySelectionToStack(cur, selectionBuffer);
1144 return !selectionBuffer.empty();
1148 void clearSelection()
1150 selectionBuffer.clear();
1154 void clearCutStack()
1161 docstring selection(size_t sel_index, DocumentClassConstPtr docclass)
1163 if (sel_index >= theCuts.size())
1166 unique_ptr<Buffer> buffer(copyToTempBuffer(theCuts[sel_index].first,
1171 return buffer->paragraphs().back().asString(AS_STR_INSETS | AS_STR_NEWLINES);
1175 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
1176 DocumentClassConstPtr docclass, ErrorList & errorList,
1177 cap::BranchAction branchAction)
1179 if (cur.inTexted()) {
1180 Text * text = cur.text();
1183 PasteReturnValue prv =
1184 pasteSelectionHelper(cur, parlist, docclass, branchAction, errorList);
1185 cur.forceBufferUpdate();
1186 cur.clearSelection();
1187 text->setCursor(cur, prv.pit, prv.pos);
1190 // mathed is handled in InsetMathNest/InsetMathGrid
1191 LATTEST(!cur.inMathed());
1195 bool pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
1197 // this does not make sense, if there is nothing to paste
1198 if (!checkPastePossible(sel_index))
1202 pasteParagraphList(cur, theCuts[sel_index].first,
1203 theCuts[sel_index].second, errorList, BRANCH_ASK);
1208 bool pasteFromTemp(Cursor & cur, ErrorList & errorList)
1210 // this does not make sense, if there is nothing to paste
1211 if (tempCut.empty() || tempCut[0].first.empty())
1215 pasteParagraphList(cur, tempCut[0].first,
1216 tempCut[0].second, errorList, BRANCH_IGNORE);
1221 bool pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs,
1222 Clipboard::TextType type)
1224 // Use internal clipboard if it is the most recent one
1225 // This overrides asParagraphs and type on purpose!
1226 if (theClipboard().isInternal())
1227 return pasteFromStack(cur, errorList, 0);
1229 // First try LyX format
1230 if ((type == Clipboard::LyXTextType ||
1231 type == Clipboard::LyXOrPlainTextType ||
1232 type == Clipboard::AnyTextType) &&
1233 theClipboard().hasTextContents(Clipboard::LyXTextType)) {
1234 string lyx = theClipboard().getAsLyX();
1236 // For some strange reason gcc 3.2 and 3.3 do not accept
1237 // Buffer buffer(string(), false);
1238 Buffer buffer("", false);
1239 buffer.setUnnamed(true);
1240 if (buffer.readString(lyx)) {
1242 pasteParagraphList(cur, buffer.paragraphs(),
1243 buffer.params().documentClassPtr(), errorList);
1249 // Then try TeX and HTML
1250 Clipboard::TextType types[2] = {Clipboard::HtmlTextType, Clipboard::LaTeXTextType};
1251 string names[2] = {"html", "latexclipboard"};
1252 for (int i = 0; i < 2; ++i) {
1253 if (type != types[i] && type != Clipboard::AnyTextType)
1255 bool available = theClipboard().hasTextContents(types[i]);
1257 // If a specific type was explicitly requested, try to
1258 // interpret plain text: The user told us that the clipboard
1259 // contents is in the desired format
1260 if (!available && type == types[i]) {
1261 types[i] = Clipboard::PlainTextType;
1262 available = theClipboard().hasTextContents(types[i]);
1266 docstring text = theClipboard().getAsText(types[i]);
1267 available = !text.empty();
1269 // For some strange reason gcc 3.2 and 3.3 do not accept
1270 // Buffer buffer(string(), false);
1271 Buffer buffer("", false);
1272 buffer.setUnnamed(true);
1273 available = buffer.importString(names[i], text, errorList);
1275 available = !buffer.paragraphs().empty();
1276 if (available && !buffer.paragraphs()[0].empty()) {
1277 // TeX2lyx (also used in the HTML chain) assumes English as document language
1278 // if no language is explicitly set (as is the case here).
1279 // We thus reset the temp buffer's language to the context language
1280 buffer.changeLanguage(buffer.language(), cur.getFont().language());
1282 pasteParagraphList(cur, buffer.paragraphs(),
1283 buffer.params().documentClassPtr(), errorList);
1290 // Then try plain text
1291 docstring const text = theClipboard().getAsText(Clipboard::PlainTextType);
1296 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1298 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1299 cur.forceBufferUpdate();
1304 void pasteSimpleText(Cursor & cur, bool asParagraphs)
1307 // Use internal clipboard if it is the most recent one
1308 if (theClipboard().isInternal()) {
1309 if (!checkPastePossible(0))
1312 ParagraphList const & pars = theCuts[0].first;
1313 ParagraphList::const_iterator it = pars.begin();
1314 for (; it != pars.end(); ++it) {
1315 if (it != pars.begin())
1317 text += (*it).asString();
1319 asParagraphs = false;
1321 // Then try plain text
1322 text = theClipboard().getAsText(Clipboard::PlainTextType);
1329 cutSelection(cur, false);
1331 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1333 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1337 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
1338 Clipboard::GraphicsType preferedType)
1340 LASSERT(theClipboard().hasGraphicsContents(preferedType), return);
1342 // get picture from clipboard
1343 FileName filename = theClipboard().getAsGraphics(cur, preferedType);
1344 if (filename.empty())
1347 // create inset for graphic
1348 InsetGraphics * inset = new InsetGraphics(cur.buffer());
1349 InsetGraphicsParams params;
1350 params.filename = support::DocFileName(filename.absFileName(), false);
1351 inset->setParams(params);
1357 void pasteSelection(Cursor & cur, ErrorList & errorList)
1359 if (selectionBuffer.empty())
1362 pasteParagraphList(cur, selectionBuffer[0].first,
1363 selectionBuffer[0].second, errorList);
1367 void replaceSelectionWithString(Cursor & cur, docstring const & str)
1370 DocIterator selbeg = cur.selectionBegin();
1372 // Get font setting before we cut, we need a copy here, not a bare reference.
1374 selbeg.paragraph().getFontSettings(cur.buffer()->params(), selbeg.pos());
1376 // Insert the new string
1377 pos_type pos = cur.selEnd().pos();
1378 Paragraph & par = cur.selEnd().paragraph();
1379 docstring::const_iterator cit = str.begin();
1380 docstring::const_iterator end = str.end();
1381 for (; cit != end; ++cit, ++pos)
1382 par.insertChar(pos, *cit, font, cur.buffer()->params().track_changes);
1384 // Cut the selection
1385 cutSelection(cur, false);
1389 void replaceSelection(Cursor & cur)
1391 if (cur.selection())
1392 cutSelection(cur, false);
1396 void eraseSelection(Cursor & cur)
1398 //lyxerr << "cap::eraseSelection begin: " << cur << endl;
1399 CursorSlice const & i1 = cur.selBegin();
1400 CursorSlice const & i2 = cur.selEnd();
1401 if (!i1.asInsetMath()) {
1402 LYXERR0("Can't erase this selection");
1408 InsetMath * p = i1.asInsetMath();
1409 if (i1.idx() == i2.idx()) {
1410 i1.cell().erase(i1.pos(), i2.pos());
1411 // We may have deleted i1.cell(cur.pos()).
1412 // Make sure that pos is valid.
1413 if (cur.pos() > cur.lastpos())
1414 cur.pos() = cur.lastpos();
1415 } else if (p->nrows() > 0 && p->ncols() > 0) {
1416 // This is a grid, delete a nice square region
1417 Inset::row_type r1, r2;
1418 Inset::col_type c1, c2;
1419 region(i1, i2, r1, r2, c1, c2);
1420 for (Inset::row_type row = r1; row <= r2; ++row)
1421 for (Inset::col_type col = c1; col <= c2; ++col)
1422 p->cell(p->index(row, col)).clear();
1423 // We've deleted the whole cell. Only pos 0 is valid.
1426 Inset::idx_type idx1 = i1.idx();
1427 Inset::idx_type idx2 = i2.idx();
1430 for (Inset::idx_type idx = idx1 ; idx <= idx2; ++idx)
1431 p->cell(idx).clear();
1432 // We've deleted the whole cell. Only pos 0 is valid.
1436 // need a valid cursor. (Lgb)
1437 cur.clearSelection();
1438 //lyxerr << "cap::eraseSelection end: " << cur << endl;
1442 void selDel(Cursor & cur)
1444 //lyxerr << "cap::selDel" << endl;
1445 if (cur.selection())
1446 eraseSelection(cur);
1450 void selClearOrDel(Cursor & cur)
1452 //lyxerr << "cap::selClearOrDel" << endl;
1453 if (lyxrc.auto_region_delete)
1456 cur.selection(false);
1460 docstring grabSelection(CursorData const & cur)
1462 if (!cur.selection())
1466 // grab selection by glueing multiple cells together. This is not what
1467 // we want because selections spanning multiple cells will get "&" and "\\"
1470 for (DocIterator dit = cur.selectionBegin();
1471 dit != cur.selectionEnd(); dit.forwardPos())
1472 os << asString(dit.cell());
1476 CursorSlice i1 = cur.selBegin();
1477 CursorSlice i2 = cur.selEnd();
1479 if (i1.idx() == i2.idx()) {
1480 if (i1.inset().asInsetMath()) {
1481 MathData::const_iterator it = i1.cell().begin();
1482 Buffer * buf = cur.buffer();
1483 return asString(MathData(buf, it + i1.pos(), it + i2.pos()));
1485 return from_ascii("unknown selection 1");
1489 Inset::row_type r1, r2;
1490 Inset::col_type c1, c2;
1491 region(i1, i2, r1, r2, c1, c2);
1494 if (i1.inset().asInsetMath()) {
1495 for (Inset::row_type row = r1; row <= r2; ++row) {
1498 for (Inset::col_type col = c1; col <= c2; ++col) {
1501 data += asString(i1.asInsetMath()->
1502 cell(i1.asInsetMath()->index(row, col)));
1506 data = from_ascii("unknown selection 2");
1512 void dirtyTabularStack(bool b)
1514 dirty_tabular_stack_ = b;
1518 bool tabularStackDirty()
1520 return dirty_tabular_stack_;