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 // Merge paragraphs that are to be pasted into a text inset
146 // that does not allow multiple pars.
147 InsetText * inset_text = target_inset->asInsetText();
148 if (inset_text && !inset_text->allowMultiPar()) {
149 while (insertion.size() > 1)
150 mergeParagraph(buffer.params(), insertion, 0);
153 // Convert newline to paragraph break in ParbreakIsNewline
154 if (target_inset->getLayout().parbreakIsNewline()
155 || pars[pit].layout().parbreak_is_newline) {
156 for (size_t i = 0; i != insertion.size(); ++i) {
157 for (pos_type j = 0; j != insertion[i].size(); ++j) {
158 if (insertion[i].isNewline(j)) {
159 // do not track deletion of newline
160 insertion[i].eraseChar(j, false);
161 insertion[i].setInsetOwner(target_inset);
162 breakParagraphConservative(
171 // Prevent to paste uncodable characters in verbatim and ERT.
172 // The encoding is inherited from the context here.
173 docstring uncodable_content;
174 if (target_inset->getLayout().isPassThru() && cur.getEncoding()) {
175 odocstringstream res;
176 Encoding const * e = cur.getEncoding();
177 for (size_t i = 0; i != insertion.size(); ++i) {
178 pos_type end = insertion[i].size();
179 for (pos_type j = 0; j != end; ++j) {
181 if (insertion[i].isInset(j))
183 char_type const c = insertion[i].getChar(j);
184 if (!e->encodable(c)) {
185 // do not track deletion
187 insertion[i].eraseChar(j, false);
193 docstring const uncodable = res.str();
194 if (!uncodable.empty()) {
195 if (uncodable.size() == 1)
196 uncodable_content = bformat(_("The character \"%1$s\" is uncodable in this verbatim context "
197 "and thus has not been pasted."),
200 uncodable_content = bformat(_("The characters \"%1$s\" are uncodable in this verbatim context "
201 "and thus have not been pasted."),
206 // set the paragraphs to plain layout if necessary
207 DocumentClassConstPtr newDocClass = buffer.params().documentClassPtr();
208 if (cur.inset().usePlainLayout()) {
209 bool forcePlainLayout = target_inset->forcePlainLayout();
210 Layout const & plainLayout = newDocClass->plainLayout();
211 Layout const & defaultLayout = newDocClass->defaultLayout();
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 (forcePlainLayout || parLayout == defaultLayout)
217 par->setLayout(plainLayout);
220 // check if we need to reset from plain layout
221 Layout const & defaultLayout = newDocClass->defaultLayout();
222 Layout const & plainLayout = newDocClass->plainLayout();
223 ParagraphList::iterator const end = insertion.end();
224 ParagraphList::iterator par = insertion.begin();
225 for (; par != end; ++par) {
226 Layout const & parLayout = par->layout();
227 if (parLayout == plainLayout)
228 par->setLayout(defaultLayout);
232 InsetText in(cur.buffer());
233 // Make sure there is no class difference.
234 in.paragraphs().clear();
235 // This works without copying any paragraph data because we have
236 // a specialized swap method for ParagraphList. This is important
237 // since we store pointers to insets at some places and we don't
238 // want to invalidate them.
239 insertion.swap(in.paragraphs());
240 cap::switchBetweenClasses(oldDocClass, newDocClass, in, errorlist);
241 // Do this here since switchBetweenClasses clears the errorlist
242 if (!uncodable_content.empty())
243 errorlist.push_back(ErrorItem(_("Uncodable content"), uncodable_content));
244 insertion.swap(in.paragraphs());
246 ParagraphList::iterator tmpbuf = insertion.begin();
247 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
249 depth_type max_depth = pars[pit].getMaxDepthAfter();
251 for (; tmpbuf != insertion.end(); ++tmpbuf) {
252 // If we have a negative jump so that the depth would
253 // go below 0 depth then we have to redo the delta to
254 // this new max depth level so that subsequent
255 // paragraphs are aligned correctly to this paragraph
257 if (int(tmpbuf->params().depth()) + depth_delta < 0)
260 // Set the right depth so that we are not too deep or shallow.
261 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
262 if (tmpbuf->params().depth() > max_depth)
263 tmpbuf->params().depth(max_depth);
265 // Set max_depth for the next paragraph
266 max_depth = tmpbuf->getMaxDepthAfter();
268 // Set the inset owner of this paragraph.
269 tmpbuf->setInsetOwner(target_inset);
270 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
271 // do not track deletion of invalid insets
272 if (Inset * inset = tmpbuf->getInset(i))
273 if (!target_inset->insetAllowed(inset->lyxCode()))
274 tmpbuf->eraseChar(i--, false);
277 tmpbuf->setChange(Change(buffer.params().track_changes ?
278 Change::INSERTED : Change::UNCHANGED));
281 bool const empty = pars[pit].empty();
283 // Make the buf exactly the same layout as the cursor
285 insertion.begin()->makeSameLayout(pars[pit]);
288 // Prepare the paragraphs and insets for insertion.
289 insertion.swap(in.paragraphs());
291 InsetIterator const i_end = inset_iterator_end(in);
292 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
293 // Even though this will also be done later, it has to be done here
294 // since some inset might going to try to access
295 // the buffer() member.
296 it->setBuffer(const_cast<Buffer &>(buffer));
297 switch (it->lyxCode()) {
299 case MATH_HULL_CODE: {
300 // check for equation labels and resolve duplicates
301 InsetMathHull * ins = it->asInsetMath()->asHullInset();
302 std::vector<InsetLabel *> labels = ins->getLabels();
303 for (size_t i = 0; i != labels.size(); ++i) {
306 InsetLabel * lab = labels[i];
307 docstring const oldname = lab->getParam("name");
308 lab->updateLabel(oldname);
309 // We need to update the buffer reference cache.
311 docstring const newname = lab->getParam("name");
312 if (oldname == newname)
314 // adapt the references
315 for (InsetIterator itt = inset_iterator_begin(in);
316 itt != i_end; ++itt) {
317 if (itt->lyxCode() == REF_CODE) {
318 InsetCommand * ref = itt->asInsetCommand();
319 if (ref->getParam("reference") == oldname)
320 ref->setParam("reference", newname);
321 } else if (itt->lyxCode() == MATH_REF_CODE) {
322 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
323 // this is necessary to prevent an uninitialized
324 // buffer when the RefInset is in a MathBox.
325 // FIXME audit setBuffer calls
326 mi->setBuffer(const_cast<Buffer &>(buffer));
327 if (mi->getTarget() == oldname)
328 mi->changeTarget(newname);
336 // check for duplicates
337 InsetLabel & lab = static_cast<InsetLabel &>(*it);
338 docstring const oldname = lab.getParam("name");
339 lab.updateLabel(oldname);
340 // We need to update the buffer reference cache.
342 docstring const newname = lab.getParam("name");
343 if (oldname == newname)
345 // adapt the references
346 for (InsetIterator itt = inset_iterator_begin(in); itt != i_end; ++itt) {
347 if (itt->lyxCode() == REF_CODE) {
348 InsetCommand & ref = static_cast<InsetCommand &>(*itt);
349 if (ref.getParam("reference") == oldname)
350 ref.setParam("reference", newname);
351 } else if (itt->lyxCode() == MATH_REF_CODE) {
352 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
353 // this is necessary to prevent an uninitialized
354 // buffer when the RefInset is in a MathBox.
355 // FIXME audit setBuffer calls
356 mi->setBuffer(const_cast<Buffer &>(buffer));
357 if (mi->getTarget() == oldname)
358 mi->changeTarget(newname);
365 InsetInclude & inc = static_cast<InsetInclude &>(*it);
367 // We need to update the list of included files.
373 InsetCitation & cit = static_cast<InsetCitation &>(*it);
374 // This actually only needs to be done if the cite engine
375 // differs, but we do it in general.
377 // We need to update the list of citations.
383 // check for duplicates
384 InsetBibitem & bib = static_cast<InsetBibitem &>(*it);
385 docstring const oldkey = bib.getParam("key");
386 bib.updateCommand(oldkey, false);
387 // We need to update the buffer reference cache.
389 docstring const newkey = bib.getParam("key");
390 if (oldkey == newkey)
392 // adapt the references
393 for (InsetIterator itt = inset_iterator_begin(in);
394 itt != i_end; ++itt) {
395 if (itt->lyxCode() == CITE_CODE) {
396 InsetCommand * ref = itt->asInsetCommand();
397 if (ref->getParam("key") == oldkey)
398 ref->setParam("key", newkey);
405 // check if branch is known to target buffer
407 InsetBranch & br = static_cast<InsetBranch &>(*it);
408 docstring const name = br.branch();
411 bool const is_child = (&buffer != buffer.masterBuffer());
412 BranchList branchlist = buffer.params().branchlist();
413 if ((!is_child && branchlist.find(name))
414 || (is_child && (branchlist.find(name)
415 || buffer.masterBuffer()->params().branchlist().find(name))))
417 switch(branchAction) {
418 case cap::BRANCH_ADD: {
419 // This is for a temporary buffer, so simply create the branch.
420 // Must not use lyx::dispatch(), since tmpbuffer has no view.
422 const_cast<Buffer&>(buffer).dispatch(FuncRequest(LFUN_BRANCH_ADD, name), dr);
425 case cap::BRANCH_ASK: {
426 docstring text = bformat(
427 _("The pasted branch \"%1$s\" is undefined.\n"
428 "Do you want to add it to the document's branch list?"),
430 if (frontend::Alert::prompt(_("Unknown branch"),
431 text, 0, 1, _("&Add"), _("&Don't Add")) != 0)
433 lyx::dispatch(FuncRequest(LFUN_BRANCH_ADD, name));
436 case cap::BRANCH_IGNORE:
439 // We need to update the list of branches.
448 insertion.swap(in.paragraphs());
450 // Split the paragraph for inserting the buf if necessary.
452 breakParagraphConservative(buffer.params(), pars, pit, pos);
456 pars.insert(lyx::next(pars.begin(), pit),
460 // merge the empty par with the last par of the insertion
461 mergeParagraph(buffer.params(), pars,
462 pit + insertion.size() - 1);
464 pars.insert(lyx::next(pars.begin(), pit + 1),
468 // merge the first par of the insertion with the current par
469 mergeParagraph(buffer.params(), pars, pit);
472 // Store the new cursor position.
473 pit_type last_paste = pit + insertion.size() - 1;
474 pit_type startpit = pit;
476 pos = pars[last_paste].size();
478 // FIXME Should we do it here, or should we let updateBuffer() do it?
479 // Set paragraph buffers. It's important to do this right away
480 // before something calls Inset::buffer() and causes a crash.
481 for (pit_type p = startpit; p <= pit; ++p)
482 pars[p].setInsetBuffers(const_cast<Buffer &>(buffer));
484 // Join (conditionally) last pasted paragraph with next one, i.e.,
485 // the tail of the spliced document paragraph
486 if (!empty && last_paste + 1 != pit_type(pars.size())) {
487 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
488 mergeParagraph(buffer.params(), pars, last_paste);
489 } else if (pars[last_paste + 1].empty()) {
490 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
491 mergeParagraph(buffer.params(), pars, last_paste);
492 } else if (pars[last_paste].empty()) {
493 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
494 mergeParagraph(buffer.params(), pars, last_paste);
496 pars[last_paste + 1].stripLeadingSpaces(buffer.params().track_changes);
501 return PasteReturnValue(pit, pos, need_update);
505 PitPosPair eraseSelectionHelper(BufferParams const & params,
506 ParagraphList & pars,
507 pit_type startpit, pit_type endpit,
508 int startpos, int endpos)
510 // Start of selection is really invalid.
511 if (startpit == pit_type(pars.size()) ||
512 (startpos > pars[startpit].size()))
513 return PitPosPair(endpit, endpos);
515 // Start and end is inside same paragraph
516 if (endpit == pit_type(pars.size()) || startpit == endpit) {
517 endpos -= pars[startpit].eraseChars(startpos, endpos, params.track_changes);
518 return PitPosPair(endpit, endpos);
521 for (pit_type pit = startpit; pit != endpit + 1;) {
522 pos_type const left = (pit == startpit ? startpos : 0);
523 pos_type right = (pit == endpit ? endpos : pars[pit].size() + 1);
524 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.track_changes);
526 // Logically erase only, including the end-of-paragraph character
527 pars[pit].eraseChars(left, right, params.track_changes);
529 // Separate handling of paragraph break:
530 if (merge && pit != endpit &&
532 || pars[pit].hasSameLayout(pars[endpit])
533 || pars[endpit].size() == endpos)) {
534 if (pit + 1 == endpit)
535 endpos += pars[pit].size();
536 mergeParagraph(params, pars, pit);
542 // Ensure legal cursor pos:
545 return PitPosPair(endpit, endpos);
549 Buffer * copyToTempBuffer(ParagraphList const & paragraphs, DocumentClassConstPtr docclass)
551 // This used to need to be static to avoid a memory leak. It no longer needs
552 // to be so, but the alternative is to construct a new one of these (with a
553 // new temporary directory, etc) every time, and then to destroy it. So maybe
554 // it's worth just keeping this one around.
555 static TempFile tempfile("clipboard.internal");
556 tempfile.setAutoRemove(false);
557 // The initialization of staticbuffer is thread-safe. Using a lambda
558 // guarantees that the properties are set only once.
559 static Buffer * staticbuffer = [&](){
561 theBufferList().newInternalBuffer(tempfile.name().absFileName());
563 b->inset().setBuffer(*b);
564 //initialize staticbuffer with b
567 // Use a clone for the complicated stuff so that we do not need to clean
568 // up in order to avoid a crash.
569 Buffer * buffer = staticbuffer->cloneBufferOnly();
570 LASSERT(buffer, return 0);
572 // This needs doing every time.
573 // Since setDocumentClass() causes deletion of the old document class
574 // we need to reset all layout pointers in paragraphs (otherwise they
575 // would be dangling).
576 ParIterator const end = buffer->par_iterator_end();
577 for (ParIterator it = buffer->par_iterator_begin(); it != end; ++it) {
578 docstring const name = it->layout().name();
579 if (docclass->hasLayout(name))
580 it->setLayout((*docclass)[name]);
582 it->setPlainOrDefaultLayout(*docclass);
584 buffer->params().setDocumentClass(docclass);
586 // we will use pasteSelectionHelper to copy the paragraphs into the
587 // temporary Buffer, since it does a lot of things to fix them up.
588 DocIterator dit = doc_iterator_begin(buffer, &buffer->inset());
590 pasteSelectionHelper(dit, paragraphs, docclass, cap::BRANCH_ADD, el);
596 void putClipboard(ParagraphList const & paragraphs,
597 DocumentClassConstPtr docclass, docstring const & plaintext)
599 Buffer * buffer = copyToTempBuffer(paragraphs, docclass);
600 if (!buffer) // already asserted in copyToTempBuffer()
603 // We don't want to produce images that are not used. Therefore,
604 // output formulas as MathML. Even if this is not understood by all
605 // applications, the number that can parse it should go up in the future.
606 buffer->params().html_math_output = BufferParams::MathML;
608 // Make sure MarkAsExporting is deleted before buffer is
610 // The Buffer is being used to export. This is necessary so that the
611 // updateMacros call will record the needed information.
612 MarkAsExporting mex(buffer);
614 buffer->updateBuffer(Buffer::UpdateMaster, OutputUpdate);
615 buffer->updateMacros();
616 buffer->updateMacroInstances(OutputUpdate);
621 if (buffer->write(oslyx))
625 odocstringstream oshtml;
626 OutputParams runparams(encodings.fromLyXName("utf8"));
627 // We do not need to produce images, etc.
628 runparams.dryrun = true;
629 // We are not interested in errors (bug 8866)
630 runparams.silent = true;
631 buffer->writeLyXHTMLSource(oshtml, runparams, Buffer::FullSource);
633 theClipboard().put(lyx, oshtml.str(), plaintext);
641 /// return true if the whole ParagraphList is deleted
642 static bool isFullyDeleted(ParagraphList const & pars)
644 pit_type const pars_size = static_cast<pit_type>(pars.size());
646 // check all paragraphs
647 for (pit_type pit = 0; pit < pars_size; ++pit) {
648 if (!pars[pit].empty()) // prevent assertion failure
649 if (!pars[pit].isDeleted(0, pars[pit].size()))
656 void copySelectionHelper(Buffer const & buf, Text const & text,
657 pit_type startpit, pit_type endpit,
658 int start, int end, DocumentClassConstPtr dc, CutStack & cutstack)
660 ParagraphList const & pars = text.paragraphs();
662 // In most of these cases, we can try to recover.
663 LASSERT(0 <= start, start = 0);
664 LASSERT(start <= pars[startpit].size(), start = pars[startpit].size());
665 LASSERT(0 <= end, end = 0);
666 LASSERT(end <= pars[endpit].size(), end = pars[endpit].size());
667 LASSERT(startpit != endpit || start <= end, return);
669 // Clone the paragraphs within the selection.
670 ParagraphList copy_pars(lyx::next(pars.begin(), startpit),
671 lyx::next(pars.begin(), endpit + 1));
673 // Remove the end of the last paragraph; afterwards, remove the
674 // beginning of the first paragraph. Keep this order - there may only
675 // be one paragraph! Do not track deletions here; this is an internal
676 // action not visible to the user
678 Paragraph & back = copy_pars.back();
679 back.eraseChars(end, back.size(), false);
680 Paragraph & front = copy_pars.front();
681 front.eraseChars(0, start, false);
683 ParagraphList::iterator it = copy_pars.begin();
684 ParagraphList::iterator it_end = copy_pars.end();
686 for (; it != it_end; ++it) {
687 // Since we have a copy of the paragraphs, the insets
688 // do not have a proper buffer reference. It makes
689 // sense to add them temporarily, because the
690 // operations below depend on that (acceptChanges included).
691 it->setInsetBuffers(const_cast<Buffer &>(buf));
692 // PassThru paragraphs have the Language
693 // latex_language. This is invalid for others, so we
694 // need to change it to the buffer language.
695 if (it->isPassThru())
696 it->changeLanguage(buf.params(),
697 latex_language, buf.language());
700 // do not copy text (also nested in insets) which is marked as
701 // deleted, unless the whole selection was deleted
702 if (!isFullyDeleted(copy_pars))
703 acceptChanges(copy_pars, buf.params());
705 rejectChanges(copy_pars, buf.params());
708 // do some final cleanup now, to make sure that the paragraphs
709 // are not linked to something else.
710 it = copy_pars.begin();
711 for (; it != it_end; ++it) {
713 it->setInsetOwner(0);
716 cutstack.push(make_pair(copy_pars, dc));
724 void region(CursorSlice const & i1, CursorSlice const & i2,
725 Inset::row_type & r1, Inset::row_type & r2,
726 Inset::col_type & c1, Inset::col_type & c2)
728 Inset & p = i1.inset();
729 c1 = p.col(i1.idx());
730 c2 = p.col(i2.idx());
733 r1 = p.row(i1.idx());
734 r2 = p.row(i2.idx());
740 docstring grabAndEraseSelection(Cursor & cur)
742 if (!cur.selection())
744 docstring res = grabSelection(cur);
750 bool reduceSelectionToOneCell(CursorData & cur)
752 if (!cur.selection() || !cur.inMathed())
755 CursorSlice i1 = cur.selBegin();
756 CursorSlice i2 = cur.selEnd();
757 if (!i1.inset().asInsetMath())
760 // the easy case: do nothing if only one cell is selected
761 if (i1.idx() == i2.idx())
766 cur.top().pos() = cur.top().lastpos();
772 bool multipleCellsSelected(CursorData const & cur)
774 if (!cur.selection() || !cur.inMathed())
777 CursorSlice i1 = cur.selBegin();
778 CursorSlice i2 = cur.selEnd();
779 if (!i1.inset().asInsetMath())
782 if (i1.idx() == i2.idx())
789 void switchBetweenClasses(DocumentClassConstPtr oldone,
790 DocumentClassConstPtr newone, InsetText & in, ErrorList & errorlist)
794 LBUFERR(!in.paragraphs().empty());
795 if (oldone == newone)
798 DocumentClass const & oldtc = *oldone;
799 DocumentClass const & newtc = *newone;
802 ParIterator it = par_iterator_begin(in);
803 ParIterator end = par_iterator_end(in);
804 // for remembering which layouts we've had to add
805 set<docstring> newlayouts;
806 for (; it != end; ++it) {
807 docstring const name = it->layout().name();
809 // the pasted text will keep their own layout name. If this layout does
810 // not exist in the new document, it will behave like a standard layout.
811 bool const added_one = newtc.addLayoutIfNeeded(name);
813 newlayouts.insert(name);
815 if (added_one || newlayouts.find(name) != newlayouts.end()) {
817 docstring const s = bformat(_("Layout `%1$s' was not found."), name);
818 errorlist.push_back(ErrorItem(_("Layout Not Found"), s,
819 {it->id(), 0}, {it->id(), -1}));
822 if (in.usePlainLayout())
823 it->setLayout(newtc.plainLayout());
825 it->setLayout(newtc[name]);
828 // character styles and hidden table cells
829 InsetIterator const i_end = inset_iterator_end(in);
830 for (InsetIterator iit = inset_iterator_begin(in); iit != i_end; ++iit) {
831 InsetCode const code = iit->lyxCode();
832 if (code == FLEX_CODE) {
833 // FIXME: Should we verify all InsetCollapsible?
834 docstring const layoutName = iit->layoutName();
835 docstring const & n = newone->insetLayout(layoutName).name();
836 bool const is_undefined = n.empty() ||
837 n == DocumentClass::plainInsetLayout().name();
841 // The flex inset is undefined in newtc
842 docstring const oldname = from_utf8(oldtc.name());
843 docstring const newname = from_utf8(newtc.name());
845 if (oldname == newname)
846 s = bformat(_("Flex inset %1$s is undefined after "
847 "reloading `%2$s' layout."), layoutName, oldname);
849 s = bformat(_("Flex inset %1$s is undefined because of "
850 "conversion from `%2$s' layout to `%3$s'."),
851 layoutName, oldname, newname);
852 // To warn the user that something had to be done.
853 errorlist.push_back(ErrorItem(
854 _("Undefined flex inset"), s,
855 {iit.paragraph().id(), iit.pos()},
856 {iit.paragraph().id(), iit.pos() + 1}));
857 } else if (code == TABULAR_CODE) {
858 // The recursion above does not catch paragraphs in "hidden" cells,
859 // i.e., ones that are part of a multirow or multicolum. So we need
860 // to handle those separately.
861 // This is the cause of bug #9049.
862 InsetTabular * table = iit->asInsetTabular();
863 table->setLayoutForHiddenCells(newtc);
869 vector<docstring> availableSelections(Buffer const * buf)
871 vector<docstring> selList;
875 CutStack::const_iterator cit = theCuts.begin();
876 CutStack::const_iterator end = theCuts.end();
877 for (; cit != end; ++cit) {
878 // we do not use cit-> here because gcc 2.9x does not
880 ParagraphList const & pars = (*cit).first;
882 ParagraphList::const_iterator pit = pars.begin();
883 ParagraphList::const_iterator pend = pars.end();
884 for (; pit != pend; ++pit) {
885 Paragraph par(*pit, 0, 46);
886 // adapt paragraph to current buffer.
887 par.setInsetBuffers(const_cast<Buffer &>(*buf));
888 textSel += par.asString(AS_STR_INSETS);
889 if (textSel.size() > 45) {
890 support::truncateWithEllipsis(textSel,45);
894 selList.push_back(textSel);
901 size_type numberOfSelections()
903 return theCuts.size();
908 void cutSelectionHelper(Cursor & cur, CutStack & cuts, bool doclear, bool realcut, bool putclip)
910 // This doesn't make sense, if there is no selection
911 if (!cur.selection())
914 // OK, we have a selection. This is always between cur.selBegin()
917 if (cur.inTexted()) {
918 Text * text = cur.text();
923 // make sure that the depth behind the selection are restored, too
924 cur.recordUndoSelection();
925 pit_type begpit = cur.selBegin().pit();
926 pit_type endpit = cur.selEnd().pit();
928 int endpos = cur.selEnd().pos();
930 BufferParams const & bp = cur.buffer()->params();
932 copySelectionHelper(*cur.buffer(),
935 cur.selBegin().pos(), endpos,
936 bp.documentClassPtr(), cuts);
937 // Stuff what we got on the clipboard.
938 // Even if there is no selection.
940 putClipboard(cuts[0].first, cuts[0].second,
941 cur.selectionAsString(true));
944 if (begpit != endpit)
945 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
947 tie(endpit, endpos) =
948 eraseSelectionHelper(bp, text->paragraphs(), begpit, endpit,
949 cur.selBegin().pos(), endpos);
951 // cutSelection can invalidate the cursor so we need to set
953 // we prefer the end for when tracking changes
957 // sometimes necessary
959 && text->paragraphs()[begpit].stripLeadingSpaces(bp.track_changes))
962 // need a valid cursor. (Lgb)
963 cur.clearSelection();
965 // After a cut operation, we must make sure that the Buffer is updated
966 // because some further operation might need updated label information for
967 // example. So we cannot just use "cur.forceBufferUpdate()" here.
969 cur.buffer()->updateBuffer();
971 // tell tabular that a recent copy happened
972 dirtyTabularStack(false);
975 if (cur.inMathed()) {
976 if (cur.selBegin().idx() != cur.selEnd().idx()) {
977 // The current selection spans more than one cell.
979 cur.recordUndoInset();
981 // Record only the current cell to avoid a jumping
993 void cutSelection(Cursor & cur, bool doclear, bool realcut)
995 cutSelectionHelper(cur, theCuts, doclear, realcut, true);
999 void cutSelectionToTemp(Cursor & cur, bool doclear, bool realcut)
1001 cutSelectionHelper(cur, tempCut, doclear, realcut, false);
1005 void copySelection(Cursor const & cur)
1007 copySelection(cur, cur.selectionAsString(true));
1011 void copyInset(Cursor const & cur, Inset * inset, docstring const & plaintext)
1015 BufferParams const & bp = cur.buffer()->params();
1016 par.setLayout(bp.documentClass().plainLayout());
1017 Font font(inherit_font, bp.language);
1018 par.insertInset(0, inset, font, Change(Change::UNCHANGED));
1019 pars.push_back(par);
1020 theCuts.push(make_pair(pars, bp.documentClassPtr()));
1022 // stuff the selection onto the X clipboard, from an explicit copy request
1023 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
1029 void copySelectionToStack(CursorData const & cur, CutStack & cutstack)
1031 // this doesn't make sense, if there is no selection
1032 if (!cur.selection())
1035 // copySelection can not yet handle the case of cross idx selection
1036 if (cur.selBegin().idx() != cur.selEnd().idx())
1039 if (cur.inTexted()) {
1040 Text * text = cur.text();
1042 // ok we have a selection. This is always between cur.selBegin()
1043 // and sel_end cursor
1044 copySelectionHelper(*cur.buffer(), *text,
1045 cur.selBegin().pit(), cur.selEnd().pit(),
1046 cur.selBegin().pos(), cur.selEnd().pos(),
1047 cur.buffer()->params().documentClassPtr(),
1049 // Reset the dirty_tabular_stack_ flag only when something
1050 // is copied to the clipboard (not to the selectionBuffer).
1051 if (&cutstack == &theCuts)
1052 dirtyTabularStack(false);
1055 if (cur.inMathed()) {
1056 //lyxerr << "copySelection in mathed" << endl;
1059 BufferParams const & bp = cur.buffer()->params();
1060 // FIXME This should be the plain layout...right?
1061 par.setLayout(bp.documentClass().plainLayout());
1062 // For pasting into text, we set the language to the paragraph language
1063 // (rather than the default_language which is always English; see #2596)
1064 par.insert(0, grabSelection(cur), Font(sane_font, par.getParLanguage(bp)),
1065 Change(Change::UNCHANGED));
1066 pars.push_back(par);
1067 cutstack.push(make_pair(pars, bp.documentClassPtr()));
1074 void copySelectionToStack()
1076 if (!selectionBuffer.empty())
1077 theCuts.push(selectionBuffer[0]);
1081 void copySelectionToTemp(Cursor & cur)
1083 copySelectionToStack(cur, tempCut);
1087 void copySelection(Cursor const & cur, docstring const & plaintext)
1089 // In tablemode, because copy and paste actually use special table stack
1090 // we do not attempt to get selected paragraphs under cursor. Instead, a
1091 // paragraph with the plain text version is generated so that table cells
1092 // can be pasted as pure text somewhere else.
1093 if (cur.selBegin().idx() != cur.selEnd().idx()) {
1096 BufferParams const & bp = cur.buffer()->params();
1097 par.setLayout(bp.documentClass().plainLayout());
1098 par.insert(0, plaintext, Font(), Change(Change::UNCHANGED));
1099 pars.push_back(par);
1100 theCuts.push(make_pair(pars, bp.documentClassPtr()));
1102 copySelectionToStack(cur, theCuts);
1105 // stuff the selection onto the X clipboard, from an explicit copy request
1106 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
1110 void saveSelection(Cursor const & cur)
1112 // This function is called, not when a selection is formed, but when
1113 // a selection is cleared. Therefore, multiple keyboard selection
1114 // will not repeatively trigger this function (bug 3877).
1116 && cur.selBegin() == cur.bv().cursor().selBegin()
1117 && cur.selEnd() == cur.bv().cursor().selEnd()) {
1118 LYXERR(Debug::SELECTION, "saveSelection: '" << cur.selectionAsString(true) << "'");
1119 copySelectionToStack(cur, selectionBuffer);
1126 return !selectionBuffer.empty();
1130 void clearSelection()
1132 selectionBuffer.clear();
1136 void clearCutStack()
1143 docstring selection(size_t sel_index, DocumentClassConstPtr docclass)
1145 if (sel_index >= theCuts.size())
1148 unique_ptr<Buffer> buffer(copyToTempBuffer(theCuts[sel_index].first,
1153 return buffer->paragraphs().back().asString(AS_STR_INSETS | AS_STR_NEWLINES);
1157 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
1158 DocumentClassConstPtr docclass, ErrorList & errorList,
1159 cap::BranchAction branchAction)
1161 if (cur.inTexted()) {
1162 Text * text = cur.text();
1165 PasteReturnValue prv =
1166 pasteSelectionHelper(cur, parlist, docclass, branchAction, errorList);
1167 cur.forceBufferUpdate();
1168 cur.clearSelection();
1169 text->setCursor(cur, prv.pit, prv.pos);
1172 // mathed is handled in InsetMathNest/InsetMathGrid
1173 LATTEST(!cur.inMathed());
1177 bool pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
1179 // this does not make sense, if there is nothing to paste
1180 if (!checkPastePossible(sel_index))
1184 pasteParagraphList(cur, theCuts[sel_index].first,
1185 theCuts[sel_index].second, errorList, BRANCH_ASK);
1190 bool pasteFromTemp(Cursor & cur, ErrorList & errorList)
1192 // this does not make sense, if there is nothing to paste
1193 if (tempCut.empty() || tempCut[0].first.empty())
1197 pasteParagraphList(cur, tempCut[0].first,
1198 tempCut[0].second, errorList, BRANCH_IGNORE);
1203 bool pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs,
1204 Clipboard::TextType type)
1206 // Use internal clipboard if it is the most recent one
1207 // This overrides asParagraphs and type on purpose!
1208 if (theClipboard().isInternal())
1209 return pasteFromStack(cur, errorList, 0);
1211 // First try LyX format
1212 if ((type == Clipboard::LyXTextType ||
1213 type == Clipboard::LyXOrPlainTextType ||
1214 type == Clipboard::AnyTextType) &&
1215 theClipboard().hasTextContents(Clipboard::LyXTextType)) {
1216 string lyx = theClipboard().getAsLyX();
1218 // For some strange reason gcc 3.2 and 3.3 do not accept
1219 // Buffer buffer(string(), false);
1220 Buffer buffer("", false);
1221 buffer.setUnnamed(true);
1222 if (buffer.readString(lyx)) {
1224 pasteParagraphList(cur, buffer.paragraphs(),
1225 buffer.params().documentClassPtr(), errorList);
1231 // Then try TeX and HTML
1232 Clipboard::TextType types[2] = {Clipboard::HtmlTextType, Clipboard::LaTeXTextType};
1233 string names[2] = {"html", "latexclipboard"};
1234 for (int i = 0; i < 2; ++i) {
1235 if (type != types[i] && type != Clipboard::AnyTextType)
1237 bool available = theClipboard().hasTextContents(types[i]);
1239 // If a specific type was explicitly requested, try to
1240 // interpret plain text: The user told us that the clipboard
1241 // contents is in the desired format
1242 if (!available && type == types[i]) {
1243 types[i] = Clipboard::PlainTextType;
1244 available = theClipboard().hasTextContents(types[i]);
1248 docstring text = theClipboard().getAsText(types[i]);
1249 available = !text.empty();
1251 // For some strange reason gcc 3.2 and 3.3 do not accept
1252 // Buffer buffer(string(), false);
1253 Buffer buffer("", false);
1254 buffer.setUnnamed(true);
1255 available = buffer.importString(names[i], text, errorList);
1257 available = !buffer.paragraphs().empty();
1258 if (available && !buffer.paragraphs()[0].empty()) {
1259 // TeX2lyx (also used in the HTML chain) assumes English as document language
1260 // if no language is explicitly set (as is the case here).
1261 // We thus reset the temp buffer's language to the context language
1262 buffer.changeLanguage(buffer.language(), cur.getFont().language());
1264 pasteParagraphList(cur, buffer.paragraphs(),
1265 buffer.params().documentClassPtr(), errorList);
1272 // Then try plain text
1273 docstring const text = theClipboard().getAsText(Clipboard::PlainTextType);
1278 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1280 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1281 cur.forceBufferUpdate();
1286 void pasteSimpleText(Cursor & cur, bool asParagraphs)
1289 // Use internal clipboard if it is the most recent one
1290 if (theClipboard().isInternal()) {
1291 if (!checkPastePossible(0))
1294 ParagraphList const & pars = theCuts[0].first;
1295 ParagraphList::const_iterator it = pars.begin();
1296 for (; it != pars.end(); ++it) {
1297 if (it != pars.begin())
1299 text += (*it).asString();
1301 asParagraphs = false;
1303 // Then try plain text
1304 text = theClipboard().getAsText(Clipboard::PlainTextType);
1311 cutSelection(cur, true, false);
1313 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1315 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1319 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
1320 Clipboard::GraphicsType preferedType)
1322 LASSERT(theClipboard().hasGraphicsContents(preferedType), return);
1324 // get picture from clipboard
1325 FileName filename = theClipboard().getAsGraphics(cur, preferedType);
1326 if (filename.empty())
1329 // create inset for graphic
1330 InsetGraphics * inset = new InsetGraphics(cur.buffer());
1331 InsetGraphicsParams params;
1332 params.filename = support::DocFileName(filename.absFileName(), false);
1333 inset->setParams(params);
1339 void pasteSelection(Cursor & cur, ErrorList & errorList)
1341 if (selectionBuffer.empty())
1344 pasteParagraphList(cur, selectionBuffer[0].first,
1345 selectionBuffer[0].second, errorList);
1349 void replaceSelectionWithString(Cursor & cur, docstring const & str)
1352 DocIterator selbeg = cur.selectionBegin();
1354 // Get font setting before we cut, we need a copy here, not a bare reference.
1356 selbeg.paragraph().getFontSettings(cur.buffer()->params(), selbeg.pos());
1358 // Insert the new string
1359 pos_type pos = cur.selEnd().pos();
1360 Paragraph & par = cur.selEnd().paragraph();
1361 docstring::const_iterator cit = str.begin();
1362 docstring::const_iterator end = str.end();
1363 for (; cit != end; ++cit, ++pos)
1364 par.insertChar(pos, *cit, font, cur.buffer()->params().track_changes);
1366 // Cut the selection
1367 cutSelection(cur, true, false);
1371 void replaceSelection(Cursor & cur)
1373 if (cur.selection())
1374 cutSelection(cur, true, false);
1378 void eraseSelection(Cursor & cur)
1380 //lyxerr << "cap::eraseSelection begin: " << cur << endl;
1381 CursorSlice const & i1 = cur.selBegin();
1382 CursorSlice const & i2 = cur.selEnd();
1383 if (!i1.asInsetMath()) {
1384 LYXERR0("Can't erase this selection");
1390 InsetMath * p = i1.asInsetMath();
1391 if (i1.idx() == i2.idx()) {
1392 i1.cell().erase(i1.pos(), i2.pos());
1393 // We may have deleted i1.cell(cur.pos()).
1394 // Make sure that pos is valid.
1395 if (cur.pos() > cur.lastpos())
1396 cur.pos() = cur.lastpos();
1397 } else if (p->nrows() > 0 && p->ncols() > 0) {
1398 // This is a grid, delete a nice square region
1399 Inset::row_type r1, r2;
1400 Inset::col_type c1, c2;
1401 region(i1, i2, r1, r2, c1, c2);
1402 for (Inset::row_type row = r1; row <= r2; ++row)
1403 for (Inset::col_type col = c1; col <= c2; ++col)
1404 p->cell(p->index(row, col)).clear();
1405 // We've deleted the whole cell. Only pos 0 is valid.
1408 Inset::idx_type idx1 = i1.idx();
1409 Inset::idx_type idx2 = i2.idx();
1412 for (Inset::idx_type idx = idx1 ; idx <= idx2; ++idx)
1413 p->cell(idx).clear();
1414 // We've deleted the whole cell. Only pos 0 is valid.
1418 // need a valid cursor. (Lgb)
1419 cur.clearSelection();
1420 //lyxerr << "cap::eraseSelection end: " << cur << endl;
1424 void selDel(Cursor & cur)
1426 //lyxerr << "cap::selDel" << endl;
1427 if (cur.selection())
1428 eraseSelection(cur);
1432 void selClearOrDel(Cursor & cur)
1434 //lyxerr << "cap::selClearOrDel" << endl;
1435 if (lyxrc.auto_region_delete)
1438 cur.selection(false);
1442 docstring grabSelection(CursorData const & cur)
1444 if (!cur.selection())
1448 // grab selection by glueing multiple cells together. This is not what
1449 // we want because selections spanning multiple cells will get "&" and "\\"
1452 for (DocIterator dit = cur.selectionBegin();
1453 dit != cur.selectionEnd(); dit.forwardPos())
1454 os << asString(dit.cell());
1458 CursorSlice i1 = cur.selBegin();
1459 CursorSlice i2 = cur.selEnd();
1461 if (i1.idx() == i2.idx()) {
1462 if (i1.inset().asInsetMath()) {
1463 MathData::const_iterator it = i1.cell().begin();
1464 Buffer * buf = cur.buffer();
1465 return asString(MathData(buf, it + i1.pos(), it + i2.pos()));
1467 return from_ascii("unknown selection 1");
1471 Inset::row_type r1, r2;
1472 Inset::col_type c1, c2;
1473 region(i1, i2, r1, r2, c1, c2);
1476 if (i1.inset().asInsetMath()) {
1477 for (Inset::row_type row = r1; row <= r2; ++row) {
1480 for (Inset::col_type col = c1; col <= c2; ++col) {
1483 data += asString(i1.asInsetMath()->
1484 cell(i1.asInsetMath()->index(row, col)));
1488 data = from_ascii("unknown selection 2");
1494 void dirtyTabularStack(bool b)
1496 dirty_tabular_stack_ = b;
1500 bool tabularStackDirty()
1502 return dirty_tabular_stack_;