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 // Prevent to paste uncodable characters in verbatim and ERT.
164 // The encoding is inherited from the context here.
165 docstring uncodable_content;
166 if (target_inset->getLayout().isPassThru() && cur.getEncoding()) {
167 odocstringstream res;
168 Encoding const * e = cur.getEncoding();
169 for (size_t i = 0; i != insertion.size(); ++i) {
170 pos_type end = insertion[i].size();
171 for (pos_type j = 0; j != end; ++j) {
172 char_type const c = insertion[i].getChar(j);
173 if (!e->encodable(c)) {
174 // do not track deletion
176 insertion[i].eraseChar(j, false);
182 docstring const uncodable = res.str();
183 if (!uncodable.empty()) {
184 if (uncodable.size() == 1)
185 uncodable_content = bformat(_("The character \"%1$s\" is uncodable in this verbatim context "
186 "and thus has not been pasted."),
189 uncodable_content = bformat(_("The characters \"%1$s\" are uncodable in this verbatim context "
190 "and thus have not been pasted."),
195 // set the paragraphs to plain layout if necessary
196 DocumentClassConstPtr newDocClass = buffer.params().documentClassPtr();
197 if (cur.inset().usePlainLayout()) {
198 bool forcePlainLayout = target_inset->forcePlainLayout();
199 Layout const & plainLayout = newDocClass->plainLayout();
200 Layout const & defaultLayout = newDocClass->defaultLayout();
201 ParagraphList::iterator const end = insertion.end();
202 ParagraphList::iterator par = insertion.begin();
203 for (; par != end; ++par) {
204 Layout const & parLayout = par->layout();
205 if (forcePlainLayout || parLayout == defaultLayout)
206 par->setLayout(plainLayout);
209 // check if we need to reset from plain layout
210 Layout const & defaultLayout = newDocClass->defaultLayout();
211 Layout const & plainLayout = newDocClass->plainLayout();
212 ParagraphList::iterator const end = insertion.end();
213 ParagraphList::iterator par = insertion.begin();
214 for (; par != end; ++par) {
215 Layout const & parLayout = par->layout();
216 if (parLayout == plainLayout)
217 par->setLayout(defaultLayout);
221 InsetText in(cur.buffer());
222 // Make sure there is no class difference.
223 in.paragraphs().clear();
224 // This works without copying any paragraph data because we have
225 // a specialized swap method for ParagraphList. This is important
226 // since we store pointers to insets at some places and we don't
227 // want to invalidate them.
228 insertion.swap(in.paragraphs());
229 cap::switchBetweenClasses(oldDocClass, newDocClass, in, errorlist);
230 // Do this here since switchBetweenClasses clears the errorlist
231 if (!uncodable_content.empty())
232 errorlist.push_back(ErrorItem(_("Uncodable content"), uncodable_content));
233 insertion.swap(in.paragraphs());
235 ParagraphList::iterator tmpbuf = insertion.begin();
236 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
238 depth_type max_depth = pars[pit].getMaxDepthAfter();
240 for (; tmpbuf != insertion.end(); ++tmpbuf) {
241 // If we have a negative jump so that the depth would
242 // go below 0 depth then we have to redo the delta to
243 // this new max depth level so that subsequent
244 // paragraphs are aligned correctly to this paragraph
246 if (int(tmpbuf->params().depth()) + depth_delta < 0)
249 // Set the right depth so that we are not too deep or shallow.
250 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
251 if (tmpbuf->params().depth() > max_depth)
252 tmpbuf->params().depth(max_depth);
254 // Set max_depth for the next paragraph
255 max_depth = tmpbuf->getMaxDepthAfter();
257 // Set the inset owner of this paragraph.
258 tmpbuf->setInsetOwner(target_inset);
259 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
260 // do not track deletion of invalid insets
261 if (Inset * inset = tmpbuf->getInset(i))
262 if (!target_inset->insetAllowed(inset->lyxCode()))
263 tmpbuf->eraseChar(i--, false);
266 tmpbuf->setChange(Change(buffer.params().track_changes ?
267 Change::INSERTED : Change::UNCHANGED));
270 bool const empty = pars[pit].empty();
272 // Make the buf exactly the same layout as the cursor
274 insertion.begin()->makeSameLayout(pars[pit]);
277 // Prepare the paragraphs and insets for insertion.
278 insertion.swap(in.paragraphs());
280 InsetIterator const i_end = inset_iterator_end(in);
281 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
282 // Even though this will also be done later, it has to be done here
283 // since some inset might going to try to access
284 // the buffer() member.
285 it->setBuffer(const_cast<Buffer &>(buffer));
286 switch (it->lyxCode()) {
288 case MATH_HULL_CODE: {
289 // check for equation labels and resolve duplicates
290 InsetMathHull * ins = it->asInsetMath()->asHullInset();
291 std::vector<InsetLabel *> labels = ins->getLabels();
292 for (size_t i = 0; i != labels.size(); ++i) {
295 InsetLabel * lab = labels[i];
296 docstring const oldname = lab->getParam("name");
297 lab->updateLabel(oldname);
298 // We need to update the buffer reference cache.
300 docstring const newname = lab->getParam("name");
301 if (oldname == newname)
303 // adapt the references
304 for (InsetIterator itt = inset_iterator_begin(in);
305 itt != i_end; ++itt) {
306 if (itt->lyxCode() == REF_CODE) {
307 InsetCommand * ref = itt->asInsetCommand();
308 if (ref->getParam("reference") == oldname)
309 ref->setParam("reference", newname);
310 } else if (itt->lyxCode() == MATH_REF_CODE) {
311 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
312 // this is necessary to prevent an uninitialized
313 // buffer when the RefInset is in a MathBox.
314 // FIXME audit setBuffer calls
315 mi->setBuffer(const_cast<Buffer &>(buffer));
316 if (mi->getTarget() == oldname)
317 mi->changeTarget(newname);
325 // check for duplicates
326 InsetLabel & lab = static_cast<InsetLabel &>(*it);
327 docstring const oldname = lab.getParam("name");
328 lab.updateLabel(oldname);
329 // We need to update the buffer reference cache.
331 docstring const newname = lab.getParam("name");
332 if (oldname == newname)
334 // adapt the references
335 for (InsetIterator itt = inset_iterator_begin(in); itt != i_end; ++itt) {
336 if (itt->lyxCode() == REF_CODE) {
337 InsetCommand & ref = static_cast<InsetCommand &>(*itt);
338 if (ref.getParam("reference") == oldname)
339 ref.setParam("reference", newname);
340 } else if (itt->lyxCode() == MATH_REF_CODE) {
341 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
342 // this is necessary to prevent an uninitialized
343 // buffer when the RefInset is in a MathBox.
344 // FIXME audit setBuffer calls
345 mi->setBuffer(const_cast<Buffer &>(buffer));
346 if (mi->getTarget() == oldname)
347 mi->changeTarget(newname);
354 InsetInclude & inc = static_cast<InsetInclude &>(*it);
356 // We need to update the list of included files.
362 InsetCitation & cit = static_cast<InsetCitation &>(*it);
363 // This actually only needs to be done if the cite engine
364 // differs, but we do it in general.
366 // We need to update the list of citations.
372 // check for duplicates
373 InsetBibitem & bib = static_cast<InsetBibitem &>(*it);
374 docstring const oldkey = bib.getParam("key");
375 bib.updateCommand(oldkey, false);
376 // We need to update the buffer reference cache.
378 docstring const newkey = bib.getParam("key");
379 if (oldkey == newkey)
381 // adapt the references
382 for (InsetIterator itt = inset_iterator_begin(in);
383 itt != i_end; ++itt) {
384 if (itt->lyxCode() == CITE_CODE) {
385 InsetCommand * ref = itt->asInsetCommand();
386 if (ref->getParam("key") == oldkey)
387 ref->setParam("key", newkey);
394 // check if branch is known to target buffer
396 InsetBranch & br = static_cast<InsetBranch &>(*it);
397 docstring const name = br.branch();
400 bool const is_child = (&buffer != buffer.masterBuffer());
401 BranchList branchlist = buffer.params().branchlist();
402 if ((!is_child && branchlist.find(name))
403 || (is_child && (branchlist.find(name)
404 || buffer.masterBuffer()->params().branchlist().find(name))))
406 switch(branchAction) {
407 case cap::BRANCH_ADD: {
408 // This is for a temporary buffer, so simply create the branch.
409 // Must not use lyx::dispatch(), since tmpbuffer has no view.
411 const_cast<Buffer&>(buffer).dispatch(FuncRequest(LFUN_BRANCH_ADD, name), dr);
414 case cap::BRANCH_ASK: {
415 docstring text = bformat(
416 _("The pasted branch \"%1$s\" is undefined.\n"
417 "Do you want to add it to the document's branch list?"),
419 if (frontend::Alert::prompt(_("Unknown branch"),
420 text, 0, 1, _("&Add"), _("&Don't Add")) != 0)
422 lyx::dispatch(FuncRequest(LFUN_BRANCH_ADD, name));
425 case cap::BRANCH_IGNORE:
428 // We need to update the list of branches.
437 insertion.swap(in.paragraphs());
439 // Split the paragraph for inserting the buf if necessary.
441 breakParagraphConservative(buffer.params(), pars, pit, pos);
445 pars.insert(lyx::next(pars.begin(), pit),
449 // merge the empty par with the last par of the insertion
450 mergeParagraph(buffer.params(), pars,
451 pit + insertion.size() - 1);
453 pars.insert(lyx::next(pars.begin(), pit + 1),
457 // merge the first par of the insertion with the current par
458 mergeParagraph(buffer.params(), pars, pit);
461 // Store the new cursor position.
462 pit_type last_paste = pit + insertion.size() - 1;
463 pit_type startpit = pit;
465 pos = pars[last_paste].size();
467 // FIXME Should we do it here, or should we let updateBuffer() do it?
468 // Set paragraph buffers. It's important to do this right away
469 // before something calls Inset::buffer() and causes a crash.
470 for (pit_type p = startpit; p <= pit; ++p)
471 pars[p].setInsetBuffers(const_cast<Buffer &>(buffer));
473 // Join (conditionally) last pasted paragraph with next one, i.e.,
474 // the tail of the spliced document paragraph
475 if (!empty && last_paste + 1 != pit_type(pars.size())) {
476 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
477 mergeParagraph(buffer.params(), pars, last_paste);
478 } else if (pars[last_paste + 1].empty()) {
479 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
480 mergeParagraph(buffer.params(), pars, last_paste);
481 } else if (pars[last_paste].empty()) {
482 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
483 mergeParagraph(buffer.params(), pars, last_paste);
485 pars[last_paste + 1].stripLeadingSpaces(buffer.params().track_changes);
490 return PasteReturnValue(pit, pos, need_update);
494 PitPosPair eraseSelectionHelper(BufferParams const & params,
495 ParagraphList & pars,
496 pit_type startpit, pit_type endpit,
497 int startpos, int endpos)
499 // Start of selection is really invalid.
500 if (startpit == pit_type(pars.size()) ||
501 (startpos > pars[startpit].size()))
502 return PitPosPair(endpit, endpos);
504 // Start and end is inside same paragraph
505 if (endpit == pit_type(pars.size()) || startpit == endpit) {
506 endpos -= pars[startpit].eraseChars(startpos, endpos, params.track_changes);
507 return PitPosPair(endpit, endpos);
510 for (pit_type pit = startpit; pit != endpit + 1;) {
511 pos_type const left = (pit == startpit ? startpos : 0);
512 pos_type right = (pit == endpit ? endpos : pars[pit].size() + 1);
513 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.track_changes);
515 // Logically erase only, including the end-of-paragraph character
516 pars[pit].eraseChars(left, right, params.track_changes);
518 // Separate handling of paragraph break:
519 if (merge && pit != endpit &&
521 || pars[pit].hasSameLayout(pars[endpit])
522 || pars[endpit].size() == endpos)) {
523 if (pit + 1 == endpit)
524 endpos += pars[pit].size();
525 mergeParagraph(params, pars, pit);
531 // Ensure legal cursor pos:
534 return PitPosPair(endpit, endpos);
538 Buffer * copyToTempBuffer(ParagraphList const & paragraphs, DocumentClassConstPtr docclass)
540 // This used to need to be static to avoid a memory leak. It no longer needs
541 // to be so, but the alternative is to construct a new one of these (with a
542 // new temporary directory, etc) every time, and then to destroy it. So maybe
543 // it's worth just keeping this one around.
544 static TempFile tempfile("clipboard.internal");
545 tempfile.setAutoRemove(false);
546 // The initialization of staticbuffer is thread-safe. Using a lambda
547 // guarantees that the properties are set only once.
548 static Buffer * staticbuffer = [&](){
550 theBufferList().newInternalBuffer(tempfile.name().absFileName());
552 b->inset().setBuffer(*b);
553 //initialize staticbuffer with b
556 // Use a clone for the complicated stuff so that we do not need to clean
557 // up in order to avoid a crash.
558 Buffer * buffer = staticbuffer->cloneBufferOnly();
559 LASSERT(buffer, return 0);
561 // This needs doing every time.
562 // Since setDocumentClass() causes deletion of the old document class
563 // we need to reset all layout pointers in paragraphs (otherwise they
564 // would be dangling).
565 ParIterator const end = buffer->par_iterator_end();
566 for (ParIterator it = buffer->par_iterator_begin(); it != end; ++it) {
567 docstring const name = it->layout().name();
568 if (docclass->hasLayout(name))
569 it->setLayout((*docclass)[name]);
571 it->setPlainOrDefaultLayout(*docclass);
573 buffer->params().setDocumentClass(docclass);
575 // we will use pasteSelectionHelper to copy the paragraphs into the
576 // temporary Buffer, since it does a lot of things to fix them up.
577 DocIterator dit = doc_iterator_begin(buffer, &buffer->inset());
579 pasteSelectionHelper(dit, paragraphs, docclass, cap::BRANCH_ADD, el);
585 void putClipboard(ParagraphList const & paragraphs,
586 DocumentClassConstPtr docclass, docstring const & plaintext)
588 Buffer * buffer = copyToTempBuffer(paragraphs, docclass);
589 if (!buffer) // already asserted in copyToTempBuffer()
592 // We don't want to produce images that are not used. Therefore,
593 // output formulas as MathML. Even if this is not understood by all
594 // applications, the number that can parse it should go up in the future.
595 buffer->params().html_math_output = BufferParams::MathML;
597 // Make sure MarkAsExporting is deleted before buffer is
599 // The Buffer is being used to export. This is necessary so that the
600 // updateMacros call will record the needed information.
601 MarkAsExporting mex(buffer);
603 buffer->updateBuffer(Buffer::UpdateMaster, OutputUpdate);
604 buffer->updateMacros();
605 buffer->updateMacroInstances(OutputUpdate);
610 if (buffer->write(oslyx))
614 odocstringstream oshtml;
615 OutputParams runparams(encodings.fromLyXName("utf8"));
616 // We do not need to produce images, etc.
617 runparams.dryrun = true;
618 // We are not interested in errors (bug 8866)
619 runparams.silent = true;
620 buffer->writeLyXHTMLSource(oshtml, runparams, Buffer::FullSource);
622 theClipboard().put(lyx, oshtml.str(), plaintext);
630 /// return true if the whole ParagraphList is deleted
631 static bool isFullyDeleted(ParagraphList const & pars)
633 pit_type const pars_size = static_cast<pit_type>(pars.size());
635 // check all paragraphs
636 for (pit_type pit = 0; pit < pars_size; ++pit) {
637 if (!pars[pit].empty()) // prevent assertion failure
638 if (!pars[pit].isDeleted(0, pars[pit].size()))
645 void copySelectionHelper(Buffer const & buf, Text const & text,
646 pit_type startpit, pit_type endpit,
647 int start, int end, DocumentClassConstPtr dc, CutStack & cutstack)
649 ParagraphList const & pars = text.paragraphs();
651 // In most of these cases, we can try to recover.
652 LASSERT(0 <= start, start = 0);
653 LASSERT(start <= pars[startpit].size(), start = pars[startpit].size());
654 LASSERT(0 <= end, end = 0);
655 LASSERT(end <= pars[endpit].size(), end = pars[endpit].size());
656 LASSERT(startpit != endpit || start <= end, return);
658 // Clone the paragraphs within the selection.
659 ParagraphList copy_pars(lyx::next(pars.begin(), startpit),
660 lyx::next(pars.begin(), endpit + 1));
662 // Remove the end of the last paragraph; afterwards, remove the
663 // beginning of the first paragraph. Keep this order - there may only
664 // be one paragraph! Do not track deletions here; this is an internal
665 // action not visible to the user
667 Paragraph & back = copy_pars.back();
668 back.eraseChars(end, back.size(), false);
669 Paragraph & front = copy_pars.front();
670 front.eraseChars(0, start, false);
672 ParagraphList::iterator it = copy_pars.begin();
673 ParagraphList::iterator it_end = copy_pars.end();
675 for (; it != it_end; ++it) {
676 // Since we have a copy of the paragraphs, the insets
677 // do not have a proper buffer reference. It makes
678 // sense to add them temporarily, because the
679 // operations below depend on that (acceptChanges included).
680 it->setInsetBuffers(const_cast<Buffer &>(buf));
681 // PassThru paragraphs have the Language
682 // latex_language. This is invalid for others, so we
683 // need to change it to the buffer language.
684 if (it->isPassThru())
685 it->changeLanguage(buf.params(),
686 latex_language, buf.language());
689 // do not copy text (also nested in insets) which is marked as
690 // deleted, unless the whole selection was deleted
691 if (!isFullyDeleted(copy_pars))
692 acceptChanges(copy_pars, buf.params());
694 rejectChanges(copy_pars, buf.params());
697 // do some final cleanup now, to make sure that the paragraphs
698 // are not linked to something else.
699 it = copy_pars.begin();
700 for (; it != it_end; ++it) {
702 it->setInsetOwner(0);
705 cutstack.push(make_pair(copy_pars, dc));
713 void region(CursorSlice const & i1, CursorSlice const & i2,
714 Inset::row_type & r1, Inset::row_type & r2,
715 Inset::col_type & c1, Inset::col_type & c2)
717 Inset & p = i1.inset();
718 c1 = p.col(i1.idx());
719 c2 = p.col(i2.idx());
722 r1 = p.row(i1.idx());
723 r2 = p.row(i2.idx());
729 docstring grabAndEraseSelection(Cursor & cur)
731 if (!cur.selection())
733 docstring res = grabSelection(cur);
739 bool reduceSelectionToOneCell(CursorData & cur)
741 if (!cur.selection() || !cur.inMathed())
744 CursorSlice i1 = cur.selBegin();
745 CursorSlice i2 = cur.selEnd();
746 if (!i1.inset().asInsetMath())
749 // the easy case: do nothing if only one cell is selected
750 if (i1.idx() == i2.idx())
755 cur.top().pos() = cur.top().lastpos();
761 bool multipleCellsSelected(CursorData const & cur)
763 if (!cur.selection() || !cur.inMathed())
766 CursorSlice i1 = cur.selBegin();
767 CursorSlice i2 = cur.selEnd();
768 if (!i1.inset().asInsetMath())
771 if (i1.idx() == i2.idx())
778 void switchBetweenClasses(DocumentClassConstPtr oldone,
779 DocumentClassConstPtr newone, InsetText & in, ErrorList & errorlist)
783 LBUFERR(!in.paragraphs().empty());
784 if (oldone == newone)
787 DocumentClass const & oldtc = *oldone;
788 DocumentClass const & newtc = *newone;
791 ParIterator it = par_iterator_begin(in);
792 ParIterator end = par_iterator_end(in);
793 // for remembering which layouts we've had to add
794 set<docstring> newlayouts;
795 for (; it != end; ++it) {
796 docstring const name = it->layout().name();
798 // the pasted text will keep their own layout name. If this layout does
799 // not exist in the new document, it will behave like a standard layout.
800 bool const added_one = newtc.addLayoutIfNeeded(name);
802 newlayouts.insert(name);
804 if (added_one || newlayouts.find(name) != newlayouts.end()) {
806 docstring const s = bformat(_("Layout `%1$s' was not found."), name);
807 errorlist.push_back(ErrorItem(_("Layout Not Found"), s,
808 {it->id(), 0}, {it->id(), -1}));
811 if (in.usePlainLayout())
812 it->setLayout(newtc.plainLayout());
814 it->setLayout(newtc[name]);
817 // character styles and hidden table cells
818 InsetIterator const i_end = inset_iterator_end(in);
819 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
820 InsetCode const code = it->lyxCode();
821 if (code == FLEX_CODE) {
822 // FIXME: Should we verify all InsetCollapsible?
823 docstring const layoutName = it->layoutName();
824 docstring const & n = newone->insetLayout(layoutName).name();
825 bool const is_undefined = n.empty() ||
826 n == DocumentClass::plainInsetLayout().name();
830 // The flex inset is undefined in newtc
831 docstring const oldname = from_utf8(oldtc.name());
832 docstring const newname = from_utf8(newtc.name());
834 if (oldname == newname)
835 s = bformat(_("Flex inset %1$s is undefined after "
836 "reloading `%2$s' layout."), layoutName, oldname);
838 s = bformat(_("Flex inset %1$s is undefined because of "
839 "conversion from `%2$s' layout to `%3$s'."),
840 layoutName, oldname, newname);
841 // To warn the user that something had to be done.
842 errorlist.push_back(ErrorItem(
843 _("Undefined flex inset"), s,
844 {it.paragraph().id(), it.pos()},
845 {it.paragraph().id(), it.pos()+1}));
846 } else if (code == TABULAR_CODE) {
847 // The recursion above does not catch paragraphs in "hidden" cells,
848 // i.e., ones that are part of a multirow or multicolum. So we need
849 // to handle those separately.
850 // This is the cause of bug #9049.
851 InsetTabular * table = it->asInsetTabular();
852 table->setLayoutForHiddenCells(newtc);
858 vector<docstring> availableSelections(Buffer const * buf)
860 vector<docstring> selList;
864 CutStack::const_iterator cit = theCuts.begin();
865 CutStack::const_iterator end = theCuts.end();
866 for (; cit != end; ++cit) {
867 // we do not use cit-> here because gcc 2.9x does not
869 ParagraphList const & pars = (*cit).first;
871 ParagraphList::const_iterator pit = pars.begin();
872 ParagraphList::const_iterator pend = pars.end();
873 for (; pit != pend; ++pit) {
874 Paragraph par(*pit, 0, 46);
875 // adapt paragraph to current buffer.
876 par.setInsetBuffers(const_cast<Buffer &>(*buf));
877 textSel += par.asString(AS_STR_INSETS);
878 if (textSel.size() > 45) {
879 support::truncateWithEllipsis(textSel,45);
883 selList.push_back(textSel);
890 size_type numberOfSelections()
892 return theCuts.size();
897 void cutSelectionHelper(Cursor & cur, CutStack & cuts, bool doclear, bool realcut, bool putclip)
899 // This doesn't make sense, if there is no selection
900 if (!cur.selection())
903 // OK, we have a selection. This is always between cur.selBegin()
906 if (cur.inTexted()) {
907 Text * text = cur.text();
912 // make sure that the depth behind the selection are restored, too
913 cur.recordUndoSelection();
914 pit_type begpit = cur.selBegin().pit();
915 pit_type endpit = cur.selEnd().pit();
917 int endpos = cur.selEnd().pos();
919 BufferParams const & bp = cur.buffer()->params();
921 copySelectionHelper(*cur.buffer(),
924 cur.selBegin().pos(), endpos,
925 bp.documentClassPtr(), cuts);
926 // Stuff what we got on the clipboard.
927 // Even if there is no selection.
929 putClipboard(cuts[0].first, cuts[0].second,
930 cur.selectionAsString(true));
933 if (begpit != endpit)
934 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
936 tie(endpit, endpos) =
937 eraseSelectionHelper(bp, text->paragraphs(), begpit, endpit,
938 cur.selBegin().pos(), endpos);
940 // cutSelection can invalidate the cursor so we need to set
942 // we prefer the end for when tracking changes
946 // sometimes necessary
948 && text->paragraphs()[begpit].stripLeadingSpaces(bp.track_changes))
951 // need a valid cursor. (Lgb)
952 cur.clearSelection();
954 // After a cut operation, we must make sure that the Buffer is updated
955 // because some further operation might need updated label information for
956 // example. So we cannot just use "cur.forceBufferUpdate()" here.
958 cur.buffer()->updateBuffer();
960 // tell tabular that a recent copy happened
961 dirtyTabularStack(false);
964 if (cur.inMathed()) {
965 if (cur.selBegin().idx() != cur.selEnd().idx()) {
966 // The current selection spans more than one cell.
968 cur.recordUndoInset();
970 // Record only the current cell to avoid a jumping
982 void cutSelection(Cursor & cur, bool doclear, bool realcut)
984 cutSelectionHelper(cur, theCuts, doclear, realcut, true);
988 void cutSelectionToTemp(Cursor & cur, bool doclear, bool realcut)
990 cutSelectionHelper(cur, tempCut, doclear, realcut, false);
994 void copySelection(Cursor const & cur)
996 copySelection(cur, cur.selectionAsString(true));
1000 void copyInset(Cursor const & cur, Inset * inset, docstring const & plaintext)
1004 BufferParams const & bp = cur.buffer()->params();
1005 par.setLayout(bp.documentClass().plainLayout());
1006 Font font(inherit_font, bp.language);
1007 par.insertInset(0, inset, font, Change(Change::UNCHANGED));
1008 pars.push_back(par);
1009 theCuts.push(make_pair(pars, bp.documentClassPtr()));
1011 // stuff the selection onto the X clipboard, from an explicit copy request
1012 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
1018 void copySelectionToStack(CursorData const & cur, CutStack & cutstack)
1020 // this doesn't make sense, if there is no selection
1021 if (!cur.selection())
1024 // copySelection can not yet handle the case of cross idx selection
1025 if (cur.selBegin().idx() != cur.selEnd().idx())
1028 if (cur.inTexted()) {
1029 Text * text = cur.text();
1031 // ok we have a selection. This is always between cur.selBegin()
1032 // and sel_end cursor
1033 copySelectionHelper(*cur.buffer(), *text,
1034 cur.selBegin().pit(), cur.selEnd().pit(),
1035 cur.selBegin().pos(), cur.selEnd().pos(),
1036 cur.buffer()->params().documentClassPtr(),
1038 // Reset the dirty_tabular_stack_ flag only when something
1039 // is copied to the clipboard (not to the selectionBuffer).
1040 if (&cutstack == &theCuts)
1041 dirtyTabularStack(false);
1044 if (cur.inMathed()) {
1045 //lyxerr << "copySelection in mathed" << endl;
1048 BufferParams const & bp = cur.buffer()->params();
1049 // FIXME This should be the plain layout...right?
1050 par.setLayout(bp.documentClass().plainLayout());
1051 par.insert(0, grabSelection(cur), Font(), Change(Change::UNCHANGED));
1052 pars.push_back(par);
1053 cutstack.push(make_pair(pars, bp.documentClassPtr()));
1060 void copySelectionToStack()
1062 if (!selectionBuffer.empty())
1063 theCuts.push(selectionBuffer[0]);
1067 void copySelection(Cursor const & cur, docstring const & plaintext)
1069 // In tablemode, because copy and paste actually use special table stack
1070 // we do not attempt to get selected paragraphs under cursor. Instead, a
1071 // paragraph with the plain text version is generated so that table cells
1072 // can be pasted as pure text somewhere else.
1073 if (cur.selBegin().idx() != cur.selEnd().idx()) {
1076 BufferParams const & bp = cur.buffer()->params();
1077 par.setLayout(bp.documentClass().plainLayout());
1078 par.insert(0, plaintext, Font(), Change(Change::UNCHANGED));
1079 pars.push_back(par);
1080 theCuts.push(make_pair(pars, bp.documentClassPtr()));
1082 copySelectionToStack(cur, theCuts);
1085 // stuff the selection onto the X clipboard, from an explicit copy request
1086 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
1090 void saveSelection(Cursor const & cur)
1092 // This function is called, not when a selection is formed, but when
1093 // a selection is cleared. Therefore, multiple keyboard selection
1094 // will not repeatively trigger this function (bug 3877).
1096 && cur.selBegin() == cur.bv().cursor().selBegin()
1097 && cur.selEnd() == cur.bv().cursor().selEnd()) {
1098 LYXERR(Debug::SELECTION, "saveSelection: '" << cur.selectionAsString(true) << "'");
1099 copySelectionToStack(cur, selectionBuffer);
1106 return !selectionBuffer.empty();
1110 void clearSelection()
1112 selectionBuffer.clear();
1116 void clearCutStack()
1123 docstring selection(size_t sel_index, DocumentClassConstPtr docclass)
1125 if (sel_index >= theCuts.size())
1128 unique_ptr<Buffer> buffer(copyToTempBuffer(theCuts[sel_index].first,
1133 return buffer->paragraphs().back().asString(AS_STR_INSETS | AS_STR_NEWLINES);
1137 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
1138 DocumentClassConstPtr docclass, ErrorList & errorList,
1139 cap::BranchAction branchAction)
1141 if (cur.inTexted()) {
1142 Text * text = cur.text();
1145 PasteReturnValue prv =
1146 pasteSelectionHelper(cur, parlist, docclass, branchAction, errorList);
1147 cur.forceBufferUpdate();
1148 cur.clearSelection();
1149 text->setCursor(cur, prv.pit, prv.pos);
1152 // mathed is handled in InsetMathNest/InsetMathGrid
1153 LATTEST(!cur.inMathed());
1157 bool pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
1159 // this does not make sense, if there is nothing to paste
1160 if (!checkPastePossible(sel_index))
1164 pasteParagraphList(cur, theCuts[sel_index].first,
1165 theCuts[sel_index].second, errorList, BRANCH_ASK);
1170 bool pasteFromTemp(Cursor & cur, ErrorList & errorList)
1172 // this does not make sense, if there is nothing to paste
1173 if (tempCut.empty() || tempCut[0].first.empty())
1177 pasteParagraphList(cur, tempCut[0].first,
1178 tempCut[0].second, errorList, BRANCH_IGNORE);
1183 bool pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs,
1184 Clipboard::TextType type)
1186 // Use internal clipboard if it is the most recent one
1187 // This overrides asParagraphs and type on purpose!
1188 if (theClipboard().isInternal())
1189 return pasteFromStack(cur, errorList, 0);
1191 // First try LyX format
1192 if ((type == Clipboard::LyXTextType ||
1193 type == Clipboard::LyXOrPlainTextType ||
1194 type == Clipboard::AnyTextType) &&
1195 theClipboard().hasTextContents(Clipboard::LyXTextType)) {
1196 string lyx = theClipboard().getAsLyX();
1198 // For some strange reason gcc 3.2 and 3.3 do not accept
1199 // Buffer buffer(string(), false);
1200 Buffer buffer("", false);
1201 buffer.setUnnamed(true);
1202 if (buffer.readString(lyx)) {
1204 pasteParagraphList(cur, buffer.paragraphs(),
1205 buffer.params().documentClassPtr(), errorList);
1211 // Then try TeX and HTML
1212 Clipboard::TextType types[2] = {Clipboard::HtmlTextType, Clipboard::LaTeXTextType};
1213 string names[2] = {"html", "latexclipboard"};
1214 for (int i = 0; i < 2; ++i) {
1215 if (type != types[i] && type != Clipboard::AnyTextType)
1217 bool available = theClipboard().hasTextContents(types[i]);
1219 // If a specific type was explicitly requested, try to
1220 // interpret plain text: The user told us that the clipboard
1221 // contents is in the desired format
1222 if (!available && type == types[i]) {
1223 types[i] = Clipboard::PlainTextType;
1224 available = theClipboard().hasTextContents(types[i]);
1228 docstring text = theClipboard().getAsText(types[i]);
1229 available = !text.empty();
1231 // For some strange reason gcc 3.2 and 3.3 do not accept
1232 // Buffer buffer(string(), false);
1233 Buffer buffer("", false);
1234 buffer.setUnnamed(true);
1235 available = buffer.importString(names[i], text, errorList);
1237 available = !buffer.paragraphs().empty();
1238 if (available && !buffer.paragraphs()[0].empty()) {
1240 pasteParagraphList(cur, buffer.paragraphs(),
1241 buffer.params().documentClassPtr(), errorList);
1248 // Then try plain text
1249 docstring const text = theClipboard().getAsText(Clipboard::PlainTextType);
1254 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1256 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1257 cur.forceBufferUpdate();
1262 void pasteSimpleText(Cursor & cur, bool asParagraphs)
1265 // Use internal clipboard if it is the most recent one
1266 if (theClipboard().isInternal()) {
1267 if (!checkPastePossible(0))
1270 ParagraphList const & pars = theCuts[0].first;
1271 ParagraphList::const_iterator it = pars.begin();
1272 for (; it != pars.end(); ++it) {
1273 if (it != pars.begin())
1275 text += (*it).asString();
1277 asParagraphs = false;
1279 // Then try plain text
1280 text = theClipboard().getAsText(Clipboard::PlainTextType);
1287 cutSelection(cur, true, false);
1289 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1291 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1295 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
1296 Clipboard::GraphicsType preferedType)
1298 LASSERT(theClipboard().hasGraphicsContents(preferedType), return);
1300 // get picture from clipboard
1301 FileName filename = theClipboard().getAsGraphics(cur, preferedType);
1302 if (filename.empty())
1305 // create inset for graphic
1306 InsetGraphics * inset = new InsetGraphics(cur.buffer());
1307 InsetGraphicsParams params;
1308 params.filename = support::DocFileName(filename.absFileName(), false);
1309 inset->setParams(params);
1315 void pasteSelection(Cursor & cur, ErrorList & errorList)
1317 if (selectionBuffer.empty())
1320 pasteParagraphList(cur, selectionBuffer[0].first,
1321 selectionBuffer[0].second, errorList);
1325 void replaceSelectionWithString(Cursor & cur, docstring const & str)
1328 DocIterator selbeg = cur.selectionBegin();
1330 // Get font setting before we cut, we need a copy here, not a bare reference.
1332 selbeg.paragraph().getFontSettings(cur.buffer()->params(), selbeg.pos());
1334 // Insert the new string
1335 pos_type pos = cur.selEnd().pos();
1336 Paragraph & par = cur.selEnd().paragraph();
1337 docstring::const_iterator cit = str.begin();
1338 docstring::const_iterator end = str.end();
1339 for (; cit != end; ++cit, ++pos)
1340 par.insertChar(pos, *cit, font, cur.buffer()->params().track_changes);
1342 // Cut the selection
1343 cutSelection(cur, true, false);
1347 void replaceSelection(Cursor & cur)
1349 if (cur.selection())
1350 cutSelection(cur, true, false);
1354 void eraseSelection(Cursor & cur)
1356 //lyxerr << "cap::eraseSelection begin: " << cur << endl;
1357 CursorSlice const & i1 = cur.selBegin();
1358 CursorSlice const & i2 = cur.selEnd();
1359 if (!i1.asInsetMath()) {
1360 LYXERR0("Can't erase this selection");
1366 InsetMath * p = i1.asInsetMath();
1367 if (i1.idx() == i2.idx()) {
1368 i1.cell().erase(i1.pos(), i2.pos());
1369 // We may have deleted i1.cell(cur.pos()).
1370 // Make sure that pos is valid.
1371 if (cur.pos() > cur.lastpos())
1372 cur.pos() = cur.lastpos();
1373 } else if (p->nrows() > 0 && p->ncols() > 0) {
1374 // This is a grid, delete a nice square region
1375 Inset::row_type r1, r2;
1376 Inset::col_type c1, c2;
1377 region(i1, i2, r1, r2, c1, c2);
1378 for (Inset::row_type row = r1; row <= r2; ++row)
1379 for (Inset::col_type col = c1; col <= c2; ++col)
1380 p->cell(p->index(row, col)).clear();
1381 // We've deleted the whole cell. Only pos 0 is valid.
1384 Inset::idx_type idx1 = i1.idx();
1385 Inset::idx_type idx2 = i2.idx();
1388 for (Inset::idx_type idx = idx1 ; idx <= idx2; ++idx)
1389 p->cell(idx).clear();
1390 // We've deleted the whole cell. Only pos 0 is valid.
1394 // need a valid cursor. (Lgb)
1395 cur.clearSelection();
1396 //lyxerr << "cap::eraseSelection end: " << cur << endl;
1400 void selDel(Cursor & cur)
1402 //lyxerr << "cap::selDel" << endl;
1403 if (cur.selection())
1404 eraseSelection(cur);
1408 void selClearOrDel(Cursor & cur)
1410 //lyxerr << "cap::selClearOrDel" << endl;
1411 if (lyxrc.auto_region_delete)
1414 cur.selection(false);
1418 docstring grabSelection(CursorData const & cur)
1420 if (!cur.selection())
1424 // grab selection by glueing multiple cells together. This is not what
1425 // we want because selections spanning multiple cells will get "&" and "\\"
1428 for (DocIterator dit = cur.selectionBegin();
1429 dit != cur.selectionEnd(); dit.forwardPos())
1430 os << asString(dit.cell());
1434 CursorSlice i1 = cur.selBegin();
1435 CursorSlice i2 = cur.selEnd();
1437 if (i1.idx() == i2.idx()) {
1438 if (i1.inset().asInsetMath()) {
1439 MathData::const_iterator it = i1.cell().begin();
1440 Buffer * buf = cur.buffer();
1441 return asString(MathData(buf, it + i1.pos(), it + i2.pos()));
1443 return from_ascii("unknown selection 1");
1447 Inset::row_type r1, r2;
1448 Inset::col_type c1, c2;
1449 region(i1, i2, r1, r2, c1, c2);
1452 if (i1.inset().asInsetMath()) {
1453 for (Inset::row_type row = r1; row <= r2; ++row) {
1456 for (Inset::col_type col = c1; col <= c2; ++col) {
1459 data += asString(i1.asInsetMath()->
1460 cell(i1.asInsetMath()->index(row, col)));
1464 data = from_ascii("unknown selection 2");
1470 void dirtyTabularStack(bool b)
1472 dirty_tabular_stack_ = b;
1476 bool tabularStackDirty()
1478 return dirty_tabular_stack_;