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) {
173 if (insertion[i].isInset(j))
175 char_type const c = insertion[i].getChar(j);
176 if (!e->encodable(c)) {
177 // do not track deletion
179 insertion[i].eraseChar(j, false);
185 docstring const uncodable = res.str();
186 if (!uncodable.empty()) {
187 if (uncodable.size() == 1)
188 uncodable_content = bformat(_("The character \"%1$s\" is uncodable in this verbatim context "
189 "and thus has not been pasted."),
192 uncodable_content = bformat(_("The characters \"%1$s\" are uncodable in this verbatim context "
193 "and thus have not been pasted."),
198 // set the paragraphs to plain layout if necessary
199 DocumentClassConstPtr newDocClass = buffer.params().documentClassPtr();
200 if (cur.inset().usePlainLayout()) {
201 bool forcePlainLayout = target_inset->forcePlainLayout();
202 Layout const & plainLayout = newDocClass->plainLayout();
203 Layout const & defaultLayout = newDocClass->defaultLayout();
204 ParagraphList::iterator const end = insertion.end();
205 ParagraphList::iterator par = insertion.begin();
206 for (; par != end; ++par) {
207 Layout const & parLayout = par->layout();
208 if (forcePlainLayout || parLayout == defaultLayout)
209 par->setLayout(plainLayout);
212 // check if we need to reset from plain layout
213 Layout const & defaultLayout = newDocClass->defaultLayout();
214 Layout const & plainLayout = newDocClass->plainLayout();
215 ParagraphList::iterator const end = insertion.end();
216 ParagraphList::iterator par = insertion.begin();
217 for (; par != end; ++par) {
218 Layout const & parLayout = par->layout();
219 if (parLayout == plainLayout)
220 par->setLayout(defaultLayout);
224 InsetText in(cur.buffer());
225 // Make sure there is no class difference.
226 in.paragraphs().clear();
227 // This works without copying any paragraph data because we have
228 // a specialized swap method for ParagraphList. This is important
229 // since we store pointers to insets at some places and we don't
230 // want to invalidate them.
231 insertion.swap(in.paragraphs());
232 cap::switchBetweenClasses(oldDocClass, newDocClass, in, errorlist);
233 // Do this here since switchBetweenClasses clears the errorlist
234 if (!uncodable_content.empty())
235 errorlist.push_back(ErrorItem(_("Uncodable content"), uncodable_content));
236 insertion.swap(in.paragraphs());
238 ParagraphList::iterator tmpbuf = insertion.begin();
239 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
241 depth_type max_depth = pars[pit].getMaxDepthAfter();
243 for (; tmpbuf != insertion.end(); ++tmpbuf) {
244 // If we have a negative jump so that the depth would
245 // go below 0 depth then we have to redo the delta to
246 // this new max depth level so that subsequent
247 // paragraphs are aligned correctly to this paragraph
249 if (int(tmpbuf->params().depth()) + depth_delta < 0)
252 // Set the right depth so that we are not too deep or shallow.
253 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
254 if (tmpbuf->params().depth() > max_depth)
255 tmpbuf->params().depth(max_depth);
257 // Set max_depth for the next paragraph
258 max_depth = tmpbuf->getMaxDepthAfter();
260 // Set the inset owner of this paragraph.
261 tmpbuf->setInsetOwner(target_inset);
262 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
263 // do not track deletion of invalid insets
264 if (Inset * inset = tmpbuf->getInset(i))
265 if (!target_inset->insetAllowed(inset->lyxCode()))
266 tmpbuf->eraseChar(i--, false);
269 tmpbuf->setChange(Change(buffer.params().track_changes ?
270 Change::INSERTED : Change::UNCHANGED));
273 bool const empty = pars[pit].empty();
275 // Make the buf exactly the same layout as the cursor
277 insertion.begin()->makeSameLayout(pars[pit]);
280 // Prepare the paragraphs and insets for insertion.
281 insertion.swap(in.paragraphs());
283 InsetIterator const i_end = inset_iterator_end(in);
284 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
285 // Even though this will also be done later, it has to be done here
286 // since some inset might going to try to access
287 // the buffer() member.
288 it->setBuffer(const_cast<Buffer &>(buffer));
289 switch (it->lyxCode()) {
291 case MATH_HULL_CODE: {
292 // check for equation labels and resolve duplicates
293 InsetMathHull * ins = it->asInsetMath()->asHullInset();
294 std::vector<InsetLabel *> labels = ins->getLabels();
295 for (size_t i = 0; i != labels.size(); ++i) {
298 InsetLabel * lab = labels[i];
299 docstring const oldname = lab->getParam("name");
300 lab->updateLabel(oldname);
301 // We need to update the buffer reference cache.
303 docstring const newname = lab->getParam("name");
304 if (oldname == newname)
306 // adapt the references
307 for (InsetIterator itt = inset_iterator_begin(in);
308 itt != i_end; ++itt) {
309 if (itt->lyxCode() == REF_CODE) {
310 InsetCommand * ref = itt->asInsetCommand();
311 if (ref->getParam("reference") == oldname)
312 ref->setParam("reference", newname);
313 } else if (itt->lyxCode() == MATH_REF_CODE) {
314 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
315 // this is necessary to prevent an uninitialized
316 // buffer when the RefInset is in a MathBox.
317 // FIXME audit setBuffer calls
318 mi->setBuffer(const_cast<Buffer &>(buffer));
319 if (mi->getTarget() == oldname)
320 mi->changeTarget(newname);
328 // check for duplicates
329 InsetLabel & lab = static_cast<InsetLabel &>(*it);
330 docstring const oldname = lab.getParam("name");
331 lab.updateLabel(oldname);
332 // We need to update the buffer reference cache.
334 docstring const newname = lab.getParam("name");
335 if (oldname == newname)
337 // adapt the references
338 for (InsetIterator itt = inset_iterator_begin(in); itt != i_end; ++itt) {
339 if (itt->lyxCode() == REF_CODE) {
340 InsetCommand & ref = static_cast<InsetCommand &>(*itt);
341 if (ref.getParam("reference") == oldname)
342 ref.setParam("reference", newname);
343 } else if (itt->lyxCode() == MATH_REF_CODE) {
344 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
345 // this is necessary to prevent an uninitialized
346 // buffer when the RefInset is in a MathBox.
347 // FIXME audit setBuffer calls
348 mi->setBuffer(const_cast<Buffer &>(buffer));
349 if (mi->getTarget() == oldname)
350 mi->changeTarget(newname);
357 InsetInclude & inc = static_cast<InsetInclude &>(*it);
359 // We need to update the list of included files.
365 InsetCitation & cit = static_cast<InsetCitation &>(*it);
366 // This actually only needs to be done if the cite engine
367 // differs, but we do it in general.
369 // We need to update the list of citations.
375 // check for duplicates
376 InsetBibitem & bib = static_cast<InsetBibitem &>(*it);
377 docstring const oldkey = bib.getParam("key");
378 bib.updateCommand(oldkey, false);
379 // We need to update the buffer reference cache.
381 docstring const newkey = bib.getParam("key");
382 if (oldkey == newkey)
384 // adapt the references
385 for (InsetIterator itt = inset_iterator_begin(in);
386 itt != i_end; ++itt) {
387 if (itt->lyxCode() == CITE_CODE) {
388 InsetCommand * ref = itt->asInsetCommand();
389 if (ref->getParam("key") == oldkey)
390 ref->setParam("key", newkey);
397 // check if branch is known to target buffer
399 InsetBranch & br = static_cast<InsetBranch &>(*it);
400 docstring const name = br.branch();
403 bool const is_child = (&buffer != buffer.masterBuffer());
404 BranchList branchlist = buffer.params().branchlist();
405 if ((!is_child && branchlist.find(name))
406 || (is_child && (branchlist.find(name)
407 || buffer.masterBuffer()->params().branchlist().find(name))))
409 switch(branchAction) {
410 case cap::BRANCH_ADD: {
411 // This is for a temporary buffer, so simply create the branch.
412 // Must not use lyx::dispatch(), since tmpbuffer has no view.
414 const_cast<Buffer&>(buffer).dispatch(FuncRequest(LFUN_BRANCH_ADD, name), dr);
417 case cap::BRANCH_ASK: {
418 docstring text = bformat(
419 _("The pasted branch \"%1$s\" is undefined.\n"
420 "Do you want to add it to the document's branch list?"),
422 if (frontend::Alert::prompt(_("Unknown branch"),
423 text, 0, 1, _("&Add"), _("&Don't Add")) != 0)
425 lyx::dispatch(FuncRequest(LFUN_BRANCH_ADD, name));
428 case cap::BRANCH_IGNORE:
431 // We need to update the list of branches.
440 insertion.swap(in.paragraphs());
442 // Split the paragraph for inserting the buf if necessary.
444 breakParagraphConservative(buffer.params(), pars, pit, pos);
448 pars.insert(lyx::next(pars.begin(), pit),
452 // merge the empty par with the last par of the insertion
453 mergeParagraph(buffer.params(), pars,
454 pit + insertion.size() - 1);
456 pars.insert(lyx::next(pars.begin(), pit + 1),
460 // merge the first par of the insertion with the current par
461 mergeParagraph(buffer.params(), pars, pit);
464 // Store the new cursor position.
465 pit_type last_paste = pit + insertion.size() - 1;
466 pit_type startpit = pit;
468 pos = pars[last_paste].size();
470 // FIXME Should we do it here, or should we let updateBuffer() do it?
471 // Set paragraph buffers. It's important to do this right away
472 // before something calls Inset::buffer() and causes a crash.
473 for (pit_type p = startpit; p <= pit; ++p)
474 pars[p].setInsetBuffers(const_cast<Buffer &>(buffer));
476 // Join (conditionally) last pasted paragraph with next one, i.e.,
477 // the tail of the spliced document paragraph
478 if (!empty && last_paste + 1 != pit_type(pars.size())) {
479 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
480 mergeParagraph(buffer.params(), pars, last_paste);
481 } else if (pars[last_paste + 1].empty()) {
482 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
483 mergeParagraph(buffer.params(), pars, last_paste);
484 } else if (pars[last_paste].empty()) {
485 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
486 mergeParagraph(buffer.params(), pars, last_paste);
488 pars[last_paste + 1].stripLeadingSpaces(buffer.params().track_changes);
493 return PasteReturnValue(pit, pos, need_update);
497 PitPosPair eraseSelectionHelper(BufferParams const & params,
498 ParagraphList & pars,
499 pit_type startpit, pit_type endpit,
500 int startpos, int endpos)
502 // Start of selection is really invalid.
503 if (startpit == pit_type(pars.size()) ||
504 (startpos > pars[startpit].size()))
505 return PitPosPair(endpit, endpos);
507 // Start and end is inside same paragraph
508 if (endpit == pit_type(pars.size()) || startpit == endpit) {
509 endpos -= pars[startpit].eraseChars(startpos, endpos, params.track_changes);
510 return PitPosPair(endpit, endpos);
513 for (pit_type pit = startpit; pit != endpit + 1;) {
514 pos_type const left = (pit == startpit ? startpos : 0);
515 pos_type right = (pit == endpit ? endpos : pars[pit].size() + 1);
516 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.track_changes);
518 // Logically erase only, including the end-of-paragraph character
519 pars[pit].eraseChars(left, right, params.track_changes);
521 // Separate handling of paragraph break:
522 if (merge && pit != endpit &&
524 || pars[pit].hasSameLayout(pars[endpit])
525 || pars[endpit].size() == endpos)) {
526 if (pit + 1 == endpit)
527 endpos += pars[pit].size();
528 mergeParagraph(params, pars, pit);
534 // Ensure legal cursor pos:
537 return PitPosPair(endpit, endpos);
541 Buffer * copyToTempBuffer(ParagraphList const & paragraphs, DocumentClassConstPtr docclass)
543 // This used to need to be static to avoid a memory leak. It no longer needs
544 // to be so, but the alternative is to construct a new one of these (with a
545 // new temporary directory, etc) every time, and then to destroy it. So maybe
546 // it's worth just keeping this one around.
547 static TempFile tempfile("clipboard.internal");
548 tempfile.setAutoRemove(false);
549 // The initialization of staticbuffer is thread-safe. Using a lambda
550 // guarantees that the properties are set only once.
551 static Buffer * staticbuffer = [&](){
553 theBufferList().newInternalBuffer(tempfile.name().absFileName());
555 b->inset().setBuffer(*b);
556 //initialize staticbuffer with b
559 // Use a clone for the complicated stuff so that we do not need to clean
560 // up in order to avoid a crash.
561 Buffer * buffer = staticbuffer->cloneBufferOnly();
562 LASSERT(buffer, return 0);
564 // This needs doing every time.
565 // Since setDocumentClass() causes deletion of the old document class
566 // we need to reset all layout pointers in paragraphs (otherwise they
567 // would be dangling).
568 ParIterator const end = buffer->par_iterator_end();
569 for (ParIterator it = buffer->par_iterator_begin(); it != end; ++it) {
570 docstring const name = it->layout().name();
571 if (docclass->hasLayout(name))
572 it->setLayout((*docclass)[name]);
574 it->setPlainOrDefaultLayout(*docclass);
576 buffer->params().setDocumentClass(docclass);
578 // we will use pasteSelectionHelper to copy the paragraphs into the
579 // temporary Buffer, since it does a lot of things to fix them up.
580 DocIterator dit = doc_iterator_begin(buffer, &buffer->inset());
582 pasteSelectionHelper(dit, paragraphs, docclass, cap::BRANCH_ADD, el);
588 void putClipboard(ParagraphList const & paragraphs,
589 DocumentClassConstPtr docclass, docstring const & plaintext)
591 Buffer * buffer = copyToTempBuffer(paragraphs, docclass);
592 if (!buffer) // already asserted in copyToTempBuffer()
595 // We don't want to produce images that are not used. Therefore,
596 // output formulas as MathML. Even if this is not understood by all
597 // applications, the number that can parse it should go up in the future.
598 buffer->params().html_math_output = BufferParams::MathML;
600 // Make sure MarkAsExporting is deleted before buffer is
602 // The Buffer is being used to export. This is necessary so that the
603 // updateMacros call will record the needed information.
604 MarkAsExporting mex(buffer);
606 buffer->updateBuffer(Buffer::UpdateMaster, OutputUpdate);
607 buffer->updateMacros();
608 buffer->updateMacroInstances(OutputUpdate);
613 if (buffer->write(oslyx))
617 odocstringstream oshtml;
618 OutputParams runparams(encodings.fromLyXName("utf8"));
619 // We do not need to produce images, etc.
620 runparams.dryrun = true;
621 // We are not interested in errors (bug 8866)
622 runparams.silent = true;
623 buffer->writeLyXHTMLSource(oshtml, runparams, Buffer::FullSource);
625 theClipboard().put(lyx, oshtml.str(), plaintext);
633 /// return true if the whole ParagraphList is deleted
634 static bool isFullyDeleted(ParagraphList const & pars)
636 pit_type const pars_size = static_cast<pit_type>(pars.size());
638 // check all paragraphs
639 for (pit_type pit = 0; pit < pars_size; ++pit) {
640 if (!pars[pit].empty()) // prevent assertion failure
641 if (!pars[pit].isDeleted(0, pars[pit].size()))
648 void copySelectionHelper(Buffer const & buf, Text const & text,
649 pit_type startpit, pit_type endpit,
650 int start, int end, DocumentClassConstPtr dc, CutStack & cutstack)
652 ParagraphList const & pars = text.paragraphs();
654 // In most of these cases, we can try to recover.
655 LASSERT(0 <= start, start = 0);
656 LASSERT(start <= pars[startpit].size(), start = pars[startpit].size());
657 LASSERT(0 <= end, end = 0);
658 LASSERT(end <= pars[endpit].size(), end = pars[endpit].size());
659 LASSERT(startpit != endpit || start <= end, return);
661 // Clone the paragraphs within the selection.
662 ParagraphList copy_pars(lyx::next(pars.begin(), startpit),
663 lyx::next(pars.begin(), endpit + 1));
665 // Remove the end of the last paragraph; afterwards, remove the
666 // beginning of the first paragraph. Keep this order - there may only
667 // be one paragraph! Do not track deletions here; this is an internal
668 // action not visible to the user
670 Paragraph & back = copy_pars.back();
671 back.eraseChars(end, back.size(), false);
672 Paragraph & front = copy_pars.front();
673 front.eraseChars(0, start, false);
675 ParagraphList::iterator it = copy_pars.begin();
676 ParagraphList::iterator it_end = copy_pars.end();
678 for (; it != it_end; ++it) {
679 // Since we have a copy of the paragraphs, the insets
680 // do not have a proper buffer reference. It makes
681 // sense to add them temporarily, because the
682 // operations below depend on that (acceptChanges included).
683 it->setInsetBuffers(const_cast<Buffer &>(buf));
684 // PassThru paragraphs have the Language
685 // latex_language. This is invalid for others, so we
686 // need to change it to the buffer language.
687 if (it->isPassThru())
688 it->changeLanguage(buf.params(),
689 latex_language, buf.language());
692 // do not copy text (also nested in insets) which is marked as
693 // deleted, unless the whole selection was deleted
694 if (!isFullyDeleted(copy_pars))
695 acceptChanges(copy_pars, buf.params());
697 rejectChanges(copy_pars, buf.params());
700 // do some final cleanup now, to make sure that the paragraphs
701 // are not linked to something else.
702 it = copy_pars.begin();
703 for (; it != it_end; ++it) {
705 it->setInsetOwner(0);
708 cutstack.push(make_pair(copy_pars, dc));
716 void region(CursorSlice const & i1, CursorSlice const & i2,
717 Inset::row_type & r1, Inset::row_type & r2,
718 Inset::col_type & c1, Inset::col_type & c2)
720 Inset & p = i1.inset();
721 c1 = p.col(i1.idx());
722 c2 = p.col(i2.idx());
725 r1 = p.row(i1.idx());
726 r2 = p.row(i2.idx());
732 docstring grabAndEraseSelection(Cursor & cur)
734 if (!cur.selection())
736 docstring res = grabSelection(cur);
742 bool reduceSelectionToOneCell(CursorData & cur)
744 if (!cur.selection() || !cur.inMathed())
747 CursorSlice i1 = cur.selBegin();
748 CursorSlice i2 = cur.selEnd();
749 if (!i1.inset().asInsetMath())
752 // the easy case: do nothing if only one cell is selected
753 if (i1.idx() == i2.idx())
758 cur.top().pos() = cur.top().lastpos();
764 bool multipleCellsSelected(CursorData const & cur)
766 if (!cur.selection() || !cur.inMathed())
769 CursorSlice i1 = cur.selBegin();
770 CursorSlice i2 = cur.selEnd();
771 if (!i1.inset().asInsetMath())
774 if (i1.idx() == i2.idx())
781 void switchBetweenClasses(DocumentClassConstPtr oldone,
782 DocumentClassConstPtr newone, InsetText & in, ErrorList & errorlist)
786 LBUFERR(!in.paragraphs().empty());
787 if (oldone == newone)
790 DocumentClass const & oldtc = *oldone;
791 DocumentClass const & newtc = *newone;
794 ParIterator it = par_iterator_begin(in);
795 ParIterator end = par_iterator_end(in);
796 // for remembering which layouts we've had to add
797 set<docstring> newlayouts;
798 for (; it != end; ++it) {
799 docstring const name = it->layout().name();
801 // the pasted text will keep their own layout name. If this layout does
802 // not exist in the new document, it will behave like a standard layout.
803 bool const added_one = newtc.addLayoutIfNeeded(name);
805 newlayouts.insert(name);
807 if (added_one || newlayouts.find(name) != newlayouts.end()) {
809 docstring const s = bformat(_("Layout `%1$s' was not found."), name);
810 errorlist.push_back(ErrorItem(_("Layout Not Found"), s,
811 {it->id(), 0}, {it->id(), -1}));
814 if (in.usePlainLayout())
815 it->setLayout(newtc.plainLayout());
817 it->setLayout(newtc[name]);
820 // character styles and hidden table cells
821 InsetIterator const i_end = inset_iterator_end(in);
822 for (InsetIterator iit = inset_iterator_begin(in); iit != i_end; ++iit) {
823 InsetCode const code = iit->lyxCode();
824 if (code == FLEX_CODE) {
825 // FIXME: Should we verify all InsetCollapsible?
826 docstring const layoutName = iit->layoutName();
827 docstring const & n = newone->insetLayout(layoutName).name();
828 bool const is_undefined = n.empty() ||
829 n == DocumentClass::plainInsetLayout().name();
833 // The flex inset is undefined in newtc
834 docstring const oldname = from_utf8(oldtc.name());
835 docstring const newname = from_utf8(newtc.name());
837 if (oldname == newname)
838 s = bformat(_("Flex inset %1$s is undefined after "
839 "reloading `%2$s' layout."), layoutName, oldname);
841 s = bformat(_("Flex inset %1$s is undefined because of "
842 "conversion from `%2$s' layout to `%3$s'."),
843 layoutName, oldname, newname);
844 // To warn the user that something had to be done.
845 errorlist.push_back(ErrorItem(
846 _("Undefined flex inset"), s,
847 {iit.paragraph().id(), iit.pos()},
848 {iit.paragraph().id(), iit.pos() + 1}));
849 } else if (code == TABULAR_CODE) {
850 // The recursion above does not catch paragraphs in "hidden" cells,
851 // i.e., ones that are part of a multirow or multicolum. So we need
852 // to handle those separately.
853 // This is the cause of bug #9049.
854 InsetTabular * table = iit->asInsetTabular();
855 table->setLayoutForHiddenCells(newtc);
861 vector<docstring> availableSelections(Buffer const * buf)
863 vector<docstring> selList;
867 CutStack::const_iterator cit = theCuts.begin();
868 CutStack::const_iterator end = theCuts.end();
869 for (; cit != end; ++cit) {
870 // we do not use cit-> here because gcc 2.9x does not
872 ParagraphList const & pars = (*cit).first;
874 ParagraphList::const_iterator pit = pars.begin();
875 ParagraphList::const_iterator pend = pars.end();
876 for (; pit != pend; ++pit) {
877 Paragraph par(*pit, 0, 46);
878 // adapt paragraph to current buffer.
879 par.setInsetBuffers(const_cast<Buffer &>(*buf));
880 textSel += par.asString(AS_STR_INSETS);
881 if (textSel.size() > 45) {
882 support::truncateWithEllipsis(textSel,45);
886 selList.push_back(textSel);
893 size_type numberOfSelections()
895 return theCuts.size();
900 void cutSelectionHelper(Cursor & cur, CutStack & cuts, bool doclear, bool realcut, bool putclip)
902 // This doesn't make sense, if there is no selection
903 if (!cur.selection())
906 // OK, we have a selection. This is always between cur.selBegin()
909 if (cur.inTexted()) {
910 Text * text = cur.text();
915 // make sure that the depth behind the selection are restored, too
916 cur.recordUndoSelection();
917 pit_type begpit = cur.selBegin().pit();
918 pit_type endpit = cur.selEnd().pit();
920 int endpos = cur.selEnd().pos();
922 BufferParams const & bp = cur.buffer()->params();
924 copySelectionHelper(*cur.buffer(),
927 cur.selBegin().pos(), endpos,
928 bp.documentClassPtr(), cuts);
929 // Stuff what we got on the clipboard.
930 // Even if there is no selection.
932 putClipboard(cuts[0].first, cuts[0].second,
933 cur.selectionAsString(true));
936 if (begpit != endpit)
937 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
939 tie(endpit, endpos) =
940 eraseSelectionHelper(bp, text->paragraphs(), begpit, endpit,
941 cur.selBegin().pos(), endpos);
943 // cutSelection can invalidate the cursor so we need to set
945 // we prefer the end for when tracking changes
949 // sometimes necessary
951 && text->paragraphs()[begpit].stripLeadingSpaces(bp.track_changes))
954 // need a valid cursor. (Lgb)
955 cur.clearSelection();
957 // After a cut operation, we must make sure that the Buffer is updated
958 // because some further operation might need updated label information for
959 // example. So we cannot just use "cur.forceBufferUpdate()" here.
961 cur.buffer()->updateBuffer();
963 // tell tabular that a recent copy happened
964 dirtyTabularStack(false);
967 if (cur.inMathed()) {
968 if (cur.selBegin().idx() != cur.selEnd().idx()) {
969 // The current selection spans more than one cell.
971 cur.recordUndoInset();
973 // Record only the current cell to avoid a jumping
985 void cutSelection(Cursor & cur, bool doclear, bool realcut)
987 cutSelectionHelper(cur, theCuts, doclear, realcut, true);
991 void cutSelectionToTemp(Cursor & cur, bool doclear, bool realcut)
993 cutSelectionHelper(cur, tempCut, doclear, realcut, false);
997 void copySelection(Cursor const & cur)
999 copySelection(cur, cur.selectionAsString(true));
1003 void copyInset(Cursor const & cur, Inset * inset, docstring const & plaintext)
1007 BufferParams const & bp = cur.buffer()->params();
1008 par.setLayout(bp.documentClass().plainLayout());
1009 Font font(inherit_font, bp.language);
1010 par.insertInset(0, inset, font, Change(Change::UNCHANGED));
1011 pars.push_back(par);
1012 theCuts.push(make_pair(pars, bp.documentClassPtr()));
1014 // stuff the selection onto the X clipboard, from an explicit copy request
1015 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
1021 void copySelectionToStack(CursorData const & cur, CutStack & cutstack)
1023 // this doesn't make sense, if there is no selection
1024 if (!cur.selection())
1027 // copySelection can not yet handle the case of cross idx selection
1028 if (cur.selBegin().idx() != cur.selEnd().idx())
1031 if (cur.inTexted()) {
1032 Text * text = cur.text();
1034 // ok we have a selection. This is always between cur.selBegin()
1035 // and sel_end cursor
1036 copySelectionHelper(*cur.buffer(), *text,
1037 cur.selBegin().pit(), cur.selEnd().pit(),
1038 cur.selBegin().pos(), cur.selEnd().pos(),
1039 cur.buffer()->params().documentClassPtr(),
1041 // Reset the dirty_tabular_stack_ flag only when something
1042 // is copied to the clipboard (not to the selectionBuffer).
1043 if (&cutstack == &theCuts)
1044 dirtyTabularStack(false);
1047 if (cur.inMathed()) {
1048 //lyxerr << "copySelection in mathed" << endl;
1051 BufferParams const & bp = cur.buffer()->params();
1052 // FIXME This should be the plain layout...right?
1053 par.setLayout(bp.documentClass().plainLayout());
1054 // For pasting into text, we set the language to the paragraph language
1055 // (rather than the default_language which is always English; see #2596)
1056 par.insert(0, grabSelection(cur), Font(sane_font, par.getParLanguage(bp)),
1057 Change(Change::UNCHANGED));
1058 pars.push_back(par);
1059 cutstack.push(make_pair(pars, bp.documentClassPtr()));
1066 void copySelectionToStack()
1068 if (!selectionBuffer.empty())
1069 theCuts.push(selectionBuffer[0]);
1073 void copySelection(Cursor const & cur, docstring const & plaintext)
1075 // In tablemode, because copy and paste actually use special table stack
1076 // we do not attempt to get selected paragraphs under cursor. Instead, a
1077 // paragraph with the plain text version is generated so that table cells
1078 // can be pasted as pure text somewhere else.
1079 if (cur.selBegin().idx() != cur.selEnd().idx()) {
1082 BufferParams const & bp = cur.buffer()->params();
1083 par.setLayout(bp.documentClass().plainLayout());
1084 par.insert(0, plaintext, Font(), Change(Change::UNCHANGED));
1085 pars.push_back(par);
1086 theCuts.push(make_pair(pars, bp.documentClassPtr()));
1088 copySelectionToStack(cur, theCuts);
1091 // stuff the selection onto the X clipboard, from an explicit copy request
1092 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
1096 void saveSelection(Cursor const & cur)
1098 // This function is called, not when a selection is formed, but when
1099 // a selection is cleared. Therefore, multiple keyboard selection
1100 // will not repeatively trigger this function (bug 3877).
1102 && cur.selBegin() == cur.bv().cursor().selBegin()
1103 && cur.selEnd() == cur.bv().cursor().selEnd()) {
1104 LYXERR(Debug::SELECTION, "saveSelection: '" << cur.selectionAsString(true) << "'");
1105 copySelectionToStack(cur, selectionBuffer);
1112 return !selectionBuffer.empty();
1116 void clearSelection()
1118 selectionBuffer.clear();
1122 void clearCutStack()
1129 docstring selection(size_t sel_index, DocumentClassConstPtr docclass)
1131 if (sel_index >= theCuts.size())
1134 unique_ptr<Buffer> buffer(copyToTempBuffer(theCuts[sel_index].first,
1139 return buffer->paragraphs().back().asString(AS_STR_INSETS | AS_STR_NEWLINES);
1143 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
1144 DocumentClassConstPtr docclass, ErrorList & errorList,
1145 cap::BranchAction branchAction)
1147 if (cur.inTexted()) {
1148 Text * text = cur.text();
1151 PasteReturnValue prv =
1152 pasteSelectionHelper(cur, parlist, docclass, branchAction, errorList);
1153 cur.forceBufferUpdate();
1154 cur.clearSelection();
1155 text->setCursor(cur, prv.pit, prv.pos);
1158 // mathed is handled in InsetMathNest/InsetMathGrid
1159 LATTEST(!cur.inMathed());
1163 bool pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
1165 // this does not make sense, if there is nothing to paste
1166 if (!checkPastePossible(sel_index))
1170 pasteParagraphList(cur, theCuts[sel_index].first,
1171 theCuts[sel_index].second, errorList, BRANCH_ASK);
1176 bool pasteFromTemp(Cursor & cur, ErrorList & errorList)
1178 // this does not make sense, if there is nothing to paste
1179 if (tempCut.empty() || tempCut[0].first.empty())
1183 pasteParagraphList(cur, tempCut[0].first,
1184 tempCut[0].second, errorList, BRANCH_IGNORE);
1189 bool pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs,
1190 Clipboard::TextType type)
1192 // Use internal clipboard if it is the most recent one
1193 // This overrides asParagraphs and type on purpose!
1194 if (theClipboard().isInternal())
1195 return pasteFromStack(cur, errorList, 0);
1197 // First try LyX format
1198 if ((type == Clipboard::LyXTextType ||
1199 type == Clipboard::LyXOrPlainTextType ||
1200 type == Clipboard::AnyTextType) &&
1201 theClipboard().hasTextContents(Clipboard::LyXTextType)) {
1202 string lyx = theClipboard().getAsLyX();
1204 // For some strange reason gcc 3.2 and 3.3 do not accept
1205 // Buffer buffer(string(), false);
1206 Buffer buffer("", false);
1207 buffer.setUnnamed(true);
1208 if (buffer.readString(lyx)) {
1210 pasteParagraphList(cur, buffer.paragraphs(),
1211 buffer.params().documentClassPtr(), errorList);
1217 // Then try TeX and HTML
1218 Clipboard::TextType types[2] = {Clipboard::HtmlTextType, Clipboard::LaTeXTextType};
1219 string names[2] = {"html", "latexclipboard"};
1220 for (int i = 0; i < 2; ++i) {
1221 if (type != types[i] && type != Clipboard::AnyTextType)
1223 bool available = theClipboard().hasTextContents(types[i]);
1225 // If a specific type was explicitly requested, try to
1226 // interpret plain text: The user told us that the clipboard
1227 // contents is in the desired format
1228 if (!available && type == types[i]) {
1229 types[i] = Clipboard::PlainTextType;
1230 available = theClipboard().hasTextContents(types[i]);
1234 docstring text = theClipboard().getAsText(types[i]);
1235 available = !text.empty();
1237 // For some strange reason gcc 3.2 and 3.3 do not accept
1238 // Buffer buffer(string(), false);
1239 Buffer buffer("", false);
1240 buffer.setUnnamed(true);
1241 available = buffer.importString(names[i], text, errorList);
1243 available = !buffer.paragraphs().empty();
1244 if (available && !buffer.paragraphs()[0].empty()) {
1245 // TeX2lyx (also used in the HTML chain) assumes English as document language
1246 // if no language is explicitly set (as is the case here).
1247 // We thus reset the temp buffer's language to the context language
1248 buffer.changeLanguage(buffer.language(), cur.getFont().language());
1250 pasteParagraphList(cur, buffer.paragraphs(),
1251 buffer.params().documentClassPtr(), errorList);
1258 // Then try plain text
1259 docstring const text = theClipboard().getAsText(Clipboard::PlainTextType);
1264 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1266 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1267 cur.forceBufferUpdate();
1272 void pasteSimpleText(Cursor & cur, bool asParagraphs)
1275 // Use internal clipboard if it is the most recent one
1276 if (theClipboard().isInternal()) {
1277 if (!checkPastePossible(0))
1280 ParagraphList const & pars = theCuts[0].first;
1281 ParagraphList::const_iterator it = pars.begin();
1282 for (; it != pars.end(); ++it) {
1283 if (it != pars.begin())
1285 text += (*it).asString();
1287 asParagraphs = false;
1289 // Then try plain text
1290 text = theClipboard().getAsText(Clipboard::PlainTextType);
1297 cutSelection(cur, true, false);
1299 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1301 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1305 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
1306 Clipboard::GraphicsType preferedType)
1308 LASSERT(theClipboard().hasGraphicsContents(preferedType), return);
1310 // get picture from clipboard
1311 FileName filename = theClipboard().getAsGraphics(cur, preferedType);
1312 if (filename.empty())
1315 // create inset for graphic
1316 InsetGraphics * inset = new InsetGraphics(cur.buffer());
1317 InsetGraphicsParams params;
1318 params.filename = support::DocFileName(filename.absFileName(), false);
1319 inset->setParams(params);
1325 void pasteSelection(Cursor & cur, ErrorList & errorList)
1327 if (selectionBuffer.empty())
1330 pasteParagraphList(cur, selectionBuffer[0].first,
1331 selectionBuffer[0].second, errorList);
1335 void replaceSelectionWithString(Cursor & cur, docstring const & str)
1338 DocIterator selbeg = cur.selectionBegin();
1340 // Get font setting before we cut, we need a copy here, not a bare reference.
1342 selbeg.paragraph().getFontSettings(cur.buffer()->params(), selbeg.pos());
1344 // Insert the new string
1345 pos_type pos = cur.selEnd().pos();
1346 Paragraph & par = cur.selEnd().paragraph();
1347 docstring::const_iterator cit = str.begin();
1348 docstring::const_iterator end = str.end();
1349 for (; cit != end; ++cit, ++pos)
1350 par.insertChar(pos, *cit, font, cur.buffer()->params().track_changes);
1352 // Cut the selection
1353 cutSelection(cur, true, false);
1357 void replaceSelection(Cursor & cur)
1359 if (cur.selection())
1360 cutSelection(cur, true, false);
1364 void eraseSelection(Cursor & cur)
1366 //lyxerr << "cap::eraseSelection begin: " << cur << endl;
1367 CursorSlice const & i1 = cur.selBegin();
1368 CursorSlice const & i2 = cur.selEnd();
1369 if (!i1.asInsetMath()) {
1370 LYXERR0("Can't erase this selection");
1376 InsetMath * p = i1.asInsetMath();
1377 if (i1.idx() == i2.idx()) {
1378 i1.cell().erase(i1.pos(), i2.pos());
1379 // We may have deleted i1.cell(cur.pos()).
1380 // Make sure that pos is valid.
1381 if (cur.pos() > cur.lastpos())
1382 cur.pos() = cur.lastpos();
1383 } else if (p->nrows() > 0 && p->ncols() > 0) {
1384 // This is a grid, delete a nice square region
1385 Inset::row_type r1, r2;
1386 Inset::col_type c1, c2;
1387 region(i1, i2, r1, r2, c1, c2);
1388 for (Inset::row_type row = r1; row <= r2; ++row)
1389 for (Inset::col_type col = c1; col <= c2; ++col)
1390 p->cell(p->index(row, col)).clear();
1391 // We've deleted the whole cell. Only pos 0 is valid.
1394 Inset::idx_type idx1 = i1.idx();
1395 Inset::idx_type idx2 = i2.idx();
1398 for (Inset::idx_type idx = idx1 ; idx <= idx2; ++idx)
1399 p->cell(idx).clear();
1400 // We've deleted the whole cell. Only pos 0 is valid.
1404 // need a valid cursor. (Lgb)
1405 cur.clearSelection();
1406 //lyxerr << "cap::eraseSelection end: " << cur << endl;
1410 void selDel(Cursor & cur)
1412 //lyxerr << "cap::selDel" << endl;
1413 if (cur.selection())
1414 eraseSelection(cur);
1418 void selClearOrDel(Cursor & cur)
1420 //lyxerr << "cap::selClearOrDel" << endl;
1421 if (lyxrc.auto_region_delete)
1424 cur.selection(false);
1428 docstring grabSelection(CursorData const & cur)
1430 if (!cur.selection())
1434 // grab selection by glueing multiple cells together. This is not what
1435 // we want because selections spanning multiple cells will get "&" and "\\"
1438 for (DocIterator dit = cur.selectionBegin();
1439 dit != cur.selectionEnd(); dit.forwardPos())
1440 os << asString(dit.cell());
1444 CursorSlice i1 = cur.selBegin();
1445 CursorSlice i2 = cur.selEnd();
1447 if (i1.idx() == i2.idx()) {
1448 if (i1.inset().asInsetMath()) {
1449 MathData::const_iterator it = i1.cell().begin();
1450 Buffer * buf = cur.buffer();
1451 return asString(MathData(buf, it + i1.pos(), it + i2.pos()));
1453 return from_ascii("unknown selection 1");
1457 Inset::row_type r1, r2;
1458 Inset::col_type c1, c2;
1459 region(i1, i2, r1, r2, c1, c2);
1462 if (i1.inset().asInsetMath()) {
1463 for (Inset::row_type row = r1; row <= r2; ++row) {
1466 for (Inset::col_type col = c1; col <= c2; ++col) {
1469 data += asString(i1.asInsetMath()->
1470 cell(i1.asInsetMath()->index(row, col)));
1474 data = from_ascii("unknown selection 2");
1480 void dirtyTabularStack(bool b)
1482 dirty_tabular_stack_ = b;
1486 bool tabularStackDirty()
1488 return dirty_tabular_stack_;