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/InsetCommand.h"
44 #include "insets/InsetFlex.h"
45 #include "insets/InsetGraphics.h"
46 #include "insets/InsetGraphicsParams.h"
47 #include "insets/InsetInclude.h"
48 #include "insets/InsetLabel.h"
49 #include "insets/InsetTabular.h"
51 #include "mathed/MathData.h"
52 #include "mathed/InsetMath.h"
53 #include "mathed/InsetMathHull.h"
54 #include "mathed/InsetMathRef.h"
55 #include "mathed/MathSupport.h"
57 #include "support/debug.h"
58 #include "support/docstream.h"
59 #include "support/gettext.h"
60 #include "support/lassert.h"
61 #include "support/limited_stack.h"
62 #include "support/lstrings.h"
63 #include "support/lyxalgo.h"
64 #include "support/TempFile.h"
65 #include "support/unique_ptr.h"
67 #include "frontends/alert.h"
68 #include "frontends/Clipboard.h"
69 #include "frontends/Selection.h"
75 using namespace lyx::support;
76 using lyx::frontend::Clipboard;
82 typedef pair<pit_type, int> PitPosPair;
84 typedef limited_stack<pair<ParagraphList, DocumentClassConstPtr> > CutStack;
87 // persistent selection, cleared until the next selection
88 CutStack selectionBuffer(1);
89 // temporary scratch area
92 // store whether the tabular stack is newer than the normal copy stack
93 // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
94 // when we (hopefully) have a one-for-all paste mechanism.
95 bool dirty_tabular_stack_ = false;
98 bool checkPastePossible(int index)
100 return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
104 struct PasteReturnValue {
105 PasteReturnValue(pit_type r_pit, pos_type r_pos, bool r_nu) :
106 pit(r_pit), pos(r_pos), needupdate(r_nu)
115 pasteSelectionHelper(DocIterator const & cur, ParagraphList const & parlist,
116 DocumentClassConstPtr oldDocClass, cap::BranchAction branchAction,
117 ErrorList & errorlist)
119 Buffer const & buffer = *cur.buffer();
120 pit_type pit = cur.pit();
121 pos_type pos = cur.pos();
122 bool need_update = false;
125 return PasteReturnValue(pit, pos, need_update);
127 InsetText * target_inset = cur.inset().asInsetText();
129 InsetTabular * it = cur.inset().asInsetTabular();
130 target_inset = it ? it->cell(cur.idx())->asInsetText() : 0;
132 LASSERT(target_inset, return PasteReturnValue(pit, pos, need_update));
134 ParagraphList & pars = target_inset->paragraphs();
135 LASSERT(pos <= pars[pit].size(),
136 return PasteReturnValue(pit, pos, need_update));
138 // Make a copy of the CaP paragraphs.
139 ParagraphList insertion = parlist;
141 // Now remove all out of the pars which is NOT allowed in the
142 // new environment and set also another font if that is required.
144 // Convert newline to paragraph break in ParbreakIsNewline
145 if (target_inset->getLayout().parbreakIsNewline()
146 || pars[pit].layout().parbreak_is_newline) {
147 for (size_t i = 0; i != insertion.size(); ++i) {
148 for (pos_type j = 0; j != insertion[i].size(); ++j) {
149 if (insertion[i].isNewline(j)) {
150 // do not track deletion of newline
151 insertion[i].eraseChar(j, false);
152 insertion[i].setInsetOwner(target_inset);
153 breakParagraphConservative(
162 // set the paragraphs to plain layout if necessary
163 DocumentClassConstPtr newDocClass = buffer.params().documentClassPtr();
164 if (cur.inset().usePlainLayout()) {
165 bool forcePlainLayout = target_inset->forcePlainLayout();
166 Layout const & plainLayout = newDocClass->plainLayout();
167 Layout const & defaultLayout = newDocClass->defaultLayout();
168 ParagraphList::iterator const end = insertion.end();
169 ParagraphList::iterator par = insertion.begin();
170 for (; par != end; ++par) {
171 Layout const & parLayout = par->layout();
172 if (forcePlainLayout || parLayout == defaultLayout)
173 par->setLayout(plainLayout);
176 // check if we need to reset from plain layout
177 Layout const & defaultLayout = newDocClass->defaultLayout();
178 Layout const & plainLayout = newDocClass->plainLayout();
179 ParagraphList::iterator const end = insertion.end();
180 ParagraphList::iterator par = insertion.begin();
181 for (; par != end; ++par) {
182 Layout const & parLayout = par->layout();
183 if (parLayout == plainLayout)
184 par->setLayout(defaultLayout);
188 InsetText in(cur.buffer());
189 // Make sure there is no class difference.
190 in.paragraphs().clear();
191 // This works without copying any paragraph data because we have
192 // a specialized swap method for ParagraphList. This is important
193 // since we store pointers to insets at some places and we don't
194 // want to invalidate them.
195 insertion.swap(in.paragraphs());
196 cap::switchBetweenClasses(oldDocClass, newDocClass, in, errorlist);
197 insertion.swap(in.paragraphs());
199 ParagraphList::iterator tmpbuf = insertion.begin();
200 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
202 depth_type max_depth = pars[pit].getMaxDepthAfter();
204 for (; tmpbuf != insertion.end(); ++tmpbuf) {
205 // If we have a negative jump so that the depth would
206 // go below 0 depth then we have to redo the delta to
207 // this new max depth level so that subsequent
208 // paragraphs are aligned correctly to this paragraph
210 if (int(tmpbuf->params().depth()) + depth_delta < 0)
213 // Set the right depth so that we are not too deep or shallow.
214 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
215 if (tmpbuf->params().depth() > max_depth)
216 tmpbuf->params().depth(max_depth);
218 // Set max_depth for the next paragraph
219 max_depth = tmpbuf->getMaxDepthAfter();
221 // Set the inset owner of this paragraph.
222 tmpbuf->setInsetOwner(target_inset);
223 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
224 // do not track deletion of invalid insets
225 if (Inset * inset = tmpbuf->getInset(i))
226 if (!target_inset->insetAllowed(inset->lyxCode()))
227 tmpbuf->eraseChar(i--, false);
230 tmpbuf->setChange(Change(buffer.params().track_changes ?
231 Change::INSERTED : Change::UNCHANGED));
234 bool const empty = pars[pit].empty();
236 // Make the buf exactly the same layout as the cursor
238 insertion.begin()->makeSameLayout(pars[pit]);
241 // Prepare the paragraphs and insets for insertion.
242 insertion.swap(in.paragraphs());
244 InsetIterator const i_end = inset_iterator_end(in);
245 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
246 // Even though this will also be done later, it has to be done here
247 // since some inset might going to try to access
248 // the buffer() member.
249 it->setBuffer(const_cast<Buffer &>(buffer));
250 switch (it->lyxCode()) {
252 case MATH_HULL_CODE: {
253 // check for equation labels and resolve duplicates
254 InsetMathHull * ins = it->asInsetMath()->asHullInset();
255 std::vector<InsetLabel *> labels = ins->getLabels();
256 for (size_t i = 0; i != labels.size(); ++i) {
259 InsetLabel * lab = labels[i];
260 docstring const oldname = lab->getParam("name");
261 lab->updateLabel(oldname);
262 // We need to update the buffer reference cache.
264 docstring const newname = lab->getParam("name");
265 if (oldname == newname)
267 // adapt the references
268 for (InsetIterator itt = inset_iterator_begin(in);
269 itt != i_end; ++itt) {
270 if (itt->lyxCode() == REF_CODE) {
271 InsetCommand * ref = itt->asInsetCommand();
272 if (ref->getParam("reference") == oldname)
273 ref->setParam("reference", newname);
274 } else if (itt->lyxCode() == MATH_REF_CODE) {
275 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
276 // this is necessary to prevent an uninitialized
277 // buffer when the RefInset is in a MathBox.
278 // FIXME audit setBuffer calls
279 mi->setBuffer(const_cast<Buffer &>(buffer));
280 if (mi->getTarget() == oldname)
281 mi->changeTarget(newname);
289 // check for duplicates
290 InsetLabel & lab = static_cast<InsetLabel &>(*it);
291 docstring const oldname = lab.getParam("name");
292 lab.updateLabel(oldname);
293 // We need to update the buffer reference cache.
295 docstring const newname = lab.getParam("name");
296 if (oldname == newname)
298 // adapt the references
299 for (InsetIterator itt = inset_iterator_begin(in); itt != i_end; ++itt) {
300 if (itt->lyxCode() == REF_CODE) {
301 InsetCommand & ref = static_cast<InsetCommand &>(*itt);
302 if (ref.getParam("reference") == oldname)
303 ref.setParam("reference", newname);
304 } else if (itt->lyxCode() == MATH_REF_CODE) {
305 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
306 // this is necessary to prevent an uninitialized
307 // buffer when the RefInset is in a MathBox.
308 // FIXME audit setBuffer calls
309 mi->setBuffer(const_cast<Buffer &>(buffer));
310 if (mi->getTarget() == oldname)
311 mi->changeTarget(newname);
318 InsetInclude & inc = static_cast<InsetInclude &>(*it);
320 // We need to update the list of included files.
326 // check for duplicates
327 InsetBibitem & bib = static_cast<InsetBibitem &>(*it);
328 docstring const oldkey = bib.getParam("key");
329 bib.updateCommand(oldkey, false);
330 // We need to update the buffer reference cache.
332 docstring const newkey = bib.getParam("key");
333 if (oldkey == newkey)
335 // adapt the references
336 for (InsetIterator itt = inset_iterator_begin(in);
337 itt != i_end; ++itt) {
338 if (itt->lyxCode() == CITE_CODE) {
339 InsetCommand * ref = itt->asInsetCommand();
340 if (ref->getParam("key") == oldkey)
341 ref->setParam("key", newkey);
348 // check if branch is known to target buffer
350 InsetBranch & br = static_cast<InsetBranch &>(*it);
351 docstring const name = br.branch();
354 bool const is_child = (&buffer != buffer.masterBuffer());
355 BranchList branchlist = buffer.params().branchlist();
356 if ((!is_child && branchlist.find(name))
357 || (is_child && (branchlist.find(name)
358 || buffer.masterBuffer()->params().branchlist().find(name))))
360 switch(branchAction) {
361 case cap::BRANCH_ADD: {
362 // This is for a temporary buffer, so simply create the branch.
363 // Must not use lyx::dispatch(), since tmpbuffer has no view.
365 const_cast<Buffer&>(buffer).dispatch(FuncRequest(LFUN_BRANCH_ADD, name), dr);
368 case cap::BRANCH_ASK: {
369 docstring text = bformat(
370 _("The pasted branch \"%1$s\" is undefined.\n"
371 "Do you want to add it to the document's branch list?"),
373 if (frontend::Alert::prompt(_("Unknown branch"),
374 text, 0, 1, _("&Add"), _("&Don't Add")) != 0)
376 lyx::dispatch(FuncRequest(LFUN_BRANCH_ADD, name));
379 case cap::BRANCH_IGNORE:
382 // We need to update the list of branches.
391 insertion.swap(in.paragraphs());
393 // Split the paragraph for inserting the buf if necessary.
395 breakParagraphConservative(buffer.params(), pars, pit, pos);
399 pars.insert(lyx::next(pars.begin(), pit),
403 // merge the empty par with the last par of the insertion
404 mergeParagraph(buffer.params(), pars,
405 pit + insertion.size() - 1);
407 pars.insert(lyx::next(pars.begin(), pit + 1),
411 // merge the first par of the insertion with the current par
412 mergeParagraph(buffer.params(), pars, pit);
415 // Store the new cursor position.
416 pit_type last_paste = pit + insertion.size() - 1;
417 pit_type startpit = pit;
419 pos = pars[last_paste].size();
421 // FIXME Should we do it here, or should we let updateBuffer() do it?
422 // Set paragraph buffers. It's important to do this right away
423 // before something calls Inset::buffer() and causes a crash.
424 for (pit_type p = startpit; p <= pit; ++p)
425 pars[p].setBuffer(const_cast<Buffer &>(buffer));
427 // Join (conditionally) last pasted paragraph with next one, i.e.,
428 // the tail of the spliced document paragraph
429 if (!empty && last_paste + 1 != pit_type(pars.size())) {
430 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
431 mergeParagraph(buffer.params(), pars, last_paste);
432 } else if (pars[last_paste + 1].empty()) {
433 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
434 mergeParagraph(buffer.params(), pars, last_paste);
435 } else if (pars[last_paste].empty()) {
436 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
437 mergeParagraph(buffer.params(), pars, last_paste);
439 pars[last_paste + 1].stripLeadingSpaces(buffer.params().track_changes);
444 return PasteReturnValue(pit, pos, need_update);
448 PitPosPair eraseSelectionHelper(BufferParams const & params,
449 ParagraphList & pars,
450 pit_type startpit, pit_type endpit,
451 int startpos, int endpos)
453 // Start of selection is really invalid.
454 if (startpit == pit_type(pars.size()) ||
455 (startpos > pars[startpit].size()))
456 return PitPosPair(endpit, endpos);
458 // Start and end is inside same paragraph
459 if (endpit == pit_type(pars.size()) || startpit == endpit) {
460 endpos -= pars[startpit].eraseChars(startpos, endpos, params.track_changes);
461 return PitPosPair(endpit, endpos);
464 for (pit_type pit = startpit; pit != endpit + 1;) {
465 pos_type const left = (pit == startpit ? startpos : 0);
466 pos_type right = (pit == endpit ? endpos : pars[pit].size() + 1);
467 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.track_changes);
469 // Logically erase only, including the end-of-paragraph character
470 pars[pit].eraseChars(left, right, params.track_changes);
472 // Separate handling of paragraph break:
473 if (merge && pit != endpit &&
475 || pars[pit].hasSameLayout(pars[endpit])
476 || pars[endpit].size() == endpos)) {
477 if (pit + 1 == endpit)
478 endpos += pars[pit].size();
479 mergeParagraph(params, pars, pit);
485 // Ensure legal cursor pos:
488 return PitPosPair(endpit, endpos);
492 Buffer * copyToTempBuffer(ParagraphList const & paragraphs, DocumentClassConstPtr docclass)
494 // This used to need to be static to avoid a memory leak. It no longer needs
495 // to be so, but the alternative is to construct a new one of these (with a
496 // new temporary directory, etc) every time, and then to destroy it. So maybe
497 // it's worth just keeping this one around.
498 static TempFile tempfile("clipboard.internal");
499 tempfile.setAutoRemove(false);
500 // The initialization of staticbuffer is thread-safe. Using a lambda
501 // guarantees that the properties are set only once.
502 static Buffer * staticbuffer = [&](){
504 theBufferList().newInternalBuffer(tempfile.name().absFileName());
506 b->inset().setBuffer(*b);
507 //initialize staticbuffer with b
510 // Use a clone for the complicated stuff so that we do not need to clean
511 // up in order to avoid a crash.
512 Buffer * buffer = staticbuffer->cloneBufferOnly();
513 LASSERT(buffer, return 0);
515 // This needs doing every time.
516 // Since setDocumentClass() causes deletion of the old document class
517 // we need to reset all layout pointers in paragraphs (otherwise they
518 // would be dangling).
519 ParIterator const end = buffer->par_iterator_end();
520 for (ParIterator it = buffer->par_iterator_begin(); it != end; ++it) {
521 docstring const name = it->layout().name();
522 if (docclass->hasLayout(name))
523 it->setLayout((*docclass)[name]);
525 it->setPlainOrDefaultLayout(*docclass);
527 buffer->params().setDocumentClass(docclass);
529 // we will use pasteSelectionHelper to copy the paragraphs into the
530 // temporary Buffer, since it does a lot of things to fix them up.
531 DocIterator dit = doc_iterator_begin(buffer, &buffer->inset());
533 pasteSelectionHelper(dit, paragraphs, docclass, cap::BRANCH_ADD, el);
539 void putClipboard(ParagraphList const & paragraphs,
540 DocumentClassConstPtr docclass, docstring const & plaintext)
542 Buffer * buffer = copyToTempBuffer(paragraphs, docclass);
543 if (!buffer) // already asserted in copyToTempBuffer()
546 // We don't want to produce images that are not used. Therefore,
547 // output formulas as MathML. Even if this is not understood by all
548 // applications, the number that can parse it should go up in the future.
549 buffer->params().html_math_output = BufferParams::MathML;
551 // Make sure MarkAsExporting is deleted before buffer is
553 // The Buffer is being used to export. This is necessary so that the
554 // updateMacros call will record the needed information.
555 MarkAsExporting mex(buffer);
557 buffer->updateBuffer(Buffer::UpdateMaster, OutputUpdate);
558 buffer->updateMacros();
559 buffer->updateMacroInstances(OutputUpdate);
564 if (buffer->write(oslyx))
568 odocstringstream oshtml;
569 OutputParams runparams(encodings.fromLyXName("utf8"));
570 // We do not need to produce images, etc.
571 runparams.dryrun = true;
572 // We are not interested in errors (bug 8866)
573 runparams.silent = true;
574 buffer->writeLyXHTMLSource(oshtml, runparams, Buffer::FullSource);
576 theClipboard().put(lyx, oshtml.str(), plaintext);
584 /// return true if the whole ParagraphList is deleted
585 static bool isFullyDeleted(ParagraphList const & pars)
587 pit_type const pars_size = static_cast<pit_type>(pars.size());
589 // check all paragraphs
590 for (pit_type pit = 0; pit < pars_size; ++pit) {
591 if (!pars[pit].empty()) // prevent assertion failure
592 if (!pars[pit].isDeleted(0, pars[pit].size()))
599 void copySelectionHelper(Buffer const & buf, Text const & text,
600 pit_type startpit, pit_type endpit,
601 int start, int end, DocumentClassConstPtr dc, CutStack & cutstack)
603 ParagraphList const & pars = text.paragraphs();
605 // In most of these cases, we can try to recover.
606 LASSERT(0 <= start, start = 0);
607 LASSERT(start <= pars[startpit].size(), start = pars[startpit].size());
608 LASSERT(0 <= end, end = 0);
609 LASSERT(end <= pars[endpit].size(), end = pars[endpit].size());
610 LASSERT(startpit != endpit || start <= end, return);
612 // Clone the paragraphs within the selection.
613 ParagraphList copy_pars(lyx::next(pars.begin(), startpit),
614 lyx::next(pars.begin(), endpit + 1));
616 // Remove the end of the last paragraph; afterwards, remove the
617 // beginning of the first paragraph. Keep this order - there may only
618 // be one paragraph! Do not track deletions here; this is an internal
619 // action not visible to the user
621 Paragraph & back = copy_pars.back();
622 back.eraseChars(end, back.size(), false);
623 Paragraph & front = copy_pars.front();
624 front.eraseChars(0, start, false);
626 ParagraphList::iterator it = copy_pars.begin();
627 ParagraphList::iterator it_end = copy_pars.end();
629 for (; it != it_end; ++it) {
630 // Since we have a copy of the paragraphs, the insets
631 // do not have a proper buffer reference. It makes
632 // sense to add them temporarily, because the
633 // operations below depend on that (acceptChanges included).
634 it->setBuffer(const_cast<Buffer &>(buf));
635 // PassThru paragraphs have the Language
636 // latex_language. This is invalid for others, so we
637 // need to change it to the buffer language.
638 if (it->isPassThru())
639 it->changeLanguage(buf.params(),
640 latex_language, buf.language());
643 // do not copy text (also nested in insets) which is marked as
644 // deleted, unless the whole selection was deleted
645 if (!isFullyDeleted(copy_pars))
646 acceptChanges(copy_pars, buf.params());
648 rejectChanges(copy_pars, buf.params());
651 // do some final cleanup now, to make sure that the paragraphs
652 // are not linked to something else.
653 it = copy_pars.begin();
654 for (; it != it_end; ++it) {
655 it->setBuffer(*static_cast<Buffer *>(0));
656 it->setInsetOwner(0);
659 cutstack.push(make_pair(copy_pars, dc));
669 void region(CursorSlice const & i1, CursorSlice const & i2,
670 Inset::row_type & r1, Inset::row_type & r2,
671 Inset::col_type & c1, Inset::col_type & c2)
673 Inset & p = i1.inset();
674 c1 = p.col(i1.idx());
675 c2 = p.col(i2.idx());
678 r1 = p.row(i1.idx());
679 r2 = p.row(i2.idx());
685 docstring grabAndEraseSelection(Cursor & cur)
687 if (!cur.selection())
689 docstring res = grabSelection(cur);
695 bool reduceSelectionToOneCell(Cursor & cur)
697 if (!cur.selection() || !cur.inMathed())
700 CursorSlice i1 = cur.selBegin();
701 CursorSlice i2 = cur.selEnd();
702 if (!i1.inset().asInsetMath())
705 // the easy case: do nothing if only one cell is selected
706 if (i1.idx() == i2.idx())
711 cur.top().pos() = cur.top().lastpos();
717 bool multipleCellsSelected(Cursor const & cur)
719 if (!cur.selection() || !cur.inMathed())
722 CursorSlice i1 = cur.selBegin();
723 CursorSlice i2 = cur.selEnd();
724 if (!i1.inset().asInsetMath())
727 if (i1.idx() == i2.idx())
734 void switchBetweenClasses(DocumentClassConstPtr oldone,
735 DocumentClassConstPtr newone, InsetText & in, ErrorList & errorlist)
739 LBUFERR(!in.paragraphs().empty());
740 if (oldone == newone)
743 DocumentClass const & oldtc = *oldone;
744 DocumentClass const & newtc = *newone;
747 ParIterator it = par_iterator_begin(in);
748 ParIterator end = par_iterator_end(in);
749 // for remembering which layouts we've had to add
750 set<docstring> newlayouts;
751 for (; it != end; ++it) {
752 docstring const name = it->layout().name();
754 // the pasted text will keep their own layout name. If this layout does
755 // not exist in the new document, it will behave like a standard layout.
756 bool const added_one = newtc.addLayoutIfNeeded(name);
758 newlayouts.insert(name);
760 if (added_one || newlayouts.find(name) != newlayouts.end()) {
762 docstring const s = bformat(_("Layout `%1$s' was not found."), name);
763 errorlist.push_back(ErrorItem(_("Layout Not Found"), s,
764 {it->id(), 0}, {it->id(), -1}));
767 if (in.usePlainLayout())
768 it->setLayout(newtc.plainLayout());
770 it->setLayout(newtc[name]);
773 // character styles and hidden table cells
774 InsetIterator const i_end = inset_iterator_end(in);
775 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
776 InsetCode const code = it->lyxCode();
777 if (code == FLEX_CODE) {
778 // FIXME: Should we verify all InsetCollapsable?
779 docstring const layoutName = it->layoutName();
780 docstring const & n = newone->insetLayout(layoutName).name();
781 bool const is_undefined = n.empty() ||
782 n == DocumentClass::plainInsetLayout().name();
786 // The flex inset is undefined in newtc
787 docstring const oldname = from_utf8(oldtc.name());
788 docstring const newname = from_utf8(newtc.name());
790 if (oldname == newname)
791 s = bformat(_("Flex inset %1$s is undefined after "
792 "reloading `%2$s' layout."), layoutName, oldname);
794 s = bformat(_("Flex inset %1$s is undefined because of "
795 "conversion from `%2$s' layout to `%3$s'."),
796 layoutName, oldname, newname);
797 // To warn the user that something had to be done.
798 errorlist.push_back(ErrorItem(
799 _("Undefined flex inset"), s,
800 {it.paragraph().id(), it.pos()},
801 {it.paragraph().id(), it.pos()+1}));
802 } else if (code == TABULAR_CODE) {
803 // The recursion above does not catch paragraphs in "hidden" cells,
804 // i.e., ones that are part of a multirow or multicolum. So we need
805 // to handle those separately.
806 // This is the cause of bug #9049.
807 InsetTabular * table = it->asInsetTabular();
808 table->setLayoutForHiddenCells(newtc);
814 vector<docstring> availableSelections(Buffer const * buf)
816 vector<docstring> selList;
820 CutStack::const_iterator cit = theCuts.begin();
821 CutStack::const_iterator end = theCuts.end();
822 for (; cit != end; ++cit) {
823 // we do not use cit-> here because gcc 2.9x does not
825 ParagraphList const & pars = (*cit).first;
827 ParagraphList::const_iterator pit = pars.begin();
828 ParagraphList::const_iterator pend = pars.end();
829 for (; pit != pend; ++pit) {
830 Paragraph par(*pit, 0, 46);
831 // adapt paragraph to current buffer.
832 par.setBuffer(const_cast<Buffer &>(*buf));
833 textSel += par.asString(AS_STR_INSETS);
834 if (textSel.size() > 45) {
835 support::truncateWithEllipsis(textSel,45);
839 selList.push_back(textSel);
846 size_type numberOfSelections()
848 return theCuts.size();
853 void cutSelectionHelper(Cursor & cur, CutStack & cuts, bool doclear, bool realcut, bool putclip)
855 // This doesn't make sense, if there is no selection
856 if (!cur.selection())
859 // OK, we have a selection. This is always between cur.selBegin()
862 if (cur.inTexted()) {
863 Text * text = cur.text();
868 // make sure that the depth behind the selection are restored, too
869 cur.recordUndoSelection();
870 pit_type begpit = cur.selBegin().pit();
871 pit_type endpit = cur.selEnd().pit();
873 int endpos = cur.selEnd().pos();
875 BufferParams const & bp = cur.buffer()->params();
877 copySelectionHelper(*cur.buffer(),
880 cur.selBegin().pos(), endpos,
881 bp.documentClassPtr(), cuts);
882 // Stuff what we got on the clipboard.
883 // Even if there is no selection.
885 putClipboard(cuts[0].first, cuts[0].second,
886 cur.selectionAsString(true));
889 if (begpit != endpit)
890 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
892 tie(endpit, endpos) =
893 eraseSelectionHelper(bp, text->paragraphs(), begpit, endpit,
894 cur.selBegin().pos(), endpos);
896 // cutSelection can invalidate the cursor so we need to set
898 // we prefer the end for when tracking changes
902 // sometimes necessary
904 && text->paragraphs()[begpit].stripLeadingSpaces(bp.track_changes))
907 // need a valid cursor. (Lgb)
908 cur.clearSelection();
910 // After a cut operation, we must make sure that the Buffer is updated
911 // because some further operation might need updated label information for
912 // example. So we cannot just use "cur.forceBufferUpdate()" here.
914 cur.buffer()->updateBuffer();
916 // tell tabular that a recent copy happened
917 dirtyTabularStack(false);
920 if (cur.inMathed()) {
921 if (cur.selBegin().idx() != cur.selEnd().idx()) {
922 // The current selection spans more than one cell.
924 cur.recordUndoInset();
926 // Record only the current cell to avoid a jumping
938 void cutSelection(Cursor & cur, bool doclear, bool realcut)
940 cutSelectionHelper(cur, theCuts, doclear, realcut, true);
944 void cutSelectionToTemp(Cursor & cur, bool doclear, bool realcut)
946 cutSelectionHelper(cur, tempCut, doclear, realcut, false);
950 void copySelection(Cursor const & cur)
952 copySelection(cur, cur.selectionAsString(true));
956 void copyInset(Cursor const & cur, Inset * inset, docstring const & plaintext)
960 BufferParams const & bp = cur.buffer()->params();
961 par.setLayout(bp.documentClass().plainLayout());
962 Font font(inherit_font, bp.language);
963 par.insertInset(0, inset, font, Change(Change::UNCHANGED));
965 theCuts.push(make_pair(pars, bp.documentClassPtr()));
967 // stuff the selection onto the X clipboard, from an explicit copy request
968 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
974 void copySelectionToStack(Cursor const & cur, CutStack & cutstack)
976 // this doesn't make sense, if there is no selection
977 if (!cur.selection())
980 // copySelection can not yet handle the case of cross idx selection
981 if (cur.selBegin().idx() != cur.selEnd().idx())
984 if (cur.inTexted()) {
985 Text * text = cur.text();
987 // ok we have a selection. This is always between cur.selBegin()
988 // and sel_end cursor
989 copySelectionHelper(*cur.buffer(), *text,
990 cur.selBegin().pit(), cur.selEnd().pit(),
991 cur.selBegin().pos(), cur.selEnd().pos(),
992 cur.buffer()->params().documentClassPtr(),
994 // Reset the dirty_tabular_stack_ flag only when something
995 // is copied to the clipboard (not to the selectionBuffer).
996 if (&cutstack == &theCuts)
997 dirtyTabularStack(false);
1000 if (cur.inMathed()) {
1001 //lyxerr << "copySelection in mathed" << endl;
1004 BufferParams const & bp = cur.buffer()->params();
1005 // FIXME This should be the plain layout...right?
1006 par.setLayout(bp.documentClass().plainLayout());
1007 par.insert(0, grabSelection(cur), Font(), Change(Change::UNCHANGED));
1008 pars.push_back(par);
1009 cutstack.push(make_pair(pars, bp.documentClassPtr()));
1016 void copySelectionToStack()
1018 if (!selectionBuffer.empty())
1019 theCuts.push(selectionBuffer[0]);
1023 void copySelection(Cursor const & cur, docstring const & plaintext)
1025 // In tablemode, because copy and paste actually use special table stack
1026 // we do not attempt to get selected paragraphs under cursor. Instead, a
1027 // paragraph with the plain text version is generated so that table cells
1028 // can be pasted as pure text somewhere else.
1029 if (cur.selBegin().idx() != cur.selEnd().idx()) {
1032 BufferParams const & bp = cur.buffer()->params();
1033 par.setLayout(bp.documentClass().plainLayout());
1034 par.insert(0, plaintext, Font(), Change(Change::UNCHANGED));
1035 pars.push_back(par);
1036 theCuts.push(make_pair(pars, bp.documentClassPtr()));
1038 copySelectionToStack(cur, theCuts);
1041 // stuff the selection onto the X clipboard, from an explicit copy request
1042 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
1046 void saveSelection(Cursor const & cur)
1048 // This function is called, not when a selection is formed, but when
1049 // a selection is cleared. Therefore, multiple keyboard selection
1050 // will not repeatively trigger this function (bug 3877).
1052 && cur.selBegin() == cur.bv().cursor().selBegin()
1053 && cur.selEnd() == cur.bv().cursor().selEnd()) {
1054 LYXERR(Debug::SELECTION, "saveSelection: '" << cur.selectionAsString(true) << "'");
1055 copySelectionToStack(cur, selectionBuffer);
1062 return !selectionBuffer.empty();
1066 void clearSelection()
1068 selectionBuffer.clear();
1072 void clearCutStack()
1078 docstring selection(size_t sel_index, DocumentClassConstPtr docclass)
1080 if (sel_index >= theCuts.size())
1083 unique_ptr<Buffer> buffer(copyToTempBuffer(theCuts[sel_index].first,
1088 return buffer->paragraphs().back().asString(AS_STR_INSETS | AS_STR_NEWLINES);
1092 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
1093 DocumentClassConstPtr docclass, ErrorList & errorList,
1094 cap::BranchAction branchAction)
1096 if (cur.inTexted()) {
1097 Text * text = cur.text();
1100 PasteReturnValue prv =
1101 pasteSelectionHelper(cur, parlist, docclass, branchAction, errorList);
1102 cur.forceBufferUpdate();
1103 cur.clearSelection();
1104 text->setCursor(cur, prv.pit, prv.pos);
1107 // mathed is handled in InsetMathNest/InsetMathGrid
1108 LATTEST(!cur.inMathed());
1112 bool pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
1114 // this does not make sense, if there is nothing to paste
1115 if (!checkPastePossible(sel_index))
1119 pasteParagraphList(cur, theCuts[sel_index].first,
1120 theCuts[sel_index].second, errorList, BRANCH_ASK);
1125 bool pasteFromTemp(Cursor & cur, ErrorList & errorList)
1127 // this does not make sense, if there is nothing to paste
1128 if (tempCut.empty() || tempCut[0].first.empty())
1132 pasteParagraphList(cur, tempCut[0].first,
1133 tempCut[0].second, errorList, BRANCH_IGNORE);
1138 bool pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs,
1139 Clipboard::TextType type)
1141 // Use internal clipboard if it is the most recent one
1142 // This overrides asParagraphs and type on purpose!
1143 if (theClipboard().isInternal())
1144 return pasteFromStack(cur, errorList, 0);
1146 // First try LyX format
1147 if ((type == Clipboard::LyXTextType ||
1148 type == Clipboard::LyXOrPlainTextType ||
1149 type == Clipboard::AnyTextType) &&
1150 theClipboard().hasTextContents(Clipboard::LyXTextType)) {
1151 string lyx = theClipboard().getAsLyX();
1153 // For some strange reason gcc 3.2 and 3.3 do not accept
1154 // Buffer buffer(string(), false);
1155 Buffer buffer("", false);
1156 buffer.setUnnamed(true);
1157 if (buffer.readString(lyx)) {
1159 pasteParagraphList(cur, buffer.paragraphs(),
1160 buffer.params().documentClassPtr(), errorList);
1166 // Then try TeX and HTML
1167 Clipboard::TextType types[2] = {Clipboard::HtmlTextType, Clipboard::LaTeXTextType};
1168 string names[2] = {"html", "latexclipboard"};
1169 for (int i = 0; i < 2; ++i) {
1170 if (type != types[i] && type != Clipboard::AnyTextType)
1172 bool available = theClipboard().hasTextContents(types[i]);
1174 // If a specific type was explicitly requested, try to
1175 // interpret plain text: The user told us that the clipboard
1176 // contents is in the desired format
1177 if (!available && type == types[i]) {
1178 types[i] = Clipboard::PlainTextType;
1179 available = theClipboard().hasTextContents(types[i]);
1183 docstring text = theClipboard().getAsText(types[i]);
1184 available = !text.empty();
1186 // For some strange reason gcc 3.2 and 3.3 do not accept
1187 // Buffer buffer(string(), false);
1188 Buffer buffer("", false);
1189 buffer.setUnnamed(true);
1190 available = buffer.importString(names[i], text, errorList);
1192 available = !buffer.paragraphs().empty();
1193 if (available && !buffer.paragraphs()[0].empty()) {
1195 pasteParagraphList(cur, buffer.paragraphs(),
1196 buffer.params().documentClassPtr(), errorList);
1203 // Then try plain text
1204 docstring const text = theClipboard().getAsText(Clipboard::PlainTextType);
1209 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1211 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1212 cur.forceBufferUpdate();
1217 void pasteSimpleText(Cursor & cur, bool asParagraphs)
1220 // Use internal clipboard if it is the most recent one
1221 if (theClipboard().isInternal()) {
1222 if (!checkPastePossible(0))
1225 ParagraphList const & pars = theCuts[0].first;
1226 ParagraphList::const_iterator it = pars.begin();
1227 for (; it != pars.end(); ++it) {
1228 if (it != pars.begin())
1230 text += (*it).asString();
1232 asParagraphs = false;
1234 // Then try plain text
1235 text = theClipboard().getAsText(Clipboard::PlainTextType);
1242 cutSelection(cur, true, false);
1244 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1246 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1250 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
1251 Clipboard::GraphicsType preferedType)
1253 LASSERT(theClipboard().hasGraphicsContents(preferedType), return);
1255 // get picture from clipboard
1256 FileName filename = theClipboard().getAsGraphics(cur, preferedType);
1257 if (filename.empty())
1260 // create inset for graphic
1261 InsetGraphics * inset = new InsetGraphics(cur.buffer());
1262 InsetGraphicsParams params;
1263 params.filename = support::DocFileName(filename.absFileName(), false);
1264 inset->setParams(params);
1270 void pasteSelection(Cursor & cur, ErrorList & errorList)
1272 if (selectionBuffer.empty())
1275 pasteParagraphList(cur, selectionBuffer[0].first,
1276 selectionBuffer[0].second, errorList);
1280 void replaceSelectionWithString(Cursor & cur, docstring const & str)
1283 DocIterator selbeg = cur.selectionBegin();
1285 // Get font setting before we cut, we need a copy here, not a bare reference.
1287 selbeg.paragraph().getFontSettings(cur.buffer()->params(), selbeg.pos());
1289 // Insert the new string
1290 pos_type pos = cur.selEnd().pos();
1291 Paragraph & par = cur.selEnd().paragraph();
1292 docstring::const_iterator cit = str.begin();
1293 docstring::const_iterator end = str.end();
1294 for (; cit != end; ++cit, ++pos)
1295 par.insertChar(pos, *cit, font, cur.buffer()->params().track_changes);
1297 // Cut the selection
1298 cutSelection(cur, true, false);
1302 void replaceSelection(Cursor & cur)
1304 if (cur.selection())
1305 cutSelection(cur, true, false);
1309 void eraseSelection(Cursor & cur)
1311 //lyxerr << "cap::eraseSelection begin: " << cur << endl;
1312 CursorSlice const & i1 = cur.selBegin();
1313 CursorSlice const & i2 = cur.selEnd();
1314 if (!i1.asInsetMath()) {
1315 LYXERR0("Can't erase this selection");
1321 InsetMath * p = i1.asInsetMath();
1322 if (i1.idx() == i2.idx()) {
1323 i1.cell().erase(i1.pos(), i2.pos());
1324 // We may have deleted i1.cell(cur.pos()).
1325 // Make sure that pos is valid.
1326 if (cur.pos() > cur.lastpos())
1327 cur.pos() = cur.lastpos();
1328 } else if (p->nrows() > 0 && p->ncols() > 0) {
1329 // This is a grid, delete a nice square region
1330 Inset::row_type r1, r2;
1331 Inset::col_type c1, c2;
1332 region(i1, i2, r1, r2, c1, c2);
1333 for (Inset::row_type row = r1; row <= r2; ++row)
1334 for (Inset::col_type col = c1; col <= c2; ++col)
1335 p->cell(p->index(row, col)).clear();
1336 // We've deleted the whole cell. Only pos 0 is valid.
1339 Inset::idx_type idx1 = i1.idx();
1340 Inset::idx_type idx2 = i2.idx();
1343 for (Inset::idx_type idx = idx1 ; idx <= idx2; ++idx)
1344 p->cell(idx).clear();
1345 // We've deleted the whole cell. Only pos 0 is valid.
1349 // need a valid cursor. (Lgb)
1350 cur.clearSelection();
1351 //lyxerr << "cap::eraseSelection end: " << cur << endl;
1355 void selDel(Cursor & cur)
1357 //lyxerr << "cap::selDel" << endl;
1358 if (cur.selection())
1359 eraseSelection(cur);
1363 void selClearOrDel(Cursor & cur)
1365 //lyxerr << "cap::selClearOrDel" << endl;
1366 if (lyxrc.auto_region_delete)
1369 cur.selection(false);
1373 docstring grabSelection(Cursor const & cur)
1375 if (!cur.selection())
1379 // grab selection by glueing multiple cells together. This is not what
1380 // we want because selections spanning multiple cells will get "&" and "\\"
1383 for (DocIterator dit = cur.selectionBegin();
1384 dit != cur.selectionEnd(); dit.forwardPos())
1385 os << asString(dit.cell());
1389 CursorSlice i1 = cur.selBegin();
1390 CursorSlice i2 = cur.selEnd();
1392 if (i1.idx() == i2.idx()) {
1393 if (i1.inset().asInsetMath()) {
1394 MathData::const_iterator it = i1.cell().begin();
1395 Buffer * buf = cur.buffer();
1396 return asString(MathData(buf, it + i1.pos(), it + i2.pos()));
1398 return from_ascii("unknown selection 1");
1402 Inset::row_type r1, r2;
1403 Inset::col_type c1, c2;
1404 region(i1, i2, r1, r2, c1, c2);
1407 if (i1.inset().asInsetMath()) {
1408 for (Inset::row_type row = r1; row <= r2; ++row) {
1411 for (Inset::col_type col = c1; col <= c2; ++col) {
1414 data += asString(i1.asInsetMath()->
1415 cell(i1.asInsetMath()->index(row, col)));
1419 data = from_ascii("unknown selection 2");
1425 void dirtyTabularStack(bool b)
1427 dirty_tabular_stack_ = b;
1431 bool tabularStackDirty()
1433 return dirty_tabular_stack_;