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) {
171 char_type const c = insertion[i].getChar(j);
172 if (!e->encodable(c)) {
173 // do not track deletion
175 insertion[i].eraseChar(j, false);
181 docstring const uncodable = res.str();
182 if (!uncodable.empty()) {
183 if (uncodable.size() == 1)
184 uncodable_content = bformat(_("The character \"%1$s\" is uncodable in this verbatim context "
185 "and thus has not been pasted."),
188 uncodable_content = bformat(_("The characters \"%1$s\" are uncodable in this verbatim context "
189 "and thus have not been pasted."),
194 // set the paragraphs to plain layout if necessary
195 DocumentClassConstPtr newDocClass = buffer.params().documentClassPtr();
196 if (cur.inset().usePlainLayout()) {
197 bool forcePlainLayout = target_inset->forcePlainLayout();
198 Layout const & plainLayout = newDocClass->plainLayout();
199 Layout const & defaultLayout = newDocClass->defaultLayout();
200 ParagraphList::iterator const end = insertion.end();
201 ParagraphList::iterator par = insertion.begin();
202 for (; par != end; ++par) {
203 Layout const & parLayout = par->layout();
204 if (forcePlainLayout || parLayout == defaultLayout)
205 par->setLayout(plainLayout);
208 // check if we need to reset from plain layout
209 Layout const & defaultLayout = newDocClass->defaultLayout();
210 Layout const & plainLayout = newDocClass->plainLayout();
211 ParagraphList::iterator const end = insertion.end();
212 ParagraphList::iterator par = insertion.begin();
213 for (; par != end; ++par) {
214 Layout const & parLayout = par->layout();
215 if (parLayout == plainLayout)
216 par->setLayout(defaultLayout);
220 InsetText in(cur.buffer());
221 // Make sure there is no class difference.
222 in.paragraphs().clear();
223 // This works without copying any paragraph data because we have
224 // a specialized swap method for ParagraphList. This is important
225 // since we store pointers to insets at some places and we don't
226 // want to invalidate them.
227 insertion.swap(in.paragraphs());
228 cap::switchBetweenClasses(oldDocClass, newDocClass, in, errorlist);
229 // Do this here since switchBetweenClasses clears the errorlist
230 if (!uncodable_content.empty())
231 errorlist.push_back(ErrorItem(_("Uncodable content"), uncodable_content));
232 insertion.swap(in.paragraphs());
234 ParagraphList::iterator tmpbuf = insertion.begin();
235 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
237 depth_type max_depth = pars[pit].getMaxDepthAfter();
239 for (; tmpbuf != insertion.end(); ++tmpbuf) {
240 // If we have a negative jump so that the depth would
241 // go below 0 depth then we have to redo the delta to
242 // this new max depth level so that subsequent
243 // paragraphs are aligned correctly to this paragraph
245 if (int(tmpbuf->params().depth()) + depth_delta < 0)
248 // Set the right depth so that we are not too deep or shallow.
249 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
250 if (tmpbuf->params().depth() > max_depth)
251 tmpbuf->params().depth(max_depth);
253 // Set max_depth for the next paragraph
254 max_depth = tmpbuf->getMaxDepthAfter();
256 // Set the inset owner of this paragraph.
257 tmpbuf->setInsetOwner(target_inset);
258 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
259 // do not track deletion of invalid insets
260 if (Inset * inset = tmpbuf->getInset(i))
261 if (!target_inset->insetAllowed(inset->lyxCode()))
262 tmpbuf->eraseChar(i--, false);
265 tmpbuf->setChange(Change(buffer.params().track_changes ?
266 Change::INSERTED : Change::UNCHANGED));
269 bool const empty = pars[pit].empty();
271 // Make the buf exactly the same layout as the cursor
273 insertion.begin()->makeSameLayout(pars[pit]);
276 // Prepare the paragraphs and insets for insertion.
277 insertion.swap(in.paragraphs());
279 InsetIterator const i_end = inset_iterator_end(in);
280 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
281 // Even though this will also be done later, it has to be done here
282 // since some inset might going to try to access
283 // the buffer() member.
284 it->setBuffer(const_cast<Buffer &>(buffer));
285 switch (it->lyxCode()) {
287 case MATH_HULL_CODE: {
288 // check for equation labels and resolve duplicates
289 InsetMathHull * ins = it->asInsetMath()->asHullInset();
290 std::vector<InsetLabel *> labels = ins->getLabels();
291 for (size_t i = 0; i != labels.size(); ++i) {
294 InsetLabel * lab = labels[i];
295 docstring const oldname = lab->getParam("name");
296 lab->updateLabel(oldname);
297 // We need to update the buffer reference cache.
299 docstring const newname = lab->getParam("name");
300 if (oldname == newname)
302 // adapt the references
303 for (InsetIterator itt = inset_iterator_begin(in);
304 itt != i_end; ++itt) {
305 if (itt->lyxCode() == REF_CODE) {
306 InsetCommand * ref = itt->asInsetCommand();
307 if (ref->getParam("reference") == oldname)
308 ref->setParam("reference", newname);
309 } else if (itt->lyxCode() == MATH_REF_CODE) {
310 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
311 // this is necessary to prevent an uninitialized
312 // buffer when the RefInset is in a MathBox.
313 // FIXME audit setBuffer calls
314 mi->setBuffer(const_cast<Buffer &>(buffer));
315 if (mi->getTarget() == oldname)
316 mi->changeTarget(newname);
324 // check for duplicates
325 InsetLabel & lab = static_cast<InsetLabel &>(*it);
326 docstring const oldname = lab.getParam("name");
327 lab.updateLabel(oldname);
328 // We need to update the buffer reference cache.
330 docstring const newname = lab.getParam("name");
331 if (oldname == newname)
333 // adapt the references
334 for (InsetIterator itt = inset_iterator_begin(in); itt != i_end; ++itt) {
335 if (itt->lyxCode() == REF_CODE) {
336 InsetCommand & ref = static_cast<InsetCommand &>(*itt);
337 if (ref.getParam("reference") == oldname)
338 ref.setParam("reference", newname);
339 } else if (itt->lyxCode() == MATH_REF_CODE) {
340 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
341 // this is necessary to prevent an uninitialized
342 // buffer when the RefInset is in a MathBox.
343 // FIXME audit setBuffer calls
344 mi->setBuffer(const_cast<Buffer &>(buffer));
345 if (mi->getTarget() == oldname)
346 mi->changeTarget(newname);
353 InsetInclude & inc = static_cast<InsetInclude &>(*it);
355 // We need to update the list of included files.
361 // check for duplicates
362 InsetBibitem & bib = static_cast<InsetBibitem &>(*it);
363 docstring const oldkey = bib.getParam("key");
364 bib.updateCommand(oldkey, false);
365 // We need to update the buffer reference cache.
367 docstring const newkey = bib.getParam("key");
368 if (oldkey == newkey)
370 // adapt the references
371 for (InsetIterator itt = inset_iterator_begin(in);
372 itt != i_end; ++itt) {
373 if (itt->lyxCode() == CITE_CODE) {
374 InsetCommand * ref = itt->asInsetCommand();
375 if (ref->getParam("key") == oldkey)
376 ref->setParam("key", newkey);
383 // check if branch is known to target buffer
385 InsetBranch & br = static_cast<InsetBranch &>(*it);
386 docstring const name = br.branch();
389 bool const is_child = (&buffer != buffer.masterBuffer());
390 BranchList branchlist = buffer.params().branchlist();
391 if ((!is_child && branchlist.find(name))
392 || (is_child && (branchlist.find(name)
393 || buffer.masterBuffer()->params().branchlist().find(name))))
395 switch(branchAction) {
396 case cap::BRANCH_ADD: {
397 // This is for a temporary buffer, so simply create the branch.
398 // Must not use lyx::dispatch(), since tmpbuffer has no view.
400 const_cast<Buffer&>(buffer).dispatch(FuncRequest(LFUN_BRANCH_ADD, name), dr);
403 case cap::BRANCH_ASK: {
404 docstring text = bformat(
405 _("The pasted branch \"%1$s\" is undefined.\n"
406 "Do you want to add it to the document's branch list?"),
408 if (frontend::Alert::prompt(_("Unknown branch"),
409 text, 0, 1, _("&Add"), _("&Don't Add")) != 0)
411 lyx::dispatch(FuncRequest(LFUN_BRANCH_ADD, name));
414 case cap::BRANCH_IGNORE:
417 // We need to update the list of branches.
426 insertion.swap(in.paragraphs());
428 // Split the paragraph for inserting the buf if necessary.
430 breakParagraphConservative(buffer.params(), pars, pit, pos);
434 pars.insert(lyx::next(pars.begin(), pit),
438 // merge the empty par with the last par of the insertion
439 mergeParagraph(buffer.params(), pars,
440 pit + insertion.size() - 1);
442 pars.insert(lyx::next(pars.begin(), pit + 1),
446 // merge the first par of the insertion with the current par
447 mergeParagraph(buffer.params(), pars, pit);
450 // Store the new cursor position.
451 pit_type last_paste = pit + insertion.size() - 1;
452 pit_type startpit = pit;
454 pos = pars[last_paste].size();
456 // FIXME Should we do it here, or should we let updateBuffer() do it?
457 // Set paragraph buffers. It's important to do this right away
458 // before something calls Inset::buffer() and causes a crash.
459 for (pit_type p = startpit; p <= pit; ++p)
460 pars[p].setBuffer(const_cast<Buffer &>(buffer));
462 // Join (conditionally) last pasted paragraph with next one, i.e.,
463 // the tail of the spliced document paragraph
464 if (!empty && last_paste + 1 != pit_type(pars.size())) {
465 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
466 mergeParagraph(buffer.params(), pars, last_paste);
467 } else if (pars[last_paste + 1].empty()) {
468 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
469 mergeParagraph(buffer.params(), pars, last_paste);
470 } else if (pars[last_paste].empty()) {
471 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
472 mergeParagraph(buffer.params(), pars, last_paste);
474 pars[last_paste + 1].stripLeadingSpaces(buffer.params().track_changes);
479 return PasteReturnValue(pit, pos, need_update);
483 PitPosPair eraseSelectionHelper(BufferParams const & params,
484 ParagraphList & pars,
485 pit_type startpit, pit_type endpit,
486 int startpos, int endpos)
488 // Start of selection is really invalid.
489 if (startpit == pit_type(pars.size()) ||
490 (startpos > pars[startpit].size()))
491 return PitPosPair(endpit, endpos);
493 // Start and end is inside same paragraph
494 if (endpit == pit_type(pars.size()) || startpit == endpit) {
495 endpos -= pars[startpit].eraseChars(startpos, endpos, params.track_changes);
496 return PitPosPair(endpit, endpos);
499 for (pit_type pit = startpit; pit != endpit + 1;) {
500 pos_type const left = (pit == startpit ? startpos : 0);
501 pos_type right = (pit == endpit ? endpos : pars[pit].size() + 1);
502 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.track_changes);
504 // Logically erase only, including the end-of-paragraph character
505 pars[pit].eraseChars(left, right, params.track_changes);
507 // Separate handling of paragraph break:
508 if (merge && pit != endpit &&
510 || pars[pit].hasSameLayout(pars[endpit])
511 || pars[endpit].size() == endpos)) {
512 if (pit + 1 == endpit)
513 endpos += pars[pit].size();
514 mergeParagraph(params, pars, pit);
520 // Ensure legal cursor pos:
523 return PitPosPair(endpit, endpos);
527 Buffer * copyToTempBuffer(ParagraphList const & paragraphs, DocumentClassConstPtr docclass)
529 // This used to need to be static to avoid a memory leak. It no longer needs
530 // to be so, but the alternative is to construct a new one of these (with a
531 // new temporary directory, etc) every time, and then to destroy it. So maybe
532 // it's worth just keeping this one around.
533 static TempFile tempfile("clipboard.internal");
534 tempfile.setAutoRemove(false);
535 // The initialization of staticbuffer is thread-safe. Using a lambda
536 // guarantees that the properties are set only once.
537 static Buffer * staticbuffer = [&](){
539 theBufferList().newInternalBuffer(tempfile.name().absFileName());
541 b->inset().setBuffer(*b);
542 //initialize staticbuffer with b
545 // Use a clone for the complicated stuff so that we do not need to clean
546 // up in order to avoid a crash.
547 Buffer * buffer = staticbuffer->cloneBufferOnly();
548 LASSERT(buffer, return 0);
550 // This needs doing every time.
551 // Since setDocumentClass() causes deletion of the old document class
552 // we need to reset all layout pointers in paragraphs (otherwise they
553 // would be dangling).
554 ParIterator const end = buffer->par_iterator_end();
555 for (ParIterator it = buffer->par_iterator_begin(); it != end; ++it) {
556 docstring const name = it->layout().name();
557 if (docclass->hasLayout(name))
558 it->setLayout((*docclass)[name]);
560 it->setPlainOrDefaultLayout(*docclass);
562 buffer->params().setDocumentClass(docclass);
564 // we will use pasteSelectionHelper to copy the paragraphs into the
565 // temporary Buffer, since it does a lot of things to fix them up.
566 DocIterator dit = doc_iterator_begin(buffer, &buffer->inset());
568 pasteSelectionHelper(dit, paragraphs, docclass, cap::BRANCH_ADD, el);
574 void putClipboard(ParagraphList const & paragraphs,
575 DocumentClassConstPtr docclass, docstring const & plaintext)
577 Buffer * buffer = copyToTempBuffer(paragraphs, docclass);
578 if (!buffer) // already asserted in copyToTempBuffer()
581 // We don't want to produce images that are not used. Therefore,
582 // output formulas as MathML. Even if this is not understood by all
583 // applications, the number that can parse it should go up in the future.
584 buffer->params().html_math_output = BufferParams::MathML;
586 // Make sure MarkAsExporting is deleted before buffer is
588 // The Buffer is being used to export. This is necessary so that the
589 // updateMacros call will record the needed information.
590 MarkAsExporting mex(buffer);
592 buffer->updateBuffer(Buffer::UpdateMaster, OutputUpdate);
593 buffer->updateMacros();
594 buffer->updateMacroInstances(OutputUpdate);
599 if (buffer->write(oslyx))
603 odocstringstream oshtml;
604 OutputParams runparams(encodings.fromLyXName("utf8"));
605 // We do not need to produce images, etc.
606 runparams.dryrun = true;
607 // We are not interested in errors (bug 8866)
608 runparams.silent = true;
609 buffer->writeLyXHTMLSource(oshtml, runparams, Buffer::FullSource);
611 theClipboard().put(lyx, oshtml.str(), plaintext);
619 /// return true if the whole ParagraphList is deleted
620 static bool isFullyDeleted(ParagraphList const & pars)
622 pit_type const pars_size = static_cast<pit_type>(pars.size());
624 // check all paragraphs
625 for (pit_type pit = 0; pit < pars_size; ++pit) {
626 if (!pars[pit].empty()) // prevent assertion failure
627 if (!pars[pit].isDeleted(0, pars[pit].size()))
634 void copySelectionHelper(Buffer const & buf, Text const & text,
635 pit_type startpit, pit_type endpit,
636 int start, int end, DocumentClassConstPtr dc, CutStack & cutstack)
638 ParagraphList const & pars = text.paragraphs();
640 // In most of these cases, we can try to recover.
641 LASSERT(0 <= start, start = 0);
642 LASSERT(start <= pars[startpit].size(), start = pars[startpit].size());
643 LASSERT(0 <= end, end = 0);
644 LASSERT(end <= pars[endpit].size(), end = pars[endpit].size());
645 LASSERT(startpit != endpit || start <= end, return);
647 // Clone the paragraphs within the selection.
648 ParagraphList copy_pars(lyx::next(pars.begin(), startpit),
649 lyx::next(pars.begin(), endpit + 1));
651 // Remove the end of the last paragraph; afterwards, remove the
652 // beginning of the first paragraph. Keep this order - there may only
653 // be one paragraph! Do not track deletions here; this is an internal
654 // action not visible to the user
656 Paragraph & back = copy_pars.back();
657 back.eraseChars(end, back.size(), false);
658 Paragraph & front = copy_pars.front();
659 front.eraseChars(0, start, false);
661 ParagraphList::iterator it = copy_pars.begin();
662 ParagraphList::iterator it_end = copy_pars.end();
664 for (; it != it_end; ++it) {
665 // Since we have a copy of the paragraphs, the insets
666 // do not have a proper buffer reference. It makes
667 // sense to add them temporarily, because the
668 // operations below depend on that (acceptChanges included).
669 it->setBuffer(const_cast<Buffer &>(buf));
670 // PassThru paragraphs have the Language
671 // latex_language. This is invalid for others, so we
672 // need to change it to the buffer language.
673 if (it->isPassThru())
674 it->changeLanguage(buf.params(),
675 latex_language, buf.language());
678 // do not copy text (also nested in insets) which is marked as
679 // deleted, unless the whole selection was deleted
680 if (!isFullyDeleted(copy_pars))
681 acceptChanges(copy_pars, buf.params());
683 rejectChanges(copy_pars, buf.params());
686 // do some final cleanup now, to make sure that the paragraphs
687 // are not linked to something else.
688 it = copy_pars.begin();
689 for (; it != it_end; ++it) {
691 it->setInsetOwner(0);
694 cutstack.push(make_pair(copy_pars, dc));
702 void region(CursorSlice const & i1, CursorSlice const & i2,
703 Inset::row_type & r1, Inset::row_type & r2,
704 Inset::col_type & c1, Inset::col_type & c2)
706 Inset & p = i1.inset();
707 c1 = p.col(i1.idx());
708 c2 = p.col(i2.idx());
711 r1 = p.row(i1.idx());
712 r2 = p.row(i2.idx());
718 docstring grabAndEraseSelection(Cursor & cur)
720 if (!cur.selection())
722 docstring res = grabSelection(cur);
728 bool reduceSelectionToOneCell(Cursor & cur)
730 if (!cur.selection() || !cur.inMathed())
733 CursorSlice i1 = cur.selBegin();
734 CursorSlice i2 = cur.selEnd();
735 if (!i1.inset().asInsetMath())
738 // the easy case: do nothing if only one cell is selected
739 if (i1.idx() == i2.idx())
744 cur.top().pos() = cur.top().lastpos();
750 bool multipleCellsSelected(Cursor const & cur)
752 if (!cur.selection() || !cur.inMathed())
755 CursorSlice i1 = cur.selBegin();
756 CursorSlice i2 = cur.selEnd();
757 if (!i1.inset().asInsetMath())
760 if (i1.idx() == i2.idx())
767 void switchBetweenClasses(DocumentClassConstPtr oldone,
768 DocumentClassConstPtr newone, InsetText & in, ErrorList & errorlist)
772 LBUFERR(!in.paragraphs().empty());
773 if (oldone == newone)
776 DocumentClass const & oldtc = *oldone;
777 DocumentClass const & newtc = *newone;
780 ParIterator it = par_iterator_begin(in);
781 ParIterator end = par_iterator_end(in);
782 // for remembering which layouts we've had to add
783 set<docstring> newlayouts;
784 for (; it != end; ++it) {
785 docstring const name = it->layout().name();
787 // the pasted text will keep their own layout name. If this layout does
788 // not exist in the new document, it will behave like a standard layout.
789 bool const added_one = newtc.addLayoutIfNeeded(name);
791 newlayouts.insert(name);
793 if (added_one || newlayouts.find(name) != newlayouts.end()) {
795 docstring const s = bformat(_("Layout `%1$s' was not found."), name);
796 errorlist.push_back(ErrorItem(_("Layout Not Found"), s,
797 {it->id(), 0}, {it->id(), -1}));
800 if (in.usePlainLayout())
801 it->setLayout(newtc.plainLayout());
803 it->setLayout(newtc[name]);
806 // character styles and hidden table cells
807 InsetIterator const i_end = inset_iterator_end(in);
808 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
809 InsetCode const code = it->lyxCode();
810 if (code == FLEX_CODE) {
811 // FIXME: Should we verify all InsetCollapsible?
812 docstring const layoutName = it->layoutName();
813 docstring const & n = newone->insetLayout(layoutName).name();
814 bool const is_undefined = n.empty() ||
815 n == DocumentClass::plainInsetLayout().name();
819 // The flex inset is undefined in newtc
820 docstring const oldname = from_utf8(oldtc.name());
821 docstring const newname = from_utf8(newtc.name());
823 if (oldname == newname)
824 s = bformat(_("Flex inset %1$s is undefined after "
825 "reloading `%2$s' layout."), layoutName, oldname);
827 s = bformat(_("Flex inset %1$s is undefined because of "
828 "conversion from `%2$s' layout to `%3$s'."),
829 layoutName, oldname, newname);
830 // To warn the user that something had to be done.
831 errorlist.push_back(ErrorItem(
832 _("Undefined flex inset"), s,
833 {it.paragraph().id(), it.pos()},
834 {it.paragraph().id(), it.pos()+1}));
835 } else if (code == TABULAR_CODE) {
836 // The recursion above does not catch paragraphs in "hidden" cells,
837 // i.e., ones that are part of a multirow or multicolum. So we need
838 // to handle those separately.
839 // This is the cause of bug #9049.
840 InsetTabular * table = it->asInsetTabular();
841 table->setLayoutForHiddenCells(newtc);
847 vector<docstring> availableSelections(Buffer const * buf)
849 vector<docstring> selList;
853 CutStack::const_iterator cit = theCuts.begin();
854 CutStack::const_iterator end = theCuts.end();
855 for (; cit != end; ++cit) {
856 // we do not use cit-> here because gcc 2.9x does not
858 ParagraphList const & pars = (*cit).first;
860 ParagraphList::const_iterator pit = pars.begin();
861 ParagraphList::const_iterator pend = pars.end();
862 for (; pit != pend; ++pit) {
863 Paragraph par(*pit, 0, 46);
864 // adapt paragraph to current buffer.
865 par.setBuffer(const_cast<Buffer &>(*buf));
866 textSel += par.asString(AS_STR_INSETS);
867 if (textSel.size() > 45) {
868 support::truncateWithEllipsis(textSel,45);
872 selList.push_back(textSel);
879 size_type numberOfSelections()
881 return theCuts.size();
886 void cutSelectionHelper(Cursor & cur, CutStack & cuts, bool doclear, bool realcut, bool putclip)
888 // This doesn't make sense, if there is no selection
889 if (!cur.selection())
892 // OK, we have a selection. This is always between cur.selBegin()
895 if (cur.inTexted()) {
896 Text * text = cur.text();
901 // make sure that the depth behind the selection are restored, too
902 cur.recordUndoSelection();
903 pit_type begpit = cur.selBegin().pit();
904 pit_type endpit = cur.selEnd().pit();
906 int endpos = cur.selEnd().pos();
908 BufferParams const & bp = cur.buffer()->params();
910 copySelectionHelper(*cur.buffer(),
913 cur.selBegin().pos(), endpos,
914 bp.documentClassPtr(), cuts);
915 // Stuff what we got on the clipboard.
916 // Even if there is no selection.
918 putClipboard(cuts[0].first, cuts[0].second,
919 cur.selectionAsString(true));
922 if (begpit != endpit)
923 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
925 tie(endpit, endpos) =
926 eraseSelectionHelper(bp, text->paragraphs(), begpit, endpit,
927 cur.selBegin().pos(), endpos);
929 // cutSelection can invalidate the cursor so we need to set
931 // we prefer the end for when tracking changes
935 // sometimes necessary
937 && text->paragraphs()[begpit].stripLeadingSpaces(bp.track_changes))
940 // need a valid cursor. (Lgb)
941 cur.clearSelection();
943 // After a cut operation, we must make sure that the Buffer is updated
944 // because some further operation might need updated label information for
945 // example. So we cannot just use "cur.forceBufferUpdate()" here.
947 cur.buffer()->updateBuffer();
949 // tell tabular that a recent copy happened
950 dirtyTabularStack(false);
953 if (cur.inMathed()) {
954 if (cur.selBegin().idx() != cur.selEnd().idx()) {
955 // The current selection spans more than one cell.
957 cur.recordUndoInset();
959 // Record only the current cell to avoid a jumping
971 void cutSelection(Cursor & cur, bool doclear, bool realcut)
973 cutSelectionHelper(cur, theCuts, doclear, realcut, true);
977 void cutSelectionToTemp(Cursor & cur, bool doclear, bool realcut)
979 cutSelectionHelper(cur, tempCut, doclear, realcut, false);
983 void copySelection(Cursor const & cur)
985 copySelection(cur, cur.selectionAsString(true));
989 void copyInset(Cursor const & cur, Inset * inset, docstring const & plaintext)
993 BufferParams const & bp = cur.buffer()->params();
994 par.setLayout(bp.documentClass().plainLayout());
995 Font font(inherit_font, bp.language);
996 par.insertInset(0, inset, font, Change(Change::UNCHANGED));
998 theCuts.push(make_pair(pars, bp.documentClassPtr()));
1000 // stuff the selection onto the X clipboard, from an explicit copy request
1001 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
1007 void copySelectionToStack(Cursor const & cur, CutStack & cutstack)
1009 // this doesn't make sense, if there is no selection
1010 if (!cur.selection())
1013 // copySelection can not yet handle the case of cross idx selection
1014 if (cur.selBegin().idx() != cur.selEnd().idx())
1017 if (cur.inTexted()) {
1018 Text * text = cur.text();
1020 // ok we have a selection. This is always between cur.selBegin()
1021 // and sel_end cursor
1022 copySelectionHelper(*cur.buffer(), *text,
1023 cur.selBegin().pit(), cur.selEnd().pit(),
1024 cur.selBegin().pos(), cur.selEnd().pos(),
1025 cur.buffer()->params().documentClassPtr(),
1027 // Reset the dirty_tabular_stack_ flag only when something
1028 // is copied to the clipboard (not to the selectionBuffer).
1029 if (&cutstack == &theCuts)
1030 dirtyTabularStack(false);
1033 if (cur.inMathed()) {
1034 //lyxerr << "copySelection in mathed" << endl;
1037 BufferParams const & bp = cur.buffer()->params();
1038 // FIXME This should be the plain layout...right?
1039 par.setLayout(bp.documentClass().plainLayout());
1040 par.insert(0, grabSelection(cur), Font(), Change(Change::UNCHANGED));
1041 pars.push_back(par);
1042 cutstack.push(make_pair(pars, bp.documentClassPtr()));
1049 void copySelectionToStack()
1051 if (!selectionBuffer.empty())
1052 theCuts.push(selectionBuffer[0]);
1056 void copySelection(Cursor const & cur, docstring const & plaintext)
1058 // In tablemode, because copy and paste actually use special table stack
1059 // we do not attempt to get selected paragraphs under cursor. Instead, a
1060 // paragraph with the plain text version is generated so that table cells
1061 // can be pasted as pure text somewhere else.
1062 if (cur.selBegin().idx() != cur.selEnd().idx()) {
1065 BufferParams const & bp = cur.buffer()->params();
1066 par.setLayout(bp.documentClass().plainLayout());
1067 par.insert(0, plaintext, Font(), Change(Change::UNCHANGED));
1068 pars.push_back(par);
1069 theCuts.push(make_pair(pars, bp.documentClassPtr()));
1071 copySelectionToStack(cur, theCuts);
1074 // stuff the selection onto the X clipboard, from an explicit copy request
1075 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
1079 void saveSelection(Cursor const & cur)
1081 // This function is called, not when a selection is formed, but when
1082 // a selection is cleared. Therefore, multiple keyboard selection
1083 // will not repeatively trigger this function (bug 3877).
1085 && cur.selBegin() == cur.bv().cursor().selBegin()
1086 && cur.selEnd() == cur.bv().cursor().selEnd()) {
1087 LYXERR(Debug::SELECTION, "saveSelection: '" << cur.selectionAsString(true) << "'");
1088 copySelectionToStack(cur, selectionBuffer);
1095 return !selectionBuffer.empty();
1099 void clearSelection()
1101 selectionBuffer.clear();
1105 void clearCutStack()
1112 docstring selection(size_t sel_index, DocumentClassConstPtr docclass)
1114 if (sel_index >= theCuts.size())
1117 unique_ptr<Buffer> buffer(copyToTempBuffer(theCuts[sel_index].first,
1122 return buffer->paragraphs().back().asString(AS_STR_INSETS | AS_STR_NEWLINES);
1126 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
1127 DocumentClassConstPtr docclass, ErrorList & errorList,
1128 cap::BranchAction branchAction)
1130 if (cur.inTexted()) {
1131 Text * text = cur.text();
1134 PasteReturnValue prv =
1135 pasteSelectionHelper(cur, parlist, docclass, branchAction, errorList);
1136 cur.forceBufferUpdate();
1137 cur.clearSelection();
1138 text->setCursor(cur, prv.pit, prv.pos);
1141 // mathed is handled in InsetMathNest/InsetMathGrid
1142 LATTEST(!cur.inMathed());
1146 bool pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
1148 // this does not make sense, if there is nothing to paste
1149 if (!checkPastePossible(sel_index))
1153 pasteParagraphList(cur, theCuts[sel_index].first,
1154 theCuts[sel_index].second, errorList, BRANCH_ASK);
1159 bool pasteFromTemp(Cursor & cur, ErrorList & errorList)
1161 // this does not make sense, if there is nothing to paste
1162 if (tempCut.empty() || tempCut[0].first.empty())
1166 pasteParagraphList(cur, tempCut[0].first,
1167 tempCut[0].second, errorList, BRANCH_IGNORE);
1172 bool pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs,
1173 Clipboard::TextType type)
1175 // Use internal clipboard if it is the most recent one
1176 // This overrides asParagraphs and type on purpose!
1177 if (theClipboard().isInternal())
1178 return pasteFromStack(cur, errorList, 0);
1180 // First try LyX format
1181 if ((type == Clipboard::LyXTextType ||
1182 type == Clipboard::LyXOrPlainTextType ||
1183 type == Clipboard::AnyTextType) &&
1184 theClipboard().hasTextContents(Clipboard::LyXTextType)) {
1185 string lyx = theClipboard().getAsLyX();
1187 // For some strange reason gcc 3.2 and 3.3 do not accept
1188 // Buffer buffer(string(), false);
1189 Buffer buffer("", false);
1190 buffer.setUnnamed(true);
1191 if (buffer.readString(lyx)) {
1193 pasteParagraphList(cur, buffer.paragraphs(),
1194 buffer.params().documentClassPtr(), errorList);
1200 // Then try TeX and HTML
1201 Clipboard::TextType types[2] = {Clipboard::HtmlTextType, Clipboard::LaTeXTextType};
1202 string names[2] = {"html", "latexclipboard"};
1203 for (int i = 0; i < 2; ++i) {
1204 if (type != types[i] && type != Clipboard::AnyTextType)
1206 bool available = theClipboard().hasTextContents(types[i]);
1208 // If a specific type was explicitly requested, try to
1209 // interpret plain text: The user told us that the clipboard
1210 // contents is in the desired format
1211 if (!available && type == types[i]) {
1212 types[i] = Clipboard::PlainTextType;
1213 available = theClipboard().hasTextContents(types[i]);
1217 docstring text = theClipboard().getAsText(types[i]);
1218 available = !text.empty();
1220 // For some strange reason gcc 3.2 and 3.3 do not accept
1221 // Buffer buffer(string(), false);
1222 Buffer buffer("", false);
1223 buffer.setUnnamed(true);
1224 available = buffer.importString(names[i], text, errorList);
1226 available = !buffer.paragraphs().empty();
1227 if (available && !buffer.paragraphs()[0].empty()) {
1229 pasteParagraphList(cur, buffer.paragraphs(),
1230 buffer.params().documentClassPtr(), errorList);
1237 // Then try plain text
1238 docstring const text = theClipboard().getAsText(Clipboard::PlainTextType);
1243 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1245 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1246 cur.forceBufferUpdate();
1251 void pasteSimpleText(Cursor & cur, bool asParagraphs)
1254 // Use internal clipboard if it is the most recent one
1255 if (theClipboard().isInternal()) {
1256 if (!checkPastePossible(0))
1259 ParagraphList const & pars = theCuts[0].first;
1260 ParagraphList::const_iterator it = pars.begin();
1261 for (; it != pars.end(); ++it) {
1262 if (it != pars.begin())
1264 text += (*it).asString();
1266 asParagraphs = false;
1268 // Then try plain text
1269 text = theClipboard().getAsText(Clipboard::PlainTextType);
1276 cutSelection(cur, true, false);
1278 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1280 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1284 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
1285 Clipboard::GraphicsType preferedType)
1287 LASSERT(theClipboard().hasGraphicsContents(preferedType), return);
1289 // get picture from clipboard
1290 FileName filename = theClipboard().getAsGraphics(cur, preferedType);
1291 if (filename.empty())
1294 // create inset for graphic
1295 InsetGraphics * inset = new InsetGraphics(cur.buffer());
1296 InsetGraphicsParams params;
1297 params.filename = support::DocFileName(filename.absFileName(), false);
1298 inset->setParams(params);
1304 void pasteSelection(Cursor & cur, ErrorList & errorList)
1306 if (selectionBuffer.empty())
1309 pasteParagraphList(cur, selectionBuffer[0].first,
1310 selectionBuffer[0].second, errorList);
1314 void replaceSelectionWithString(Cursor & cur, docstring const & str)
1317 DocIterator selbeg = cur.selectionBegin();
1319 // Get font setting before we cut, we need a copy here, not a bare reference.
1321 selbeg.paragraph().getFontSettings(cur.buffer()->params(), selbeg.pos());
1323 // Insert the new string
1324 pos_type pos = cur.selEnd().pos();
1325 Paragraph & par = cur.selEnd().paragraph();
1326 docstring::const_iterator cit = str.begin();
1327 docstring::const_iterator end = str.end();
1328 for (; cit != end; ++cit, ++pos)
1329 par.insertChar(pos, *cit, font, cur.buffer()->params().track_changes);
1331 // Cut the selection
1332 cutSelection(cur, true, false);
1336 void replaceSelection(Cursor & cur)
1338 if (cur.selection())
1339 cutSelection(cur, true, false);
1343 void eraseSelection(Cursor & cur)
1345 //lyxerr << "cap::eraseSelection begin: " << cur << endl;
1346 CursorSlice const & i1 = cur.selBegin();
1347 CursorSlice const & i2 = cur.selEnd();
1348 if (!i1.asInsetMath()) {
1349 LYXERR0("Can't erase this selection");
1355 InsetMath * p = i1.asInsetMath();
1356 if (i1.idx() == i2.idx()) {
1357 i1.cell().erase(i1.pos(), i2.pos());
1358 // We may have deleted i1.cell(cur.pos()).
1359 // Make sure that pos is valid.
1360 if (cur.pos() > cur.lastpos())
1361 cur.pos() = cur.lastpos();
1362 } else if (p->nrows() > 0 && p->ncols() > 0) {
1363 // This is a grid, delete a nice square region
1364 Inset::row_type r1, r2;
1365 Inset::col_type c1, c2;
1366 region(i1, i2, r1, r2, c1, c2);
1367 for (Inset::row_type row = r1; row <= r2; ++row)
1368 for (Inset::col_type col = c1; col <= c2; ++col)
1369 p->cell(p->index(row, col)).clear();
1370 // We've deleted the whole cell. Only pos 0 is valid.
1373 Inset::idx_type idx1 = i1.idx();
1374 Inset::idx_type idx2 = i2.idx();
1377 for (Inset::idx_type idx = idx1 ; idx <= idx2; ++idx)
1378 p->cell(idx).clear();
1379 // We've deleted the whole cell. Only pos 0 is valid.
1383 // need a valid cursor. (Lgb)
1384 cur.clearSelection();
1385 //lyxerr << "cap::eraseSelection end: " << cur << endl;
1389 void selDel(Cursor & cur)
1391 //lyxerr << "cap::selDel" << endl;
1392 if (cur.selection())
1393 eraseSelection(cur);
1397 void selClearOrDel(Cursor & cur)
1399 //lyxerr << "cap::selClearOrDel" << endl;
1400 if (lyxrc.auto_region_delete)
1403 cur.selection(false);
1407 docstring grabSelection(Cursor const & cur)
1409 if (!cur.selection())
1413 // grab selection by glueing multiple cells together. This is not what
1414 // we want because selections spanning multiple cells will get "&" and "\\"
1417 for (DocIterator dit = cur.selectionBegin();
1418 dit != cur.selectionEnd(); dit.forwardPos())
1419 os << asString(dit.cell());
1423 CursorSlice i1 = cur.selBegin();
1424 CursorSlice i2 = cur.selEnd();
1426 if (i1.idx() == i2.idx()) {
1427 if (i1.inset().asInsetMath()) {
1428 MathData::const_iterator it = i1.cell().begin();
1429 Buffer * buf = cur.buffer();
1430 return asString(MathData(buf, it + i1.pos(), it + i2.pos()));
1432 return from_ascii("unknown selection 1");
1436 Inset::row_type r1, r2;
1437 Inset::col_type c1, c2;
1438 region(i1, i2, r1, r2, c1, c2);
1441 if (i1.inset().asInsetMath()) {
1442 for (Inset::row_type row = r1; row <= r2; ++row) {
1445 for (Inset::col_type col = c1; col <= c2; ++col) {
1448 data += asString(i1.asInsetMath()->
1449 cell(i1.asInsetMath()->index(row, col)));
1453 data = from_ascii("unknown selection 2");
1459 void dirtyTabularStack(bool b)
1461 dirty_tabular_stack_ = b;
1465 bool tabularStackDirty()
1467 return dirty_tabular_stack_;