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 InsetText * target_inset = cur.inset().asInsetText();
130 InsetTabular * it = cur.inset().asInsetTabular();
131 target_inset = it ? it->cell(cur.idx())->asInsetText() : 0;
133 LASSERT(target_inset, return PasteReturnValue(pit, pos, need_update));
135 ParagraphList & pars = target_inset->paragraphs();
136 LASSERT(pos <= pars[pit].size(),
137 return PasteReturnValue(pit, pos, need_update));
139 // Make a copy of the CaP paragraphs.
140 ParagraphList insertion = parlist;
142 // Now remove all out of the pars which is NOT allowed in the
143 // new environment and set also another font if that is required.
145 // Convert newline to paragraph break in ParbreakIsNewline
146 if (target_inset->getLayout().parbreakIsNewline()
147 || pars[pit].layout().parbreak_is_newline) {
148 for (size_t i = 0; i != insertion.size(); ++i) {
149 for (pos_type j = 0; j != insertion[i].size(); ++j) {
150 if (insertion[i].isNewline(j)) {
151 // do not track deletion of newline
152 insertion[i].eraseChar(j, false);
153 insertion[i].setInsetOwner(target_inset);
154 breakParagraphConservative(
163 // set the paragraphs to plain layout if necessary
164 DocumentClassConstPtr newDocClass = buffer.params().documentClassPtr();
165 if (cur.inset().usePlainLayout()) {
166 bool forcePlainLayout = target_inset->forcePlainLayout();
167 Layout const & plainLayout = newDocClass->plainLayout();
168 Layout const & defaultLayout = newDocClass->defaultLayout();
169 ParagraphList::iterator const end = insertion.end();
170 ParagraphList::iterator par = insertion.begin();
171 for (; par != end; ++par) {
172 Layout const & parLayout = par->layout();
173 if (forcePlainLayout || parLayout == defaultLayout)
174 par->setLayout(plainLayout);
177 // check if we need to reset from plain layout
178 Layout const & defaultLayout = newDocClass->defaultLayout();
179 Layout const & plainLayout = newDocClass->plainLayout();
180 ParagraphList::iterator const end = insertion.end();
181 ParagraphList::iterator par = insertion.begin();
182 for (; par != end; ++par) {
183 Layout const & parLayout = par->layout();
184 if (parLayout == plainLayout)
185 par->setLayout(defaultLayout);
189 InsetText in(cur.buffer());
190 // Make sure there is no class difference.
191 in.paragraphs().clear();
192 // This works without copying any paragraph data because we have
193 // a specialized swap method for ParagraphList. This is important
194 // since we store pointers to insets at some places and we don't
195 // want to invalidate them.
196 insertion.swap(in.paragraphs());
197 cap::switchBetweenClasses(oldDocClass, newDocClass, in, errorlist);
198 insertion.swap(in.paragraphs());
200 ParagraphList::iterator tmpbuf = insertion.begin();
201 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
203 depth_type max_depth = pars[pit].getMaxDepthAfter();
205 for (; tmpbuf != insertion.end(); ++tmpbuf) {
206 // If we have a negative jump so that the depth would
207 // go below 0 depth then we have to redo the delta to
208 // this new max depth level so that subsequent
209 // paragraphs are aligned correctly to this paragraph
211 if (int(tmpbuf->params().depth()) + depth_delta < 0)
214 // Set the right depth so that we are not too deep or shallow.
215 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
216 if (tmpbuf->params().depth() > max_depth)
217 tmpbuf->params().depth(max_depth);
219 // Set max_depth for the next paragraph
220 max_depth = tmpbuf->getMaxDepthAfter();
222 // Set the inset owner of this paragraph.
223 tmpbuf->setInsetOwner(target_inset);
224 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
225 // do not track deletion of invalid insets
226 if (Inset * inset = tmpbuf->getInset(i))
227 if (!target_inset->insetAllowed(inset->lyxCode()))
228 tmpbuf->eraseChar(i--, false);
231 tmpbuf->setChange(Change(buffer.params().track_changes ?
232 Change::INSERTED : Change::UNCHANGED));
235 bool const empty = pars[pit].empty();
237 // Make the buf exactly the same layout as the cursor
239 insertion.begin()->makeSameLayout(pars[pit]);
242 // Prepare the paragraphs and insets for insertion.
243 insertion.swap(in.paragraphs());
245 InsetIterator const i_end = inset_iterator_end(in);
246 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
247 // Even though this will also be done later, it has to be done here
248 // since some inset might going to try to access
249 // the buffer() member.
250 it->setBuffer(const_cast<Buffer &>(buffer));
251 switch (it->lyxCode()) {
253 case MATH_HULL_CODE: {
254 // check for equation labels and resolve duplicates
255 InsetMathHull * ins = it->asInsetMath()->asHullInset();
256 std::vector<InsetLabel *> labels = ins->getLabels();
257 for (size_t i = 0; i != labels.size(); ++i) {
260 InsetLabel * lab = labels[i];
261 docstring const oldname = lab->getParam("name");
262 lab->updateLabel(oldname);
263 // We need to update the buffer reference cache.
265 docstring const newname = lab->getParam("name");
266 if (oldname == newname)
268 // adapt the references
269 for (InsetIterator itt = inset_iterator_begin(in);
270 itt != i_end; ++itt) {
271 if (itt->lyxCode() == REF_CODE) {
272 InsetCommand * ref = itt->asInsetCommand();
273 if (ref->getParam("reference") == oldname)
274 ref->setParam("reference", newname);
275 } else if (itt->lyxCode() == MATH_REF_CODE) {
276 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
277 // this is necessary to prevent an uninitialized
278 // buffer when the RefInset is in a MathBox.
279 // FIXME audit setBuffer calls
280 mi->setBuffer(const_cast<Buffer &>(buffer));
281 if (mi->getTarget() == oldname)
282 mi->changeTarget(newname);
290 // check for duplicates
291 InsetLabel & lab = static_cast<InsetLabel &>(*it);
292 docstring const oldname = lab.getParam("name");
293 lab.updateLabel(oldname);
294 // We need to update the buffer reference cache.
296 docstring const newname = lab.getParam("name");
297 if (oldname == newname)
299 // adapt the references
300 for (InsetIterator itt = inset_iterator_begin(in); itt != i_end; ++itt) {
301 if (itt->lyxCode() == REF_CODE) {
302 InsetCommand & ref = static_cast<InsetCommand &>(*itt);
303 if (ref.getParam("reference") == oldname)
304 ref.setParam("reference", newname);
305 } else if (itt->lyxCode() == MATH_REF_CODE) {
306 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
307 // this is necessary to prevent an uninitialized
308 // buffer when the RefInset is in a MathBox.
309 // FIXME audit setBuffer calls
310 mi->setBuffer(const_cast<Buffer &>(buffer));
311 if (mi->getTarget() == oldname)
312 mi->changeTarget(newname);
319 InsetInclude & inc = static_cast<InsetInclude &>(*it);
321 // We need to update the list of included files.
327 InsetCitation & cit = static_cast<InsetCitation &>(*it);
328 // This actually only needs to be done if the cite engine
329 // differs, but we do it in general.
331 // We need to update the list of citations.
337 // check for duplicates
338 InsetBibitem & bib = static_cast<InsetBibitem &>(*it);
339 docstring const oldkey = bib.getParam("key");
340 bib.updateCommand(oldkey, false);
341 // We need to update the buffer reference cache.
343 docstring const newkey = bib.getParam("key");
344 if (oldkey == newkey)
346 // adapt the references
347 for (InsetIterator itt = inset_iterator_begin(in);
348 itt != i_end; ++itt) {
349 if (itt->lyxCode() == CITE_CODE) {
350 InsetCommand * ref = itt->asInsetCommand();
351 if (ref->getParam("key") == oldkey)
352 ref->setParam("key", newkey);
359 // check if branch is known to target buffer
361 InsetBranch & br = static_cast<InsetBranch &>(*it);
362 docstring const name = br.branch();
365 bool const is_child = (&buffer != buffer.masterBuffer());
366 BranchList branchlist = buffer.params().branchlist();
367 if ((!is_child && branchlist.find(name))
368 || (is_child && (branchlist.find(name)
369 || buffer.masterBuffer()->params().branchlist().find(name))))
371 switch(branchAction) {
372 case cap::BRANCH_ADD: {
373 // This is for a temporary buffer, so simply create the branch.
374 // Must not use lyx::dispatch(), since tmpbuffer has no view.
376 const_cast<Buffer&>(buffer).dispatch(FuncRequest(LFUN_BRANCH_ADD, name), dr);
379 case cap::BRANCH_ASK: {
380 docstring text = bformat(
381 _("The pasted branch \"%1$s\" is undefined.\n"
382 "Do you want to add it to the document's branch list?"),
384 if (frontend::Alert::prompt(_("Unknown branch"),
385 text, 0, 1, _("&Add"), _("&Don't Add")) != 0)
387 lyx::dispatch(FuncRequest(LFUN_BRANCH_ADD, name));
390 case cap::BRANCH_IGNORE:
393 // We need to update the list of branches.
402 insertion.swap(in.paragraphs());
404 // Split the paragraph for inserting the buf if necessary.
406 breakParagraphConservative(buffer.params(), pars, pit, pos);
410 pars.insert(lyx::next(pars.begin(), pit),
414 // merge the empty par with the last par of the insertion
415 mergeParagraph(buffer.params(), pars,
416 pit + insertion.size() - 1);
418 pars.insert(lyx::next(pars.begin(), pit + 1),
422 // merge the first par of the insertion with the current par
423 mergeParagraph(buffer.params(), pars, pit);
426 // Store the new cursor position.
427 pit_type last_paste = pit + insertion.size() - 1;
428 pit_type startpit = pit;
430 pos = pars[last_paste].size();
432 // FIXME Should we do it here, or should we let updateBuffer() do it?
433 // Set paragraph buffers. It's important to do this right away
434 // before something calls Inset::buffer() and causes a crash.
435 for (pit_type p = startpit; p <= pit; ++p)
436 pars[p].setInsetBuffers(const_cast<Buffer &>(buffer));
438 // Join (conditionally) last pasted paragraph with next one, i.e.,
439 // the tail of the spliced document paragraph
440 if (!empty && last_paste + 1 != pit_type(pars.size())) {
441 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
442 mergeParagraph(buffer.params(), pars, last_paste);
443 } else if (pars[last_paste + 1].empty()) {
444 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
445 mergeParagraph(buffer.params(), pars, last_paste);
446 } else if (pars[last_paste].empty()) {
447 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
448 mergeParagraph(buffer.params(), pars, last_paste);
450 pars[last_paste + 1].stripLeadingSpaces(buffer.params().track_changes);
455 return PasteReturnValue(pit, pos, need_update);
459 PitPosPair eraseSelectionHelper(BufferParams const & params,
460 ParagraphList & pars,
461 pit_type startpit, pit_type endpit,
462 int startpos, int endpos)
464 // Start of selection is really invalid.
465 if (startpit == pit_type(pars.size()) ||
466 (startpos > pars[startpit].size()))
467 return PitPosPair(endpit, endpos);
469 // Start and end is inside same paragraph
470 if (endpit == pit_type(pars.size()) || startpit == endpit) {
471 endpos -= pars[startpit].eraseChars(startpos, endpos, params.track_changes);
472 return PitPosPair(endpit, endpos);
475 for (pit_type pit = startpit; pit != endpit + 1;) {
476 pos_type const left = (pit == startpit ? startpos : 0);
477 pos_type right = (pit == endpit ? endpos : pars[pit].size() + 1);
478 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.track_changes);
480 // Logically erase only, including the end-of-paragraph character
481 pars[pit].eraseChars(left, right, params.track_changes);
483 // Separate handling of paragraph break:
484 if (merge && pit != endpit &&
486 || pars[pit].hasSameLayout(pars[endpit])
487 || pars[endpit].size() == endpos)) {
488 if (pit + 1 == endpit)
489 endpos += pars[pit].size();
490 mergeParagraph(params, pars, pit);
496 // Ensure legal cursor pos:
499 return PitPosPair(endpit, endpos);
503 Buffer * copyToTempBuffer(ParagraphList const & paragraphs, DocumentClassConstPtr docclass)
505 // This used to need to be static to avoid a memory leak. It no longer needs
506 // to be so, but the alternative is to construct a new one of these (with a
507 // new temporary directory, etc) every time, and then to destroy it. So maybe
508 // it's worth just keeping this one around.
509 static TempFile tempfile("clipboard.internal");
510 tempfile.setAutoRemove(false);
511 // The initialization of staticbuffer is thread-safe. Using a lambda
512 // guarantees that the properties are set only once.
513 static Buffer * staticbuffer = [&](){
515 theBufferList().newInternalBuffer(tempfile.name().absFileName());
517 b->inset().setBuffer(*b);
518 //initialize staticbuffer with b
521 // Use a clone for the complicated stuff so that we do not need to clean
522 // up in order to avoid a crash.
523 Buffer * buffer = staticbuffer->cloneBufferOnly();
524 LASSERT(buffer, return 0);
526 // This needs doing every time.
527 // Since setDocumentClass() causes deletion of the old document class
528 // we need to reset all layout pointers in paragraphs (otherwise they
529 // would be dangling).
530 ParIterator const end = buffer->par_iterator_end();
531 for (ParIterator it = buffer->par_iterator_begin(); it != end; ++it) {
532 docstring const name = it->layout().name();
533 if (docclass->hasLayout(name))
534 it->setLayout((*docclass)[name]);
536 it->setPlainOrDefaultLayout(*docclass);
538 buffer->params().setDocumentClass(docclass);
540 // we will use pasteSelectionHelper to copy the paragraphs into the
541 // temporary Buffer, since it does a lot of things to fix them up.
542 DocIterator dit = doc_iterator_begin(buffer, &buffer->inset());
544 pasteSelectionHelper(dit, paragraphs, docclass, cap::BRANCH_ADD, el);
550 void putClipboard(ParagraphList const & paragraphs,
551 DocumentClassConstPtr docclass, docstring const & plaintext)
553 Buffer * buffer = copyToTempBuffer(paragraphs, docclass);
554 if (!buffer) // already asserted in copyToTempBuffer()
557 // We don't want to produce images that are not used. Therefore,
558 // output formulas as MathML. Even if this is not understood by all
559 // applications, the number that can parse it should go up in the future.
560 buffer->params().html_math_output = BufferParams::MathML;
562 // Make sure MarkAsExporting is deleted before buffer is
564 // The Buffer is being used to export. This is necessary so that the
565 // updateMacros call will record the needed information.
566 MarkAsExporting mex(buffer);
568 buffer->updateBuffer(Buffer::UpdateMaster, OutputUpdate);
569 buffer->updateMacros();
570 buffer->updateMacroInstances(OutputUpdate);
575 if (buffer->write(oslyx))
579 odocstringstream oshtml;
580 OutputParams runparams(encodings.fromLyXName("utf8"));
581 // We do not need to produce images, etc.
582 runparams.dryrun = true;
583 // We are not interested in errors (bug 8866)
584 runparams.silent = true;
585 buffer->writeLyXHTMLSource(oshtml, runparams, Buffer::FullSource);
587 theClipboard().put(lyx, oshtml.str(), plaintext);
595 /// return true if the whole ParagraphList is deleted
596 static bool isFullyDeleted(ParagraphList const & pars)
598 pit_type const pars_size = static_cast<pit_type>(pars.size());
600 // check all paragraphs
601 for (pit_type pit = 0; pit < pars_size; ++pit) {
602 if (!pars[pit].empty()) // prevent assertion failure
603 if (!pars[pit].isDeleted(0, pars[pit].size()))
610 void copySelectionHelper(Buffer const & buf, Text const & text,
611 pit_type startpit, pit_type endpit,
612 int start, int end, DocumentClassConstPtr dc, CutStack & cutstack)
614 ParagraphList const & pars = text.paragraphs();
616 // In most of these cases, we can try to recover.
617 LASSERT(0 <= start, start = 0);
618 LASSERT(start <= pars[startpit].size(), start = pars[startpit].size());
619 LASSERT(0 <= end, end = 0);
620 LASSERT(end <= pars[endpit].size(), end = pars[endpit].size());
621 LASSERT(startpit != endpit || start <= end, return);
623 // Clone the paragraphs within the selection.
624 ParagraphList copy_pars(lyx::next(pars.begin(), startpit),
625 lyx::next(pars.begin(), endpit + 1));
627 // Remove the end of the last paragraph; afterwards, remove the
628 // beginning of the first paragraph. Keep this order - there may only
629 // be one paragraph! Do not track deletions here; this is an internal
630 // action not visible to the user
632 Paragraph & back = copy_pars.back();
633 back.eraseChars(end, back.size(), false);
634 Paragraph & front = copy_pars.front();
635 front.eraseChars(0, start, false);
637 ParagraphList::iterator it = copy_pars.begin();
638 ParagraphList::iterator it_end = copy_pars.end();
640 for (; it != it_end; ++it) {
641 // Since we have a copy of the paragraphs, the insets
642 // do not have a proper buffer reference. It makes
643 // sense to add them temporarily, because the
644 // operations below depend on that (acceptChanges included).
645 it->setInsetBuffers(const_cast<Buffer &>(buf));
646 // PassThru paragraphs have the Language
647 // latex_language. This is invalid for others, so we
648 // need to change it to the buffer language.
649 if (it->isPassThru())
650 it->changeLanguage(buf.params(),
651 latex_language, buf.language());
654 // do not copy text (also nested in insets) which is marked as
655 // deleted, unless the whole selection was deleted
656 if (!isFullyDeleted(copy_pars))
657 acceptChanges(copy_pars, buf.params());
659 rejectChanges(copy_pars, buf.params());
662 // do some final cleanup now, to make sure that the paragraphs
663 // are not linked to something else.
664 it = copy_pars.begin();
665 for (; it != it_end; ++it) {
667 it->setInsetOwner(0);
670 cutstack.push(make_pair(copy_pars, dc));
678 void region(CursorSlice const & i1, CursorSlice const & i2,
679 Inset::row_type & r1, Inset::row_type & r2,
680 Inset::col_type & c1, Inset::col_type & c2)
682 Inset & p = i1.inset();
683 c1 = p.col(i1.idx());
684 c2 = p.col(i2.idx());
687 r1 = p.row(i1.idx());
688 r2 = p.row(i2.idx());
694 docstring grabAndEraseSelection(Cursor & cur)
696 if (!cur.selection())
698 docstring res = grabSelection(cur);
704 bool reduceSelectionToOneCell(CursorData & cur)
706 if (!cur.selection() || !cur.inMathed())
709 CursorSlice i1 = cur.selBegin();
710 CursorSlice i2 = cur.selEnd();
711 if (!i1.inset().asInsetMath())
714 // the easy case: do nothing if only one cell is selected
715 if (i1.idx() == i2.idx())
720 cur.top().pos() = cur.top().lastpos();
726 bool multipleCellsSelected(CursorData const & cur)
728 if (!cur.selection() || !cur.inMathed())
731 CursorSlice i1 = cur.selBegin();
732 CursorSlice i2 = cur.selEnd();
733 if (!i1.inset().asInsetMath())
736 if (i1.idx() == i2.idx())
743 void switchBetweenClasses(DocumentClassConstPtr oldone,
744 DocumentClassConstPtr newone, InsetText & in, ErrorList & errorlist)
748 LBUFERR(!in.paragraphs().empty());
749 if (oldone == newone)
752 DocumentClass const & oldtc = *oldone;
753 DocumentClass const & newtc = *newone;
756 ParIterator it = par_iterator_begin(in);
757 ParIterator end = par_iterator_end(in);
758 // for remembering which layouts we've had to add
759 set<docstring> newlayouts;
760 for (; it != end; ++it) {
761 docstring const name = it->layout().name();
763 // the pasted text will keep their own layout name. If this layout does
764 // not exist in the new document, it will behave like a standard layout.
765 bool const added_one = newtc.addLayoutIfNeeded(name);
767 newlayouts.insert(name);
769 if (added_one || newlayouts.find(name) != newlayouts.end()) {
771 docstring const s = bformat(_("Layout `%1$s' was not found."), name);
772 errorlist.push_back(ErrorItem(_("Layout Not Found"), s,
773 {it->id(), 0}, {it->id(), -1}));
776 if (in.usePlainLayout())
777 it->setLayout(newtc.plainLayout());
779 it->setLayout(newtc[name]);
782 // character styles and hidden table cells
783 InsetIterator const i_end = inset_iterator_end(in);
784 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
785 InsetCode const code = it->lyxCode();
786 if (code == FLEX_CODE) {
787 // FIXME: Should we verify all InsetCollapsible?
788 docstring const layoutName = it->layoutName();
789 docstring const & n = newone->insetLayout(layoutName).name();
790 bool const is_undefined = n.empty() ||
791 n == DocumentClass::plainInsetLayout().name();
795 // The flex inset is undefined in newtc
796 docstring const oldname = from_utf8(oldtc.name());
797 docstring const newname = from_utf8(newtc.name());
799 if (oldname == newname)
800 s = bformat(_("Flex inset %1$s is undefined after "
801 "reloading `%2$s' layout."), layoutName, oldname);
803 s = bformat(_("Flex inset %1$s is undefined because of "
804 "conversion from `%2$s' layout to `%3$s'."),
805 layoutName, oldname, newname);
806 // To warn the user that something had to be done.
807 errorlist.push_back(ErrorItem(
808 _("Undefined flex inset"), s,
809 {it.paragraph().id(), it.pos()},
810 {it.paragraph().id(), it.pos()+1}));
811 } else if (code == TABULAR_CODE) {
812 // The recursion above does not catch paragraphs in "hidden" cells,
813 // i.e., ones that are part of a multirow or multicolum. So we need
814 // to handle those separately.
815 // This is the cause of bug #9049.
816 InsetTabular * table = it->asInsetTabular();
817 table->setLayoutForHiddenCells(newtc);
823 vector<docstring> availableSelections(Buffer const * buf)
825 vector<docstring> selList;
829 CutStack::const_iterator cit = theCuts.begin();
830 CutStack::const_iterator end = theCuts.end();
831 for (; cit != end; ++cit) {
832 // we do not use cit-> here because gcc 2.9x does not
834 ParagraphList const & pars = (*cit).first;
836 ParagraphList::const_iterator pit = pars.begin();
837 ParagraphList::const_iterator pend = pars.end();
838 for (; pit != pend; ++pit) {
839 Paragraph par(*pit, 0, 46);
840 // adapt paragraph to current buffer.
841 par.setInsetBuffers(const_cast<Buffer &>(*buf));
842 textSel += par.asString(AS_STR_INSETS);
843 if (textSel.size() > 45) {
844 support::truncateWithEllipsis(textSel,45);
848 selList.push_back(textSel);
855 size_type numberOfSelections()
857 return theCuts.size();
862 void cutSelectionHelper(Cursor & cur, CutStack & cuts, bool doclear, bool realcut, bool putclip)
864 // This doesn't make sense, if there is no selection
865 if (!cur.selection())
868 // OK, we have a selection. This is always between cur.selBegin()
871 if (cur.inTexted()) {
872 Text * text = cur.text();
877 // make sure that the depth behind the selection are restored, too
878 cur.recordUndoSelection();
879 pit_type begpit = cur.selBegin().pit();
880 pit_type endpit = cur.selEnd().pit();
882 int endpos = cur.selEnd().pos();
884 BufferParams const & bp = cur.buffer()->params();
886 copySelectionHelper(*cur.buffer(),
889 cur.selBegin().pos(), endpos,
890 bp.documentClassPtr(), cuts);
891 // Stuff what we got on the clipboard.
892 // Even if there is no selection.
894 putClipboard(cuts[0].first, cuts[0].second,
895 cur.selectionAsString(true));
898 if (begpit != endpit)
899 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
901 tie(endpit, endpos) =
902 eraseSelectionHelper(bp, text->paragraphs(), begpit, endpit,
903 cur.selBegin().pos(), endpos);
905 // cutSelection can invalidate the cursor so we need to set
907 // we prefer the end for when tracking changes
911 // sometimes necessary
913 && text->paragraphs()[begpit].stripLeadingSpaces(bp.track_changes))
916 // need a valid cursor. (Lgb)
917 cur.clearSelection();
919 // After a cut operation, we must make sure that the Buffer is updated
920 // because some further operation might need updated label information for
921 // example. So we cannot just use "cur.forceBufferUpdate()" here.
923 cur.buffer()->updateBuffer();
925 // tell tabular that a recent copy happened
926 dirtyTabularStack(false);
929 if (cur.inMathed()) {
930 if (cur.selBegin().idx() != cur.selEnd().idx()) {
931 // The current selection spans more than one cell.
933 cur.recordUndoInset();
935 // Record only the current cell to avoid a jumping
947 void cutSelection(Cursor & cur, bool doclear, bool realcut)
949 cutSelectionHelper(cur, theCuts, doclear, realcut, true);
953 void cutSelectionToTemp(Cursor & cur, bool doclear, bool realcut)
955 cutSelectionHelper(cur, tempCut, doclear, realcut, false);
959 void copySelection(Cursor const & cur)
961 copySelection(cur, cur.selectionAsString(true));
965 void copyInset(Cursor const & cur, Inset * inset, docstring const & plaintext)
969 BufferParams const & bp = cur.buffer()->params();
970 par.setLayout(bp.documentClass().plainLayout());
971 Font font(inherit_font, bp.language);
972 par.insertInset(0, inset, font, Change(Change::UNCHANGED));
974 theCuts.push(make_pair(pars, bp.documentClassPtr()));
976 // stuff the selection onto the X clipboard, from an explicit copy request
977 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
983 void copySelectionToStack(CursorData const & cur, CutStack & cutstack)
985 // this doesn't make sense, if there is no selection
986 if (!cur.selection())
989 // copySelection can not yet handle the case of cross idx selection
990 if (cur.selBegin().idx() != cur.selEnd().idx())
993 if (cur.inTexted()) {
994 Text * text = cur.text();
996 // ok we have a selection. This is always between cur.selBegin()
997 // and sel_end cursor
998 copySelectionHelper(*cur.buffer(), *text,
999 cur.selBegin().pit(), cur.selEnd().pit(),
1000 cur.selBegin().pos(), cur.selEnd().pos(),
1001 cur.buffer()->params().documentClassPtr(),
1003 // Reset the dirty_tabular_stack_ flag only when something
1004 // is copied to the clipboard (not to the selectionBuffer).
1005 if (&cutstack == &theCuts)
1006 dirtyTabularStack(false);
1009 if (cur.inMathed()) {
1010 //lyxerr << "copySelection in mathed" << endl;
1013 BufferParams const & bp = cur.buffer()->params();
1014 // FIXME This should be the plain layout...right?
1015 par.setLayout(bp.documentClass().plainLayout());
1016 par.insert(0, grabSelection(cur), Font(), Change(Change::UNCHANGED));
1017 pars.push_back(par);
1018 cutstack.push(make_pair(pars, bp.documentClassPtr()));
1025 void copySelectionToStack()
1027 if (!selectionBuffer.empty())
1028 theCuts.push(selectionBuffer[0]);
1032 void copySelection(Cursor const & cur, docstring const & plaintext)
1034 // In tablemode, because copy and paste actually use special table stack
1035 // we do not attempt to get selected paragraphs under cursor. Instead, a
1036 // paragraph with the plain text version is generated so that table cells
1037 // can be pasted as pure text somewhere else.
1038 if (cur.selBegin().idx() != cur.selEnd().idx()) {
1041 BufferParams const & bp = cur.buffer()->params();
1042 par.setLayout(bp.documentClass().plainLayout());
1043 par.insert(0, plaintext, Font(), Change(Change::UNCHANGED));
1044 pars.push_back(par);
1045 theCuts.push(make_pair(pars, bp.documentClassPtr()));
1047 copySelectionToStack(cur, theCuts);
1050 // stuff the selection onto the X clipboard, from an explicit copy request
1051 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
1055 void saveSelection(Cursor const & cur)
1057 // This function is called, not when a selection is formed, but when
1058 // a selection is cleared. Therefore, multiple keyboard selection
1059 // will not repeatively trigger this function (bug 3877).
1061 && cur.selBegin() == cur.bv().cursor().selBegin()
1062 && cur.selEnd() == cur.bv().cursor().selEnd()) {
1063 LYXERR(Debug::SELECTION, "saveSelection: '" << cur.selectionAsString(true) << "'");
1064 copySelectionToStack(cur, selectionBuffer);
1071 return !selectionBuffer.empty();
1075 void clearSelection()
1077 selectionBuffer.clear();
1081 void clearCutStack()
1088 docstring selection(size_t sel_index, DocumentClassConstPtr docclass)
1090 if (sel_index >= theCuts.size())
1093 unique_ptr<Buffer> buffer(copyToTempBuffer(theCuts[sel_index].first,
1098 return buffer->paragraphs().back().asString(AS_STR_INSETS | AS_STR_NEWLINES);
1102 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
1103 DocumentClassConstPtr docclass, ErrorList & errorList,
1104 cap::BranchAction branchAction)
1106 if (cur.inTexted()) {
1107 Text * text = cur.text();
1110 PasteReturnValue prv =
1111 pasteSelectionHelper(cur, parlist, docclass, branchAction, errorList);
1112 cur.forceBufferUpdate();
1113 cur.clearSelection();
1114 text->setCursor(cur, prv.pit, prv.pos);
1117 // mathed is handled in InsetMathNest/InsetMathGrid
1118 LATTEST(!cur.inMathed());
1122 bool pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
1124 // this does not make sense, if there is nothing to paste
1125 if (!checkPastePossible(sel_index))
1129 pasteParagraphList(cur, theCuts[sel_index].first,
1130 theCuts[sel_index].second, errorList, BRANCH_ASK);
1135 bool pasteFromTemp(Cursor & cur, ErrorList & errorList)
1137 // this does not make sense, if there is nothing to paste
1138 if (tempCut.empty() || tempCut[0].first.empty())
1142 pasteParagraphList(cur, tempCut[0].first,
1143 tempCut[0].second, errorList, BRANCH_IGNORE);
1148 bool pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs,
1149 Clipboard::TextType type)
1151 // Use internal clipboard if it is the most recent one
1152 // This overrides asParagraphs and type on purpose!
1153 if (theClipboard().isInternal())
1154 return pasteFromStack(cur, errorList, 0);
1156 // First try LyX format
1157 if ((type == Clipboard::LyXTextType ||
1158 type == Clipboard::LyXOrPlainTextType ||
1159 type == Clipboard::AnyTextType) &&
1160 theClipboard().hasTextContents(Clipboard::LyXTextType)) {
1161 string lyx = theClipboard().getAsLyX();
1163 // For some strange reason gcc 3.2 and 3.3 do not accept
1164 // Buffer buffer(string(), false);
1165 Buffer buffer("", false);
1166 buffer.setUnnamed(true);
1167 if (buffer.readString(lyx)) {
1169 pasteParagraphList(cur, buffer.paragraphs(),
1170 buffer.params().documentClassPtr(), errorList);
1176 // Then try TeX and HTML
1177 Clipboard::TextType types[2] = {Clipboard::HtmlTextType, Clipboard::LaTeXTextType};
1178 string names[2] = {"html", "latexclipboard"};
1179 for (int i = 0; i < 2; ++i) {
1180 if (type != types[i] && type != Clipboard::AnyTextType)
1182 bool available = theClipboard().hasTextContents(types[i]);
1184 // If a specific type was explicitly requested, try to
1185 // interpret plain text: The user told us that the clipboard
1186 // contents is in the desired format
1187 if (!available && type == types[i]) {
1188 types[i] = Clipboard::PlainTextType;
1189 available = theClipboard().hasTextContents(types[i]);
1193 docstring text = theClipboard().getAsText(types[i]);
1194 available = !text.empty();
1196 // For some strange reason gcc 3.2 and 3.3 do not accept
1197 // Buffer buffer(string(), false);
1198 Buffer buffer("", false);
1199 buffer.setUnnamed(true);
1200 available = buffer.importString(names[i], text, errorList);
1202 available = !buffer.paragraphs().empty();
1203 if (available && !buffer.paragraphs()[0].empty()) {
1205 pasteParagraphList(cur, buffer.paragraphs(),
1206 buffer.params().documentClassPtr(), errorList);
1213 // Then try plain text
1214 docstring const text = theClipboard().getAsText(Clipboard::PlainTextType);
1219 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1221 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1222 cur.forceBufferUpdate();
1227 void pasteSimpleText(Cursor & cur, bool asParagraphs)
1230 // Use internal clipboard if it is the most recent one
1231 if (theClipboard().isInternal()) {
1232 if (!checkPastePossible(0))
1235 ParagraphList const & pars = theCuts[0].first;
1236 ParagraphList::const_iterator it = pars.begin();
1237 for (; it != pars.end(); ++it) {
1238 if (it != pars.begin())
1240 text += (*it).asString();
1242 asParagraphs = false;
1244 // Then try plain text
1245 text = theClipboard().getAsText(Clipboard::PlainTextType);
1252 cutSelection(cur, true, false);
1254 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1256 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1260 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
1261 Clipboard::GraphicsType preferedType)
1263 LASSERT(theClipboard().hasGraphicsContents(preferedType), return);
1265 // get picture from clipboard
1266 FileName filename = theClipboard().getAsGraphics(cur, preferedType);
1267 if (filename.empty())
1270 // create inset for graphic
1271 InsetGraphics * inset = new InsetGraphics(cur.buffer());
1272 InsetGraphicsParams params;
1273 params.filename = support::DocFileName(filename.absFileName(), false);
1274 inset->setParams(params);
1280 void pasteSelection(Cursor & cur, ErrorList & errorList)
1282 if (selectionBuffer.empty())
1285 pasteParagraphList(cur, selectionBuffer[0].first,
1286 selectionBuffer[0].second, errorList);
1290 void replaceSelectionWithString(Cursor & cur, docstring const & str)
1293 DocIterator selbeg = cur.selectionBegin();
1295 // Get font setting before we cut, we need a copy here, not a bare reference.
1297 selbeg.paragraph().getFontSettings(cur.buffer()->params(), selbeg.pos());
1299 // Insert the new string
1300 pos_type pos = cur.selEnd().pos();
1301 Paragraph & par = cur.selEnd().paragraph();
1302 docstring::const_iterator cit = str.begin();
1303 docstring::const_iterator end = str.end();
1304 for (; cit != end; ++cit, ++pos)
1305 par.insertChar(pos, *cit, font, cur.buffer()->params().track_changes);
1307 // Cut the selection
1308 cutSelection(cur, true, false);
1312 void replaceSelection(Cursor & cur)
1314 if (cur.selection())
1315 cutSelection(cur, true, false);
1319 void eraseSelection(Cursor & cur)
1321 //lyxerr << "cap::eraseSelection begin: " << cur << endl;
1322 CursorSlice const & i1 = cur.selBegin();
1323 CursorSlice const & i2 = cur.selEnd();
1324 if (!i1.asInsetMath()) {
1325 LYXERR0("Can't erase this selection");
1331 InsetMath * p = i1.asInsetMath();
1332 if (i1.idx() == i2.idx()) {
1333 i1.cell().erase(i1.pos(), i2.pos());
1334 // We may have deleted i1.cell(cur.pos()).
1335 // Make sure that pos is valid.
1336 if (cur.pos() > cur.lastpos())
1337 cur.pos() = cur.lastpos();
1338 } else if (p->nrows() > 0 && p->ncols() > 0) {
1339 // This is a grid, delete a nice square region
1340 Inset::row_type r1, r2;
1341 Inset::col_type c1, c2;
1342 region(i1, i2, r1, r2, c1, c2);
1343 for (Inset::row_type row = r1; row <= r2; ++row)
1344 for (Inset::col_type col = c1; col <= c2; ++col)
1345 p->cell(p->index(row, col)).clear();
1346 // We've deleted the whole cell. Only pos 0 is valid.
1349 Inset::idx_type idx1 = i1.idx();
1350 Inset::idx_type idx2 = i2.idx();
1353 for (Inset::idx_type idx = idx1 ; idx <= idx2; ++idx)
1354 p->cell(idx).clear();
1355 // We've deleted the whole cell. Only pos 0 is valid.
1359 // need a valid cursor. (Lgb)
1360 cur.clearSelection();
1361 //lyxerr << "cap::eraseSelection end: " << cur << endl;
1365 void selDel(Cursor & cur)
1367 //lyxerr << "cap::selDel" << endl;
1368 if (cur.selection())
1369 eraseSelection(cur);
1373 void selClearOrDel(Cursor & cur)
1375 //lyxerr << "cap::selClearOrDel" << endl;
1376 if (lyxrc.auto_region_delete)
1379 cur.selection(false);
1383 docstring grabSelection(CursorData const & cur)
1385 if (!cur.selection())
1389 // grab selection by glueing multiple cells together. This is not what
1390 // we want because selections spanning multiple cells will get "&" and "\\"
1393 for (DocIterator dit = cur.selectionBegin();
1394 dit != cur.selectionEnd(); dit.forwardPos())
1395 os << asString(dit.cell());
1399 CursorSlice i1 = cur.selBegin();
1400 CursorSlice i2 = cur.selEnd();
1402 if (i1.idx() == i2.idx()) {
1403 if (i1.inset().asInsetMath()) {
1404 MathData::const_iterator it = i1.cell().begin();
1405 Buffer * buf = cur.buffer();
1406 return asString(MathData(buf, it + i1.pos(), it + i2.pos()));
1408 return from_ascii("unknown selection 1");
1412 Inset::row_type r1, r2;
1413 Inset::col_type c1, c2;
1414 region(i1, i2, r1, r2, c1, c2);
1417 if (i1.inset().asInsetMath()) {
1418 for (Inset::row_type row = r1; row <= r2; ++row) {
1421 for (Inset::col_type col = c1; col <= c2; ++col) {
1424 data += asString(i1.asInsetMath()->
1425 cell(i1.asInsetMath()->index(row, col)));
1429 data = from_ascii("unknown selection 2");
1435 void dirtyTabularStack(bool b)
1437 dirty_tabular_stack_ = b;
1441 bool tabularStackDirty()
1443 return dirty_tabular_stack_;