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 // Prevent to paste uncodable characters in verbatim and ERT.
163 // The encoding is inherited from the context here.
164 docstring uncodable_content;
165 if (target_inset->getLayout().isPassThru() && cur.getEncoding()) {
166 odocstringstream res;
167 Encoding const * e = cur.getEncoding();
168 for (size_t i = 0; i != insertion.size(); ++i) {
169 pos_type end = insertion[i].size();
170 for (pos_type j = 0; j != end; ++j) {
172 if (insertion[i].isInset(j))
174 char_type const c = insertion[i].getChar(j);
175 if (!e->encodable(c)) {
176 // do not track deletion
178 insertion[i].eraseChar(j, false);
184 docstring const uncodable = res.str();
185 if (!uncodable.empty()) {
186 if (uncodable.size() == 1)
187 uncodable_content = bformat(_("The character \"%1$s\" is uncodable in this verbatim context "
188 "and thus has not been pasted."),
191 uncodable_content = bformat(_("The characters \"%1$s\" are uncodable in this verbatim context "
192 "and thus have not been pasted."),
197 // set the paragraphs to plain layout if necessary
198 DocumentClassConstPtr newDocClass = buffer.params().documentClassPtr();
199 if (cur.inset().usePlainLayout()) {
200 bool forcePlainLayout = target_inset->forcePlainLayout();
201 Layout const & plainLayout = newDocClass->plainLayout();
202 Layout const & defaultLayout = newDocClass->defaultLayout();
203 ParagraphList::iterator const end = insertion.end();
204 ParagraphList::iterator par = insertion.begin();
205 for (; par != end; ++par) {
206 Layout const & parLayout = par->layout();
207 if (forcePlainLayout || parLayout == defaultLayout)
208 par->setLayout(plainLayout);
211 // check if we need to reset from plain layout
212 Layout const & defaultLayout = newDocClass->defaultLayout();
213 Layout const & plainLayout = newDocClass->plainLayout();
214 ParagraphList::iterator const end = insertion.end();
215 ParagraphList::iterator par = insertion.begin();
216 for (; par != end; ++par) {
217 Layout const & parLayout = par->layout();
218 if (parLayout == plainLayout)
219 par->setLayout(defaultLayout);
223 InsetText in(cur.buffer());
224 // Make sure there is no class difference.
225 in.paragraphs().clear();
226 // This works without copying any paragraph data because we have
227 // a specialized swap method for ParagraphList. This is important
228 // since we store pointers to insets at some places and we don't
229 // want to invalidate them.
230 insertion.swap(in.paragraphs());
231 cap::switchBetweenClasses(oldDocClass, newDocClass, in, errorlist);
232 // Do this here since switchBetweenClasses clears the errorlist
233 if (!uncodable_content.empty())
234 errorlist.push_back(ErrorItem(_("Uncodable content"), uncodable_content));
235 insertion.swap(in.paragraphs());
237 ParagraphList::iterator tmpbuf = insertion.begin();
238 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
240 depth_type max_depth = pars[pit].getMaxDepthAfter();
242 for (; tmpbuf != insertion.end(); ++tmpbuf) {
243 // If we have a negative jump so that the depth would
244 // go below 0 depth then we have to redo the delta to
245 // this new max depth level so that subsequent
246 // paragraphs are aligned correctly to this paragraph
248 if (int(tmpbuf->params().depth()) + depth_delta < 0)
251 // Set the right depth so that we are not too deep or shallow.
252 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
253 if (tmpbuf->params().depth() > max_depth)
254 tmpbuf->params().depth(max_depth);
256 // Set max_depth for the next paragraph
257 max_depth = tmpbuf->getMaxDepthAfter();
259 // Set the inset owner of this paragraph.
260 tmpbuf->setInsetOwner(target_inset);
261 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
262 // do not track deletion of invalid insets
263 if (Inset * inset = tmpbuf->getInset(i))
264 if (!target_inset->insetAllowed(inset->lyxCode()))
265 tmpbuf->eraseChar(i--, false);
268 tmpbuf->setChange(Change(buffer.params().track_changes ?
269 Change::INSERTED : Change::UNCHANGED));
272 bool const empty = pars[pit].empty();
274 // Make the buf exactly the same layout as the cursor
276 insertion.begin()->makeSameLayout(pars[pit]);
279 // Prepare the paragraphs and insets for insertion.
280 insertion.swap(in.paragraphs());
282 InsetIterator const i_end = inset_iterator_end(in);
283 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
284 // Even though this will also be done later, it has to be done here
285 // since some inset might going to try to access
286 // the buffer() member.
287 it->setBuffer(const_cast<Buffer &>(buffer));
288 switch (it->lyxCode()) {
290 case MATH_HULL_CODE: {
291 // check for equation labels and resolve duplicates
292 InsetMathHull * ins = it->asInsetMath()->asHullInset();
293 std::vector<InsetLabel *> labels = ins->getLabels();
294 for (size_t i = 0; i != labels.size(); ++i) {
297 InsetLabel * lab = labels[i];
298 docstring const oldname = lab->getParam("name");
299 lab->updateLabel(oldname);
300 // We need to update the buffer reference cache.
302 docstring const newname = lab->getParam("name");
303 if (oldname == newname)
305 // adapt the references
306 for (InsetIterator itt = inset_iterator_begin(in);
307 itt != i_end; ++itt) {
308 if (itt->lyxCode() == REF_CODE) {
309 InsetCommand * ref = itt->asInsetCommand();
310 if (ref->getParam("reference") == oldname)
311 ref->setParam("reference", newname);
312 } else if (itt->lyxCode() == MATH_REF_CODE) {
313 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
314 // this is necessary to prevent an uninitialized
315 // buffer when the RefInset is in a MathBox.
316 // FIXME audit setBuffer calls
317 mi->setBuffer(const_cast<Buffer &>(buffer));
318 if (mi->getTarget() == oldname)
319 mi->changeTarget(newname);
327 // check for duplicates
328 InsetLabel & lab = static_cast<InsetLabel &>(*it);
329 docstring const oldname = lab.getParam("name");
330 lab.updateLabel(oldname);
331 // We need to update the buffer reference cache.
333 docstring const newname = lab.getParam("name");
334 if (oldname == newname)
336 // adapt the references
337 for (InsetIterator itt = inset_iterator_begin(in); itt != i_end; ++itt) {
338 if (itt->lyxCode() == REF_CODE) {
339 InsetCommand & ref = static_cast<InsetCommand &>(*itt);
340 if (ref.getParam("reference") == oldname)
341 ref.setParam("reference", newname);
342 } else if (itt->lyxCode() == MATH_REF_CODE) {
343 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
344 // this is necessary to prevent an uninitialized
345 // buffer when the RefInset is in a MathBox.
346 // FIXME audit setBuffer calls
347 mi->setBuffer(const_cast<Buffer &>(buffer));
348 if (mi->getTarget() == oldname)
349 mi->changeTarget(newname);
356 InsetInclude & inc = static_cast<InsetInclude &>(*it);
358 // We need to update the list of included files.
364 // check for duplicates
365 InsetBibitem & bib = static_cast<InsetBibitem &>(*it);
366 docstring const oldkey = bib.getParam("key");
367 bib.updateCommand(oldkey, false);
368 // We need to update the buffer reference cache.
370 docstring const newkey = bib.getParam("key");
371 if (oldkey == newkey)
373 // adapt the references
374 for (InsetIterator itt = inset_iterator_begin(in);
375 itt != i_end; ++itt) {
376 if (itt->lyxCode() == CITE_CODE) {
377 InsetCommand * ref = itt->asInsetCommand();
378 if (ref->getParam("key") == oldkey)
379 ref->setParam("key", newkey);
386 // check if branch is known to target buffer
388 InsetBranch & br = static_cast<InsetBranch &>(*it);
389 docstring const name = br.branch();
392 bool const is_child = (&buffer != buffer.masterBuffer());
393 BranchList branchlist = buffer.params().branchlist();
394 if ((!is_child && branchlist.find(name))
395 || (is_child && (branchlist.find(name)
396 || buffer.masterBuffer()->params().branchlist().find(name))))
398 switch(branchAction) {
399 case cap::BRANCH_ADD: {
400 // This is for a temporary buffer, so simply create the branch.
401 // Must not use lyx::dispatch(), since tmpbuffer has no view.
403 const_cast<Buffer&>(buffer).dispatch(FuncRequest(LFUN_BRANCH_ADD, name), dr);
406 case cap::BRANCH_ASK: {
407 docstring text = bformat(
408 _("The pasted branch \"%1$s\" is undefined.\n"
409 "Do you want to add it to the document's branch list?"),
411 if (frontend::Alert::prompt(_("Unknown branch"),
412 text, 0, 1, _("&Add"), _("&Don't Add")) != 0)
414 lyx::dispatch(FuncRequest(LFUN_BRANCH_ADD, name));
417 case cap::BRANCH_IGNORE:
420 // We need to update the list of branches.
429 insertion.swap(in.paragraphs());
431 // Split the paragraph for inserting the buf if necessary.
433 breakParagraphConservative(buffer.params(), pars, pit, pos);
437 pars.insert(lyx::next(pars.begin(), pit),
441 // merge the empty par with the last par of the insertion
442 mergeParagraph(buffer.params(), pars,
443 pit + insertion.size() - 1);
445 pars.insert(lyx::next(pars.begin(), pit + 1),
449 // merge the first par of the insertion with the current par
450 mergeParagraph(buffer.params(), pars, pit);
453 // Store the new cursor position.
454 pit_type last_paste = pit + insertion.size() - 1;
455 pit_type startpit = pit;
457 pos = pars[last_paste].size();
459 // FIXME Should we do it here, or should we let updateBuffer() do it?
460 // Set paragraph buffers. It's important to do this right away
461 // before something calls Inset::buffer() and causes a crash.
462 for (pit_type p = startpit; p <= pit; ++p)
463 pars[p].setBuffer(const_cast<Buffer &>(buffer));
465 // Join (conditionally) last pasted paragraph with next one, i.e.,
466 // the tail of the spliced document paragraph
467 if (!empty && last_paste + 1 != pit_type(pars.size())) {
468 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
469 mergeParagraph(buffer.params(), pars, last_paste);
470 } else if (pars[last_paste + 1].empty()) {
471 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
472 mergeParagraph(buffer.params(), pars, last_paste);
473 } else if (pars[last_paste].empty()) {
474 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
475 mergeParagraph(buffer.params(), pars, last_paste);
477 pars[last_paste + 1].stripLeadingSpaces(buffer.params().track_changes);
482 return PasteReturnValue(pit, pos, need_update);
486 PitPosPair eraseSelectionHelper(BufferParams const & params,
487 ParagraphList & pars,
488 pit_type startpit, pit_type endpit,
489 int startpos, int endpos)
491 // Start of selection is really invalid.
492 if (startpit == pit_type(pars.size()) ||
493 (startpos > pars[startpit].size()))
494 return PitPosPair(endpit, endpos);
496 // Start and end is inside same paragraph
497 if (endpit == pit_type(pars.size()) || startpit == endpit) {
498 endpos -= pars[startpit].eraseChars(startpos, endpos, params.track_changes);
499 return PitPosPair(endpit, endpos);
502 for (pit_type pit = startpit; pit != endpit + 1;) {
503 pos_type const left = (pit == startpit ? startpos : 0);
504 pos_type right = (pit == endpit ? endpos : pars[pit].size() + 1);
505 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.track_changes);
507 // Logically erase only, including the end-of-paragraph character
508 pars[pit].eraseChars(left, right, params.track_changes);
510 // Separate handling of paragraph break:
511 if (merge && pit != endpit &&
513 || pars[pit].hasSameLayout(pars[endpit])
514 || pars[endpit].size() == endpos)) {
515 if (pit + 1 == endpit)
516 endpos += pars[pit].size();
517 mergeParagraph(params, pars, pit);
523 // Ensure legal cursor pos:
526 return PitPosPair(endpit, endpos);
530 Buffer * copyToTempBuffer(ParagraphList const & paragraphs, DocumentClassConstPtr docclass)
532 // This used to need to be static to avoid a memory leak. It no longer needs
533 // to be so, but the alternative is to construct a new one of these (with a
534 // new temporary directory, etc) every time, and then to destroy it. So maybe
535 // it's worth just keeping this one around.
536 static TempFile tempfile("clipboard.internal");
537 tempfile.setAutoRemove(false);
538 // The initialization of staticbuffer is thread-safe. Using a lambda
539 // guarantees that the properties are set only once.
540 static Buffer * staticbuffer = [&](){
542 theBufferList().newInternalBuffer(tempfile.name().absFileName());
544 b->inset().setBuffer(*b);
545 //initialize staticbuffer with b
548 // Use a clone for the complicated stuff so that we do not need to clean
549 // up in order to avoid a crash.
550 Buffer * buffer = staticbuffer->cloneBufferOnly();
551 LASSERT(buffer, return 0);
553 // This needs doing every time.
554 // Since setDocumentClass() causes deletion of the old document class
555 // we need to reset all layout pointers in paragraphs (otherwise they
556 // would be dangling).
557 ParIterator const end = buffer->par_iterator_end();
558 for (ParIterator it = buffer->par_iterator_begin(); it != end; ++it) {
559 docstring const name = it->layout().name();
560 if (docclass->hasLayout(name))
561 it->setLayout((*docclass)[name]);
563 it->setPlainOrDefaultLayout(*docclass);
565 buffer->params().setDocumentClass(docclass);
567 // we will use pasteSelectionHelper to copy the paragraphs into the
568 // temporary Buffer, since it does a lot of things to fix them up.
569 DocIterator dit = doc_iterator_begin(buffer, &buffer->inset());
571 pasteSelectionHelper(dit, paragraphs, docclass, cap::BRANCH_ADD, el);
577 void putClipboard(ParagraphList const & paragraphs,
578 DocumentClassConstPtr docclass, docstring const & plaintext)
580 Buffer * buffer = copyToTempBuffer(paragraphs, docclass);
581 if (!buffer) // already asserted in copyToTempBuffer()
584 // We don't want to produce images that are not used. Therefore,
585 // output formulas as MathML. Even if this is not understood by all
586 // applications, the number that can parse it should go up in the future.
587 buffer->params().html_math_output = BufferParams::MathML;
589 // Make sure MarkAsExporting is deleted before buffer is
591 // The Buffer is being used to export. This is necessary so that the
592 // updateMacros call will record the needed information.
593 MarkAsExporting mex(buffer);
595 buffer->updateBuffer(Buffer::UpdateMaster, OutputUpdate);
596 buffer->updateMacros();
597 buffer->updateMacroInstances(OutputUpdate);
602 if (buffer->write(oslyx))
606 odocstringstream oshtml;
607 OutputParams runparams(encodings.fromLyXName("utf8"));
608 // We do not need to produce images, etc.
609 runparams.dryrun = true;
610 // We are not interested in errors (bug 8866)
611 runparams.silent = true;
612 buffer->writeLyXHTMLSource(oshtml, runparams, Buffer::FullSource);
614 theClipboard().put(lyx, oshtml.str(), plaintext);
622 /// return true if the whole ParagraphList is deleted
623 static bool isFullyDeleted(ParagraphList const & pars)
625 pit_type const pars_size = static_cast<pit_type>(pars.size());
627 // check all paragraphs
628 for (pit_type pit = 0; pit < pars_size; ++pit) {
629 if (!pars[pit].empty()) // prevent assertion failure
630 if (!pars[pit].isDeleted(0, pars[pit].size()))
637 void copySelectionHelper(Buffer const & buf, Text const & text,
638 pit_type startpit, pit_type endpit,
639 int start, int end, DocumentClassConstPtr dc, CutStack & cutstack)
641 ParagraphList const & pars = text.paragraphs();
643 // In most of these cases, we can try to recover.
644 LASSERT(0 <= start, start = 0);
645 LASSERT(start <= pars[startpit].size(), start = pars[startpit].size());
646 LASSERT(0 <= end, end = 0);
647 LASSERT(end <= pars[endpit].size(), end = pars[endpit].size());
648 LASSERT(startpit != endpit || start <= end, return);
650 // Clone the paragraphs within the selection.
651 ParagraphList copy_pars(lyx::next(pars.begin(), startpit),
652 lyx::next(pars.begin(), endpit + 1));
654 // Remove the end of the last paragraph; afterwards, remove the
655 // beginning of the first paragraph. Keep this order - there may only
656 // be one paragraph! Do not track deletions here; this is an internal
657 // action not visible to the user
659 Paragraph & back = copy_pars.back();
660 back.eraseChars(end, back.size(), false);
661 Paragraph & front = copy_pars.front();
662 front.eraseChars(0, start, false);
664 ParagraphList::iterator it = copy_pars.begin();
665 ParagraphList::iterator it_end = copy_pars.end();
667 for (; it != it_end; ++it) {
668 // Since we have a copy of the paragraphs, the insets
669 // do not have a proper buffer reference. It makes
670 // sense to add them temporarily, because the
671 // operations below depend on that (acceptChanges included).
672 it->setBuffer(const_cast<Buffer &>(buf));
673 // PassThru paragraphs have the Language
674 // latex_language. This is invalid for others, so we
675 // need to change it to the buffer language.
676 if (it->isPassThru())
677 it->changeLanguage(buf.params(),
678 latex_language, buf.language());
681 // do not copy text (also nested in insets) which is marked as
682 // deleted, unless the whole selection was deleted
683 if (!isFullyDeleted(copy_pars))
684 acceptChanges(copy_pars, buf.params());
686 rejectChanges(copy_pars, buf.params());
689 // do some final cleanup now, to make sure that the paragraphs
690 // are not linked to something else.
691 it = copy_pars.begin();
692 for (; it != it_end; ++it) {
694 it->setInsetOwner(0);
697 cutstack.push(make_pair(copy_pars, dc));
705 void region(CursorSlice const & i1, CursorSlice const & i2,
706 Inset::row_type & r1, Inset::row_type & r2,
707 Inset::col_type & c1, Inset::col_type & c2)
709 Inset & p = i1.inset();
710 c1 = p.col(i1.idx());
711 c2 = p.col(i2.idx());
714 r1 = p.row(i1.idx());
715 r2 = p.row(i2.idx());
721 docstring grabAndEraseSelection(Cursor & cur)
723 if (!cur.selection())
725 docstring res = grabSelection(cur);
731 bool reduceSelectionToOneCell(Cursor & cur)
733 if (!cur.selection() || !cur.inMathed())
736 CursorSlice i1 = cur.selBegin();
737 CursorSlice i2 = cur.selEnd();
738 if (!i1.inset().asInsetMath())
741 // the easy case: do nothing if only one cell is selected
742 if (i1.idx() == i2.idx())
747 cur.top().pos() = cur.top().lastpos();
753 bool multipleCellsSelected(Cursor const & cur)
755 if (!cur.selection() || !cur.inMathed())
758 CursorSlice i1 = cur.selBegin();
759 CursorSlice i2 = cur.selEnd();
760 if (!i1.inset().asInsetMath())
763 if (i1.idx() == i2.idx())
770 void switchBetweenClasses(DocumentClassConstPtr oldone,
771 DocumentClassConstPtr newone, InsetText & in, ErrorList & errorlist)
775 LBUFERR(!in.paragraphs().empty());
776 if (oldone == newone)
779 DocumentClass const & oldtc = *oldone;
780 DocumentClass const & newtc = *newone;
783 ParIterator it = par_iterator_begin(in);
784 ParIterator end = par_iterator_end(in);
785 // for remembering which layouts we've had to add
786 set<docstring> newlayouts;
787 for (; it != end; ++it) {
788 docstring const name = it->layout().name();
790 // the pasted text will keep their own layout name. If this layout does
791 // not exist in the new document, it will behave like a standard layout.
792 bool const added_one = newtc.addLayoutIfNeeded(name);
794 newlayouts.insert(name);
796 if (added_one || newlayouts.find(name) != newlayouts.end()) {
798 docstring const s = bformat(_("Layout `%1$s' was not found."), name);
799 errorlist.push_back(ErrorItem(_("Layout Not Found"), s,
800 {it->id(), 0}, {it->id(), -1}));
803 if (in.usePlainLayout())
804 it->setLayout(newtc.plainLayout());
806 it->setLayout(newtc[name]);
809 // character styles and hidden table cells
810 InsetIterator const i_end = inset_iterator_end(in);
811 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
812 InsetCode const code = it->lyxCode();
813 if (code == FLEX_CODE) {
814 // FIXME: Should we verify all InsetCollapsible?
815 docstring const layoutName = it->layoutName();
816 docstring const & n = newone->insetLayout(layoutName).name();
817 bool const is_undefined = n.empty() ||
818 n == DocumentClass::plainInsetLayout().name();
822 // The flex inset is undefined in newtc
823 docstring const oldname = from_utf8(oldtc.name());
824 docstring const newname = from_utf8(newtc.name());
826 if (oldname == newname)
827 s = bformat(_("Flex inset %1$s is undefined after "
828 "reloading `%2$s' layout."), layoutName, oldname);
830 s = bformat(_("Flex inset %1$s is undefined because of "
831 "conversion from `%2$s' layout to `%3$s'."),
832 layoutName, oldname, newname);
833 // To warn the user that something had to be done.
834 errorlist.push_back(ErrorItem(
835 _("Undefined flex inset"), s,
836 {it.paragraph().id(), it.pos()},
837 {it.paragraph().id(), it.pos()+1}));
838 } else if (code == TABULAR_CODE) {
839 // The recursion above does not catch paragraphs in "hidden" cells,
840 // i.e., ones that are part of a multirow or multicolum. So we need
841 // to handle those separately.
842 // This is the cause of bug #9049.
843 InsetTabular * table = it->asInsetTabular();
844 table->setLayoutForHiddenCells(newtc);
850 vector<docstring> availableSelections(Buffer const * buf)
852 vector<docstring> selList;
856 CutStack::const_iterator cit = theCuts.begin();
857 CutStack::const_iterator end = theCuts.end();
858 for (; cit != end; ++cit) {
859 // we do not use cit-> here because gcc 2.9x does not
861 ParagraphList const & pars = (*cit).first;
863 ParagraphList::const_iterator pit = pars.begin();
864 ParagraphList::const_iterator pend = pars.end();
865 for (; pit != pend; ++pit) {
866 Paragraph par(*pit, 0, 46);
867 // adapt paragraph to current buffer.
868 par.setBuffer(const_cast<Buffer &>(*buf));
869 textSel += par.asString(AS_STR_INSETS);
870 if (textSel.size() > 45) {
871 support::truncateWithEllipsis(textSel,45);
875 selList.push_back(textSel);
882 size_type numberOfSelections()
884 return theCuts.size();
889 void cutSelectionHelper(Cursor & cur, CutStack & cuts, bool doclear, bool realcut, bool putclip)
891 // This doesn't make sense, if there is no selection
892 if (!cur.selection())
895 // OK, we have a selection. This is always between cur.selBegin()
898 if (cur.inTexted()) {
899 Text * text = cur.text();
904 // make sure that the depth behind the selection are restored, too
905 cur.recordUndoSelection();
906 pit_type begpit = cur.selBegin().pit();
907 pit_type endpit = cur.selEnd().pit();
909 int endpos = cur.selEnd().pos();
911 BufferParams const & bp = cur.buffer()->params();
913 copySelectionHelper(*cur.buffer(),
916 cur.selBegin().pos(), endpos,
917 bp.documentClassPtr(), cuts);
918 // Stuff what we got on the clipboard.
919 // Even if there is no selection.
921 putClipboard(cuts[0].first, cuts[0].second,
922 cur.selectionAsString(true));
925 if (begpit != endpit)
926 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
928 tie(endpit, endpos) =
929 eraseSelectionHelper(bp, text->paragraphs(), begpit, endpit,
930 cur.selBegin().pos(), endpos);
932 // cutSelection can invalidate the cursor so we need to set
934 // we prefer the end for when tracking changes
938 // sometimes necessary
940 && text->paragraphs()[begpit].stripLeadingSpaces(bp.track_changes))
943 // need a valid cursor. (Lgb)
944 cur.clearSelection();
946 // After a cut operation, we must make sure that the Buffer is updated
947 // because some further operation might need updated label information for
948 // example. So we cannot just use "cur.forceBufferUpdate()" here.
950 cur.buffer()->updateBuffer();
952 // tell tabular that a recent copy happened
953 dirtyTabularStack(false);
956 if (cur.inMathed()) {
957 if (cur.selBegin().idx() != cur.selEnd().idx()) {
958 // The current selection spans more than one cell.
960 cur.recordUndoInset();
962 // Record only the current cell to avoid a jumping
974 void cutSelection(Cursor & cur, bool doclear, bool realcut)
976 cutSelectionHelper(cur, theCuts, doclear, realcut, true);
980 void cutSelectionToTemp(Cursor & cur, bool doclear, bool realcut)
982 cutSelectionHelper(cur, tempCut, doclear, realcut, false);
986 void copySelection(Cursor const & cur)
988 copySelection(cur, cur.selectionAsString(true));
992 void copyInset(Cursor const & cur, Inset * inset, docstring const & plaintext)
996 BufferParams const & bp = cur.buffer()->params();
997 par.setLayout(bp.documentClass().plainLayout());
998 Font font(inherit_font, bp.language);
999 par.insertInset(0, inset, font, Change(Change::UNCHANGED));
1000 pars.push_back(par);
1001 theCuts.push(make_pair(pars, bp.documentClassPtr()));
1003 // stuff the selection onto the X clipboard, from an explicit copy request
1004 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
1010 void copySelectionToStack(Cursor const & cur, CutStack & cutstack)
1012 // this doesn't make sense, if there is no selection
1013 if (!cur.selection())
1016 // copySelection can not yet handle the case of cross idx selection
1017 if (cur.selBegin().idx() != cur.selEnd().idx())
1020 if (cur.inTexted()) {
1021 Text * text = cur.text();
1023 // ok we have a selection. This is always between cur.selBegin()
1024 // and sel_end cursor
1025 copySelectionHelper(*cur.buffer(), *text,
1026 cur.selBegin().pit(), cur.selEnd().pit(),
1027 cur.selBegin().pos(), cur.selEnd().pos(),
1028 cur.buffer()->params().documentClassPtr(),
1030 // Reset the dirty_tabular_stack_ flag only when something
1031 // is copied to the clipboard (not to the selectionBuffer).
1032 if (&cutstack == &theCuts)
1033 dirtyTabularStack(false);
1036 if (cur.inMathed()) {
1037 //lyxerr << "copySelection in mathed" << endl;
1040 BufferParams const & bp = cur.buffer()->params();
1041 // FIXME This should be the plain layout...right?
1042 par.setLayout(bp.documentClass().plainLayout());
1043 // For pasting into text, we set the language to the paragraph language
1044 // (rather than the default_language which is always English; see #2596)
1045 par.insert(0, grabSelection(cur), Font(sane_font, par.getParLanguage(bp)),
1046 Change(Change::UNCHANGED));
1047 pars.push_back(par);
1048 cutstack.push(make_pair(pars, bp.documentClassPtr()));
1055 void copySelectionToStack()
1057 if (!selectionBuffer.empty())
1058 theCuts.push(selectionBuffer[0]);
1062 void copySelection(Cursor const & cur, docstring const & plaintext)
1064 // In tablemode, because copy and paste actually use special table stack
1065 // we do not attempt to get selected paragraphs under cursor. Instead, a
1066 // paragraph with the plain text version is generated so that table cells
1067 // can be pasted as pure text somewhere else.
1068 if (cur.selBegin().idx() != cur.selEnd().idx()) {
1071 BufferParams const & bp = cur.buffer()->params();
1072 par.setLayout(bp.documentClass().plainLayout());
1073 par.insert(0, plaintext, Font(), Change(Change::UNCHANGED));
1074 pars.push_back(par);
1075 theCuts.push(make_pair(pars, bp.documentClassPtr()));
1077 copySelectionToStack(cur, theCuts);
1080 // stuff the selection onto the X clipboard, from an explicit copy request
1081 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
1085 void saveSelection(Cursor const & cur)
1087 // This function is called, not when a selection is formed, but when
1088 // a selection is cleared. Therefore, multiple keyboard selection
1089 // will not repeatively trigger this function (bug 3877).
1091 && cur.selBegin() == cur.bv().cursor().selBegin()
1092 && cur.selEnd() == cur.bv().cursor().selEnd()) {
1093 LYXERR(Debug::SELECTION, "saveSelection: '" << cur.selectionAsString(true) << "'");
1094 copySelectionToStack(cur, selectionBuffer);
1101 return !selectionBuffer.empty();
1105 void clearSelection()
1107 selectionBuffer.clear();
1111 void clearCutStack()
1118 docstring selection(size_t sel_index, DocumentClassConstPtr docclass)
1120 if (sel_index >= theCuts.size())
1123 unique_ptr<Buffer> buffer(copyToTempBuffer(theCuts[sel_index].first,
1128 return buffer->paragraphs().back().asString(AS_STR_INSETS | AS_STR_NEWLINES);
1132 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
1133 DocumentClassConstPtr docclass, ErrorList & errorList,
1134 cap::BranchAction branchAction)
1136 if (cur.inTexted()) {
1137 Text * text = cur.text();
1140 PasteReturnValue prv =
1141 pasteSelectionHelper(cur, parlist, docclass, branchAction, errorList);
1142 cur.forceBufferUpdate();
1143 cur.clearSelection();
1144 text->setCursor(cur, prv.pit, prv.pos);
1147 // mathed is handled in InsetMathNest/InsetMathGrid
1148 LATTEST(!cur.inMathed());
1152 bool pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
1154 // this does not make sense, if there is nothing to paste
1155 if (!checkPastePossible(sel_index))
1159 pasteParagraphList(cur, theCuts[sel_index].first,
1160 theCuts[sel_index].second, errorList, BRANCH_ASK);
1165 bool pasteFromTemp(Cursor & cur, ErrorList & errorList)
1167 // this does not make sense, if there is nothing to paste
1168 if (tempCut.empty() || tempCut[0].first.empty())
1172 pasteParagraphList(cur, tempCut[0].first,
1173 tempCut[0].second, errorList, BRANCH_IGNORE);
1178 bool pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs,
1179 Clipboard::TextType type)
1181 // Use internal clipboard if it is the most recent one
1182 // This overrides asParagraphs and type on purpose!
1183 if (theClipboard().isInternal())
1184 return pasteFromStack(cur, errorList, 0);
1186 // First try LyX format
1187 if ((type == Clipboard::LyXTextType ||
1188 type == Clipboard::LyXOrPlainTextType ||
1189 type == Clipboard::AnyTextType) &&
1190 theClipboard().hasTextContents(Clipboard::LyXTextType)) {
1191 string lyx = theClipboard().getAsLyX();
1193 // For some strange reason gcc 3.2 and 3.3 do not accept
1194 // Buffer buffer(string(), false);
1195 Buffer buffer("", false);
1196 buffer.setUnnamed(true);
1197 if (buffer.readString(lyx)) {
1199 pasteParagraphList(cur, buffer.paragraphs(),
1200 buffer.params().documentClassPtr(), errorList);
1206 // Then try TeX and HTML
1207 Clipboard::TextType types[2] = {Clipboard::HtmlTextType, Clipboard::LaTeXTextType};
1208 string names[2] = {"html", "latexclipboard"};
1209 for (int i = 0; i < 2; ++i) {
1210 if (type != types[i] && type != Clipboard::AnyTextType)
1212 bool available = theClipboard().hasTextContents(types[i]);
1214 // If a specific type was explicitly requested, try to
1215 // interpret plain text: The user told us that the clipboard
1216 // contents is in the desired format
1217 if (!available && type == types[i]) {
1218 types[i] = Clipboard::PlainTextType;
1219 available = theClipboard().hasTextContents(types[i]);
1223 docstring text = theClipboard().getAsText(types[i]);
1224 available = !text.empty();
1226 // For some strange reason gcc 3.2 and 3.3 do not accept
1227 // Buffer buffer(string(), false);
1228 Buffer buffer("", false);
1229 buffer.setUnnamed(true);
1230 available = buffer.importString(names[i], text, errorList);
1231 // TeX2lyx (also used in the HTML chain) assumes English as document language
1232 // if no language is explicitly set (as is the case here).
1233 // We thus reset the temp buffer's language to the context language
1234 buffer.changeLanguage(buffer.language(), cur.getFont().language());
1236 available = !buffer.paragraphs().empty();
1237 if (available && !buffer.paragraphs()[0].empty()) {
1239 pasteParagraphList(cur, buffer.paragraphs(),
1240 buffer.params().documentClassPtr(), errorList);
1247 // Then try plain text
1248 docstring const text = theClipboard().getAsText(Clipboard::PlainTextType);
1253 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1255 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1256 cur.forceBufferUpdate();
1261 void pasteSimpleText(Cursor & cur, bool asParagraphs)
1264 // Use internal clipboard if it is the most recent one
1265 if (theClipboard().isInternal()) {
1266 if (!checkPastePossible(0))
1269 ParagraphList const & pars = theCuts[0].first;
1270 ParagraphList::const_iterator it = pars.begin();
1271 for (; it != pars.end(); ++it) {
1272 if (it != pars.begin())
1274 text += (*it).asString();
1276 asParagraphs = false;
1278 // Then try plain text
1279 text = theClipboard().getAsText(Clipboard::PlainTextType);
1286 cutSelection(cur, true, false);
1288 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1290 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1294 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
1295 Clipboard::GraphicsType preferedType)
1297 LASSERT(theClipboard().hasGraphicsContents(preferedType), return);
1299 // get picture from clipboard
1300 FileName filename = theClipboard().getAsGraphics(cur, preferedType);
1301 if (filename.empty())
1304 // create inset for graphic
1305 InsetGraphics * inset = new InsetGraphics(cur.buffer());
1306 InsetGraphicsParams params;
1307 params.filename = support::DocFileName(filename.absFileName(), false);
1308 inset->setParams(params);
1314 void pasteSelection(Cursor & cur, ErrorList & errorList)
1316 if (selectionBuffer.empty())
1319 pasteParagraphList(cur, selectionBuffer[0].first,
1320 selectionBuffer[0].second, errorList);
1324 void replaceSelectionWithString(Cursor & cur, docstring const & str)
1327 DocIterator selbeg = cur.selectionBegin();
1329 // Get font setting before we cut, we need a copy here, not a bare reference.
1331 selbeg.paragraph().getFontSettings(cur.buffer()->params(), selbeg.pos());
1333 // Insert the new string
1334 pos_type pos = cur.selEnd().pos();
1335 Paragraph & par = cur.selEnd().paragraph();
1336 docstring::const_iterator cit = str.begin();
1337 docstring::const_iterator end = str.end();
1338 for (; cit != end; ++cit, ++pos)
1339 par.insertChar(pos, *cit, font, cur.buffer()->params().track_changes);
1341 // Cut the selection
1342 cutSelection(cur, true, false);
1346 void replaceSelection(Cursor & cur)
1348 if (cur.selection())
1349 cutSelection(cur, true, false);
1353 void eraseSelection(Cursor & cur)
1355 //lyxerr << "cap::eraseSelection begin: " << cur << endl;
1356 CursorSlice const & i1 = cur.selBegin();
1357 CursorSlice const & i2 = cur.selEnd();
1358 if (!i1.asInsetMath()) {
1359 LYXERR0("Can't erase this selection");
1365 InsetMath * p = i1.asInsetMath();
1366 if (i1.idx() == i2.idx()) {
1367 i1.cell().erase(i1.pos(), i2.pos());
1368 // We may have deleted i1.cell(cur.pos()).
1369 // Make sure that pos is valid.
1370 if (cur.pos() > cur.lastpos())
1371 cur.pos() = cur.lastpos();
1372 } else if (p->nrows() > 0 && p->ncols() > 0) {
1373 // This is a grid, delete a nice square region
1374 Inset::row_type r1, r2;
1375 Inset::col_type c1, c2;
1376 region(i1, i2, r1, r2, c1, c2);
1377 for (Inset::row_type row = r1; row <= r2; ++row)
1378 for (Inset::col_type col = c1; col <= c2; ++col)
1379 p->cell(p->index(row, col)).clear();
1380 // We've deleted the whole cell. Only pos 0 is valid.
1383 Inset::idx_type idx1 = i1.idx();
1384 Inset::idx_type idx2 = i2.idx();
1387 for (Inset::idx_type idx = idx1 ; idx <= idx2; ++idx)
1388 p->cell(idx).clear();
1389 // We've deleted the whole cell. Only pos 0 is valid.
1393 // need a valid cursor. (Lgb)
1394 cur.clearSelection();
1395 //lyxerr << "cap::eraseSelection end: " << cur << endl;
1399 void selDel(Cursor & cur)
1401 //lyxerr << "cap::selDel" << endl;
1402 if (cur.selection())
1403 eraseSelection(cur);
1407 void selClearOrDel(Cursor & cur)
1409 //lyxerr << "cap::selClearOrDel" << endl;
1410 if (lyxrc.auto_region_delete)
1413 cur.selection(false);
1417 docstring grabSelection(Cursor const & cur)
1419 if (!cur.selection())
1423 // grab selection by glueing multiple cells together. This is not what
1424 // we want because selections spanning multiple cells will get "&" and "\\"
1427 for (DocIterator dit = cur.selectionBegin();
1428 dit != cur.selectionEnd(); dit.forwardPos())
1429 os << asString(dit.cell());
1433 CursorSlice i1 = cur.selBegin();
1434 CursorSlice i2 = cur.selEnd();
1436 if (i1.idx() == i2.idx()) {
1437 if (i1.inset().asInsetMath()) {
1438 MathData::const_iterator it = i1.cell().begin();
1439 Buffer * buf = cur.buffer();
1440 return asString(MathData(buf, it + i1.pos(), it + i2.pos()));
1442 return from_ascii("unknown selection 1");
1446 Inset::row_type r1, r2;
1447 Inset::col_type c1, c2;
1448 region(i1, i2, r1, r2, c1, c2);
1451 if (i1.inset().asInsetMath()) {
1452 for (Inset::row_type row = r1; row <= r2; ++row) {
1455 for (Inset::col_type col = c1; col <= c2; ++col) {
1458 data += asString(i1.asInsetMath()->
1459 cell(i1.asInsetMath()->index(row, col)));
1463 data = from_ascii("unknown selection 2");
1469 void dirtyTabularStack(bool b)
1471 dirty_tabular_stack_ = b;
1475 bool tabularStackDirty()
1477 return dirty_tabular_stack_;