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"
71 #include <boost/tuple/tuple.hpp>
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);
91 // store whether the tabular stack is newer than the normal copy stack
92 // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
93 // when we (hopefully) have a one-for-all paste mechanism.
94 bool dirty_tabular_stack_ = false;
97 bool checkPastePossible(int index)
99 return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
103 struct PasteReturnValue {
104 PasteReturnValue(pit_type r_pit, pos_type r_pos, bool r_nu) :
105 pit(r_pit), pos(r_pos), needupdate(r_nu)
114 pasteSelectionHelper(DocIterator const & cur, ParagraphList const & parlist,
115 DocumentClassConstPtr oldDocClass, Buffer * tmpbuffer,
116 ErrorList & errorlist)
118 Buffer const & buffer = *cur.buffer();
119 pit_type pit = cur.pit();
120 pos_type pos = cur.pos();
121 bool need_update = false;
124 return PasteReturnValue(pit, pos, need_update);
126 InsetText * target_inset = cur.inset().asInsetText();
128 InsetTabular * it = cur.inset().asInsetTabular();
129 target_inset = it ? it->cell(cur.idx())->asInsetText() : 0;
131 LASSERT(target_inset, return PasteReturnValue(pit, pos, need_update));
133 ParagraphList & pars = target_inset->paragraphs();
134 LASSERT(pos <= pars[pit].size(),
135 return PasteReturnValue(pit, pos, need_update));
137 // Make a copy of the CaP paragraphs.
138 ParagraphList insertion = parlist;
140 // Now remove all out of the pars which is NOT allowed in the
141 // new environment and set also another font if that is required.
143 // Convert newline to paragraph break in ParbreakIsNewline
144 if (target_inset->getLayout().parbreakIsNewline()
145 || pars[pit].layout().parbreak_is_newline) {
146 for (size_t i = 0; i != insertion.size(); ++i) {
147 for (pos_type j = 0; j != insertion[i].size(); ++j) {
148 if (insertion[i].isNewline(j)) {
149 // do not track deletion of newline
150 insertion[i].eraseChar(j, false);
151 insertion[i].setInsetOwner(target_inset);
152 breakParagraphConservative(
161 // set the paragraphs to plain layout if necessary
162 DocumentClassConstPtr newDocClass = buffer.params().documentClassPtr();
163 if (cur.inset().usePlainLayout()) {
164 bool forcePlainLayout = cur.inset().forcePlainLayout();
165 Layout const & plainLayout = newDocClass->plainLayout();
166 Layout const & defaultLayout = newDocClass->defaultLayout();
167 ParagraphList::iterator const end = insertion.end();
168 ParagraphList::iterator par = insertion.begin();
169 for (; par != end; ++par) {
170 Layout const & parLayout = par->layout();
171 if (forcePlainLayout || parLayout == defaultLayout)
172 par->setLayout(plainLayout);
175 // check if we need to reset from plain layout
176 Layout const & defaultLayout = newDocClass->defaultLayout();
177 Layout const & plainLayout = newDocClass->plainLayout();
178 ParagraphList::iterator const end = insertion.end();
179 ParagraphList::iterator par = insertion.begin();
180 for (; par != end; ++par) {
181 Layout const & parLayout = par->layout();
182 if (parLayout == plainLayout)
183 par->setLayout(defaultLayout);
187 InsetText in(cur.buffer());
188 // Make sure there is no class difference.
189 in.paragraphs().clear();
190 // This works without copying any paragraph data because we have
191 // a specialized swap method for ParagraphList. This is important
192 // since we store pointers to insets at some places and we don't
193 // want to invalidate them.
194 insertion.swap(in.paragraphs());
195 cap::switchBetweenClasses(oldDocClass, newDocClass, in, errorlist);
196 insertion.swap(in.paragraphs());
198 ParagraphList::iterator tmpbuf = insertion.begin();
199 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
201 depth_type max_depth = pars[pit].getMaxDepthAfter();
203 for (; tmpbuf != insertion.end(); ++tmpbuf) {
204 // If we have a negative jump so that the depth would
205 // go below 0 depth then we have to redo the delta to
206 // this new max depth level so that subsequent
207 // paragraphs are aligned correctly to this paragraph
209 if (int(tmpbuf->params().depth()) + depth_delta < 0)
212 // Set the right depth so that we are not too deep or shallow.
213 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
214 if (tmpbuf->params().depth() > max_depth)
215 tmpbuf->params().depth(max_depth);
217 // Set max_depth for the next paragraph
218 max_depth = tmpbuf->getMaxDepthAfter();
220 // Set the inset owner of this paragraph.
221 tmpbuf->setInsetOwner(target_inset);
222 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
223 // do not track deletion of invalid insets
224 if (Inset * inset = tmpbuf->getInset(i))
225 if (!target_inset->insetAllowed(inset->lyxCode()))
226 tmpbuf->eraseChar(i--, false);
229 tmpbuf->setChange(Change(buffer.params().track_changes ?
230 Change::INSERTED : Change::UNCHANGED));
233 bool const empty = pars[pit].empty();
235 // Make the buf exactly the same layout as the cursor
237 insertion.begin()->makeSameLayout(pars[pit]);
240 // Prepare the paragraphs and insets for insertion.
241 insertion.swap(in.paragraphs());
243 InsetIterator const i_end = inset_iterator_end(in);
244 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
245 // Even though this will also be done later, it has to be done here
246 // since some inset might going to try to access
247 // the buffer() member.
248 it->setBuffer(const_cast<Buffer &>(buffer));
249 switch (it->lyxCode()) {
251 case MATH_HULL_CODE: {
252 // check for equation labels and resolve duplicates
253 InsetMathHull * ins = it->asInsetMath()->asHullInset();
254 std::vector<InsetLabel *> labels = ins->getLabels();
255 for (size_t i = 0; i != labels.size(); ++i) {
258 InsetLabel * lab = labels[i];
259 docstring const oldname = lab->getParam("name");
260 lab->updateLabel(oldname);
261 // We need to update the buffer reference cache.
263 docstring const newname = lab->getParam("name");
264 if (oldname == newname)
266 // adapt the references
267 for (InsetIterator itt = inset_iterator_begin(in);
268 itt != i_end; ++itt) {
269 if (itt->lyxCode() == REF_CODE) {
270 InsetCommand * ref = itt->asInsetCommand();
271 if (ref->getParam("reference") == oldname)
272 ref->setParam("reference", newname);
273 } else if (itt->lyxCode() == MATH_REF_CODE) {
274 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
275 // this is necessary to prevent an uninitialized
276 // buffer when the RefInset is in a MathBox.
277 // FIXME audit setBuffer calls
278 mi->setBuffer(const_cast<Buffer &>(buffer));
279 if (mi->getTarget() == oldname)
280 mi->changeTarget(newname);
288 // check for duplicates
289 InsetLabel & lab = static_cast<InsetLabel &>(*it);
290 docstring const oldname = lab.getParam("name");
291 lab.updateLabel(oldname);
292 // We need to update the buffer reference cache.
294 docstring const newname = lab.getParam("name");
295 if (oldname == newname)
297 // adapt the references
298 for (InsetIterator itt = inset_iterator_begin(in); itt != i_end; ++itt) {
299 if (itt->lyxCode() == REF_CODE) {
300 InsetCommand & ref = static_cast<InsetCommand &>(*itt);
301 if (ref.getParam("reference") == oldname)
302 ref.setParam("reference", newname);
303 } else if (itt->lyxCode() == MATH_REF_CODE) {
304 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
305 // this is necessary to prevent an uninitialized
306 // buffer when the RefInset is in a MathBox.
307 // FIXME audit setBuffer calls
308 mi->setBuffer(const_cast<Buffer &>(buffer));
309 if (mi->getTarget() == oldname)
310 mi->changeTarget(newname);
317 InsetInclude & inc = static_cast<InsetInclude &>(*it);
319 // We need to update the list of included files.
325 // check for duplicates
326 InsetBibitem & bib = static_cast<InsetBibitem &>(*it);
327 docstring const oldkey = bib.getParam("key");
328 bib.updateCommand(oldkey, false);
329 // We need to update the buffer reference cache.
331 docstring const newkey = bib.getParam("key");
332 if (oldkey == newkey)
334 // adapt the references
335 for (InsetIterator itt = inset_iterator_begin(in);
336 itt != i_end; ++itt) {
337 if (itt->lyxCode() == CITE_CODE) {
338 InsetCommand * ref = itt->asInsetCommand();
339 if (ref->getParam("key") == oldkey)
340 ref->setParam("key", newkey);
347 // check if branch is known to target buffer
349 InsetBranch & br = static_cast<InsetBranch &>(*it);
350 docstring const name = br.branch();
353 bool const is_child = (&buffer != buffer.masterBuffer());
354 BranchList branchlist = buffer.params().branchlist();
355 if ((!is_child && branchlist.find(name))
356 || (is_child && (branchlist.find(name)
357 || buffer.masterBuffer()->params().branchlist().find(name))))
360 // This is for a temporary buffer, so simply create the branch.
361 // Must not use lyx::dispatch(), since tmpbuffer has no view.
363 tmpbuffer->dispatch(FuncRequest(LFUN_BRANCH_ADD, name), dr);
365 docstring text = bformat(
366 _("The pasted branch \"%1$s\" is undefined.\n"
367 "Do you want to add it to the document's branch list?"),
369 if (frontend::Alert::prompt(_("Unknown branch"),
370 text, 0, 1, _("&Add"), _("&Don't Add")) != 0)
372 lyx::dispatch(FuncRequest(LFUN_BRANCH_ADD, name));
374 // We need to update the list of branches.
383 insertion.swap(in.paragraphs());
385 // Split the paragraph for inserting the buf if necessary.
387 breakParagraphConservative(buffer.params(), pars, pit, pos);
391 pars.insert(lyx::next(pars.begin(), pit),
395 // merge the empty par with the last par of the insertion
396 mergeParagraph(buffer.params(), pars,
397 pit + insertion.size() - 1);
399 pars.insert(lyx::next(pars.begin(), pit + 1),
403 // merge the first par of the insertion with the current par
404 mergeParagraph(buffer.params(), pars, pit);
407 // Store the new cursor position.
408 pit_type last_paste = pit + insertion.size() - 1;
409 pit_type startpit = pit;
411 pos = pars[last_paste].size();
413 // FIXME Should we do it here, or should we let updateBuffer() do it?
414 // Set paragraph buffers. It's important to do this right away
415 // before something calls Inset::buffer() and causes a crash.
416 for (pit_type p = startpit; p <= pit; ++p)
417 pars[p].setBuffer(const_cast<Buffer &>(buffer));
419 // Join (conditionally) last pasted paragraph with next one, i.e.,
420 // the tail of the spliced document paragraph
421 if (!empty && last_paste + 1 != pit_type(pars.size())) {
422 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
423 mergeParagraph(buffer.params(), pars, last_paste);
424 } else if (pars[last_paste + 1].empty()) {
425 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
426 mergeParagraph(buffer.params(), pars, last_paste);
427 } else if (pars[last_paste].empty()) {
428 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
429 mergeParagraph(buffer.params(), pars, last_paste);
431 pars[last_paste + 1].stripLeadingSpaces(buffer.params().track_changes);
436 return PasteReturnValue(pit, pos, need_update);
440 PitPosPair eraseSelectionHelper(BufferParams const & params,
441 ParagraphList & pars,
442 pit_type startpit, pit_type endpit,
443 int startpos, int endpos)
445 // Start of selection is really invalid.
446 if (startpit == pit_type(pars.size()) ||
447 (startpos > pars[startpit].size()))
448 return PitPosPair(endpit, endpos);
450 // Start and end is inside same paragraph
451 if (endpit == pit_type(pars.size()) || startpit == endpit) {
452 endpos -= pars[startpit].eraseChars(startpos, endpos, params.track_changes);
453 return PitPosPair(endpit, endpos);
456 for (pit_type pit = startpit; pit != endpit + 1;) {
457 pos_type const left = (pit == startpit ? startpos : 0);
458 pos_type right = (pit == endpit ? endpos : pars[pit].size() + 1);
459 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.track_changes);
461 // Logically erase only, including the end-of-paragraph character
462 pars[pit].eraseChars(left, right, params.track_changes);
464 // Separate handling of paragraph break:
465 if (merge && pit != endpit &&
467 || pars[pit].hasSameLayout(pars[endpit])
468 || pars[endpit].size() == endpos)) {
469 if (pit + 1 == endpit)
470 endpos += pars[pit].size();
471 mergeParagraph(params, pars, pit);
477 // Ensure legal cursor pos:
480 return PitPosPair(endpit, endpos);
484 Buffer * copyToTempBuffer(ParagraphList const & paragraphs, DocumentClassConstPtr docclass)
486 // This used to need to be static to avoid a memory leak. It no longer needs
487 // to be so, but the alternative is to construct a new one of these (with a
488 // new temporary directory, etc) every time, and then to destroy it. So maybe
489 // it's worth just keeping this one around.
491 static TempFile tempfile("clipboard.internal");
492 tempfile.setAutoRemove(false);
493 static Buffer * staticbuffer = theBufferList().newInternalBuffer(
494 tempfile.name().absFileName());
496 // These two things only really need doing the first time.
497 staticbuffer->setUnnamed(true);
498 staticbuffer->inset().setBuffer(*staticbuffer);
500 // Use a clone for the complicated stuff so that we do not need to clean
501 // up in order to avoid a crash.
502 Buffer * buffer = staticbuffer->cloneBufferOnly();
503 LASSERT(buffer, return 0);
505 // This needs doing every time.
506 // Since setDocumentClass() causes deletion of the old document class
507 // we need to reset all layout pointers in paragraphs (otherwise they
508 // would be dangling).
509 ParIterator const end = buffer->par_iterator_end();
510 for (ParIterator it = buffer->par_iterator_begin(); it != end; ++it) {
511 docstring const name = it->layout().name();
512 if (docclass->hasLayout(name))
513 it->setLayout((*docclass)[name]);
515 it->setPlainOrDefaultLayout(*docclass);
517 buffer->params().setDocumentClass(docclass);
519 // we will use pasteSelectionHelper to copy the paragraphs into the
520 // temporary Buffer, since it does a lot of things to fix them up.
521 DocIterator dit = doc_iterator_begin(buffer, &buffer->inset());
523 pasteSelectionHelper(dit, paragraphs, docclass, buffer, el);
529 void putClipboard(ParagraphList const & paragraphs,
530 DocumentClassConstPtr docclass, docstring const & plaintext)
532 Buffer * buffer = copyToTempBuffer(paragraphs, docclass);
533 if (!buffer) // already asserted in copyToTempBuffer()
536 // We don't want to produce images that are not used. Therefore,
537 // output formulas as MathML. Even if this is not understood by all
538 // applications, the number that can parse it should go up in the future.
539 buffer->params().html_math_output = BufferParams::MathML;
541 // Make sure MarkAsExporting is deleted before buffer is
543 // The Buffer is being used to export. This is necessary so that the
544 // updateMacros call will record the needed information.
545 MarkAsExporting mex(buffer);
547 buffer->updateBuffer(Buffer::UpdateMaster, OutputUpdate);
548 buffer->updateMacros();
549 buffer->updateMacroInstances(OutputUpdate);
554 if (buffer->write(oslyx))
558 odocstringstream oshtml;
559 OutputParams runparams(encodings.fromLyXName("utf8"));
560 // We do not need to produce images, etc.
561 runparams.dryrun = true;
562 // We are not interested in errors (bug 8866)
563 runparams.silent = true;
564 buffer->writeLyXHTMLSource(oshtml, runparams, Buffer::FullSource);
566 theClipboard().put(lyx, oshtml.str(), plaintext);
574 /// return true if the whole ParagraphList is deleted
575 static bool isFullyDeleted(ParagraphList const & pars)
577 pit_type const pars_size = static_cast<pit_type>(pars.size());
579 // check all paragraphs
580 for (pit_type pit = 0; pit < pars_size; ++pit) {
581 if (!pars[pit].empty()) // prevent assertion failure
582 if (!pars[pit].isDeleted(0, pars[pit].size()))
589 void copySelectionHelper(Buffer const & buf, Text const & text,
590 pit_type startpit, pit_type endpit,
591 int start, int end, DocumentClassConstPtr dc, CutStack & cutstack)
593 ParagraphList const & pars = text.paragraphs();
595 // In most of these cases, we can try to recover.
596 LASSERT(0 <= start, start = 0);
597 LASSERT(start <= pars[startpit].size(), start = pars[startpit].size());
598 LASSERT(0 <= end, end = 0);
599 LASSERT(end <= pars[endpit].size(), end = pars[endpit].size());
600 LASSERT(startpit != endpit || start <= end, return);
602 // Clone the paragraphs within the selection.
603 ParagraphList copy_pars(lyx::next(pars.begin(), startpit),
604 lyx::next(pars.begin(), endpit + 1));
606 // Remove the end of the last paragraph; afterwards, remove the
607 // beginning of the first paragraph. Keep this order - there may only
608 // be one paragraph! Do not track deletions here; this is an internal
609 // action not visible to the user
611 Paragraph & back = copy_pars.back();
612 back.eraseChars(end, back.size(), false);
613 Paragraph & front = copy_pars.front();
614 front.eraseChars(0, start, false);
616 ParagraphList::iterator it = copy_pars.begin();
617 ParagraphList::iterator it_end = copy_pars.end();
619 for (; it != it_end; ++it) {
620 // Since we have a copy of the paragraphs, the insets
621 // do not have a proper buffer reference. It makes
622 // sense to add them temporarily, because the
623 // operations below depend on that (acceptChanges included).
624 it->setBuffer(const_cast<Buffer &>(buf));
625 // PassThru paragraphs have the Language
626 // latex_language. This is invalid for others, so we
627 // need to change it to the buffer language.
628 if (it->isPassThru())
629 it->changeLanguage(buf.params(),
630 latex_language, buf.language());
633 // do not copy text (also nested in insets) which is marked as
634 // deleted, unless the whole selection was deleted
635 if (!isFullyDeleted(copy_pars))
636 acceptChanges(copy_pars, buf.params());
638 rejectChanges(copy_pars, buf.params());
641 // do some final cleanup now, to make sure that the paragraphs
642 // are not linked to something else.
643 it = copy_pars.begin();
644 for (; it != it_end; ++it) {
645 it->setBuffer(*static_cast<Buffer *>(0));
646 it->setInsetOwner(0);
649 cutstack.push(make_pair(copy_pars, dc));
659 void region(CursorSlice const & i1, CursorSlice const & i2,
660 Inset::row_type & r1, Inset::row_type & r2,
661 Inset::col_type & c1, Inset::col_type & c2)
663 Inset & p = i1.inset();
664 c1 = p.col(i1.idx());
665 c2 = p.col(i2.idx());
668 r1 = p.row(i1.idx());
669 r2 = p.row(i2.idx());
675 docstring grabAndEraseSelection(Cursor & cur)
677 if (!cur.selection())
679 docstring res = grabSelection(cur);
685 bool reduceSelectionToOneCell(Cursor & cur)
687 if (!cur.selection() || !cur.inMathed())
690 CursorSlice i1 = cur.selBegin();
691 CursorSlice i2 = cur.selEnd();
692 if (!i1.inset().asInsetMath())
695 // the easy case: do nothing if only one cell is selected
696 if (i1.idx() == i2.idx())
701 cur.top().pos() = cur.top().lastpos();
707 bool multipleCellsSelected(Cursor const & cur)
709 if (!cur.selection() || !cur.inMathed())
712 CursorSlice i1 = cur.selBegin();
713 CursorSlice i2 = cur.selEnd();
714 if (!i1.inset().asInsetMath())
717 if (i1.idx() == i2.idx())
724 void switchBetweenClasses(DocumentClassConstPtr oldone,
725 DocumentClassConstPtr newone, InsetText & in, ErrorList & errorlist)
729 LBUFERR(!in.paragraphs().empty());
730 if (oldone == newone)
733 DocumentClass const & oldtc = *oldone;
734 DocumentClass const & newtc = *newone;
737 ParIterator it = par_iterator_begin(in);
738 ParIterator end = par_iterator_end(in);
739 // for remembering which layouts we've had to add
740 set<docstring> newlayouts;
741 for (; it != end; ++it) {
742 docstring const name = it->layout().name();
744 // the pasted text will keep their own layout name. If this layout does
745 // not exist in the new document, it will behave like a standard layout.
746 bool const added_one = newtc.addLayoutIfNeeded(name);
748 newlayouts.insert(name);
750 if (added_one || newlayouts.find(name) != newlayouts.end()) {
752 docstring const s = bformat(_("Layout `%1$s' was not found."), name);
754 ErrorItem(_("Layout Not Found"), s, it->id(), 0, it->size()));
757 if (in.usePlainLayout())
758 it->setLayout(newtc.plainLayout());
760 it->setLayout(newtc[name]);
763 // character styles and hidden table cells
764 InsetIterator const i_end = inset_iterator_end(in);
765 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
766 InsetCode const code = it->lyxCode();
767 if (code == FLEX_CODE) {
768 // FIXME: Should we verify all InsetCollapsable?
769 docstring const layoutName = it->layoutName();
770 docstring const & n = newone->insetLayout(layoutName).name();
771 bool const is_undefined = n.empty() ||
772 n == DocumentClass::plainInsetLayout().name();
776 // The flex inset is undefined in newtc
777 docstring const oldname = from_utf8(oldtc.name());
778 docstring const newname = from_utf8(newtc.name());
780 if (oldname == newname)
781 s = bformat(_("Flex inset %1$s is undefined after "
782 "reloading `%2$s' layout."), layoutName, oldname);
784 s = bformat(_("Flex inset %1$s is undefined because of "
785 "conversion from `%2$s' layout to `%3$s'."),
786 layoutName, oldname, newname);
787 // To warn the user that something had to be done.
788 errorlist.push_back(ErrorItem(
789 _("Undefined flex inset"),
790 s, it.paragraph().id(), it.pos(), it.pos() + 1));
791 } else if (code == TABULAR_CODE) {
792 // The recursion above does not catch paragraphs in "hidden" cells,
793 // i.e., ones that are part of a multirow or multicolum. So we need
794 // to handle those separately.
795 // This is the cause of bug #9049.
796 InsetTabular * table = it->asInsetTabular();
797 table->setLayoutForHiddenCells(newtc);
803 vector<docstring> availableSelections(Buffer const * buf)
805 vector<docstring> selList;
809 CutStack::const_iterator cit = theCuts.begin();
810 CutStack::const_iterator end = theCuts.end();
811 for (; cit != end; ++cit) {
812 // we do not use cit-> here because gcc 2.9x does not
814 ParagraphList const & pars = (*cit).first;
816 ParagraphList::const_iterator pit = pars.begin();
817 ParagraphList::const_iterator pend = pars.end();
818 for (; pit != pend; ++pit) {
819 Paragraph par(*pit, 0, 46);
820 // adapt paragraph to current buffer.
821 par.setBuffer(const_cast<Buffer &>(*buf));
822 textSel += par.asString(AS_STR_INSETS);
823 if (textSel.size() > 45) {
824 support::truncateWithEllipsis(textSel,45);
828 selList.push_back(textSel);
835 size_type numberOfSelections()
837 return theCuts.size();
841 void cutSelection(Cursor & cur, bool doclear, bool realcut)
843 // This doesn't make sense, if there is no selection
844 if (!cur.selection())
847 // OK, we have a selection. This is always between cur.selBegin()
850 if (cur.inTexted()) {
851 Text * text = cur.text();
856 // make sure that the depth behind the selection are restored, too
857 cur.recordUndoSelection();
858 pit_type begpit = cur.selBegin().pit();
859 pit_type endpit = cur.selEnd().pit();
861 int endpos = cur.selEnd().pos();
863 BufferParams const & bp = cur.buffer()->params();
865 copySelectionHelper(*cur.buffer(),
868 cur.selBegin().pos(), endpos,
869 bp.documentClassPtr(), theCuts);
870 // Stuff what we got on the clipboard.
871 // Even if there is no selection.
872 putClipboard(theCuts[0].first, theCuts[0].second,
873 cur.selectionAsString(true));
876 if (begpit != endpit)
877 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
879 boost::tie(endpit, endpos) =
880 eraseSelectionHelper(bp,
883 cur.selBegin().pos(), endpos);
885 // cutSelection can invalidate the cursor so we need to set
887 // we prefer the end for when tracking changes
891 // sometimes necessary
893 && text->paragraphs()[begpit].stripLeadingSpaces(bp.track_changes))
896 // need a valid cursor. (Lgb)
897 cur.clearSelection();
899 // After a cut operation, we must make sure that the Buffer is updated
900 // because some further operation might need updated label information for
901 // example. So we cannot just use "cur.forceBufferUpdate()" here.
903 cur.buffer()->updateBuffer();
905 // tell tabular that a recent copy happened
906 dirtyTabularStack(false);
909 if (cur.inMathed()) {
910 if (cur.selBegin().idx() != cur.selEnd().idx()) {
911 // The current selection spans more than one cell.
913 cur.recordUndoInset();
915 // Record only the current cell to avoid a jumping
926 void copySelection(Cursor const & cur)
928 copySelection(cur, cur.selectionAsString(true));
932 void copyInset(Cursor const & cur, Inset * inset, docstring const & plaintext)
936 BufferParams const & bp = cur.buffer()->params();
937 par.setLayout(bp.documentClass().plainLayout());
938 Font font(inherit_font, bp.language);
939 par.insertInset(0, inset, font, Change(Change::UNCHANGED));
941 theCuts.push(make_pair(pars, bp.documentClassPtr()));
943 // stuff the selection onto the X clipboard, from an explicit copy request
944 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
950 void copySelectionToStack(Cursor const & cur, CutStack & cutstack)
952 // this doesn't make sense, if there is no selection
953 if (!cur.selection())
956 // copySelection can not yet handle the case of cross idx selection
957 if (cur.selBegin().idx() != cur.selEnd().idx())
960 if (cur.inTexted()) {
961 Text * text = cur.text();
963 // ok we have a selection. This is always between cur.selBegin()
964 // and sel_end cursor
965 copySelectionHelper(*cur.buffer(), *text,
966 cur.selBegin().pit(), cur.selEnd().pit(),
967 cur.selBegin().pos(), cur.selEnd().pos(),
968 cur.buffer()->params().documentClassPtr(),
970 // Reset the dirty_tabular_stack_ flag only when something
971 // is copied to the clipboard (not to the selectionBuffer).
972 if (&cutstack == &theCuts)
973 dirtyTabularStack(false);
976 if (cur.inMathed()) {
977 //lyxerr << "copySelection in mathed" << endl;
980 BufferParams const & bp = cur.buffer()->params();
981 // FIXME This should be the plain layout...right?
982 par.setLayout(bp.documentClass().plainLayout());
983 par.insert(0, grabSelection(cur), Font(), Change(Change::UNCHANGED));
985 cutstack.push(make_pair(pars, bp.documentClassPtr()));
992 void copySelectionToStack()
994 if (!selectionBuffer.empty())
995 theCuts.push(selectionBuffer[0]);
999 void copySelection(Cursor const & cur, docstring const & plaintext)
1001 // In tablemode, because copy and paste actually use special table stack
1002 // we do not attempt to get selected paragraphs under cursor. Instead, a
1003 // paragraph with the plain text version is generated so that table cells
1004 // can be pasted as pure text somewhere else.
1005 if (cur.selBegin().idx() != cur.selEnd().idx()) {
1008 BufferParams const & bp = cur.buffer()->params();
1009 par.setLayout(bp.documentClass().plainLayout());
1010 par.insert(0, plaintext, Font(), Change(Change::UNCHANGED));
1011 pars.push_back(par);
1012 theCuts.push(make_pair(pars, bp.documentClassPtr()));
1014 copySelectionToStack(cur, theCuts);
1017 // stuff the selection onto the X clipboard, from an explicit copy request
1018 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
1022 void saveSelection(Cursor const & cur)
1024 // This function is called, not when a selection is formed, but when
1025 // a selection is cleared. Therefore, multiple keyboard selection
1026 // will not repeatively trigger this function (bug 3877).
1028 && cur.selBegin() == cur.bv().cursor().selBegin()
1029 && cur.selEnd() == cur.bv().cursor().selEnd()) {
1030 LYXERR(Debug::SELECTION, "saveSelection: '" << cur.selectionAsString(true) << "'");
1031 copySelectionToStack(cur, selectionBuffer);
1038 return !selectionBuffer.empty();
1042 void clearSelection()
1044 selectionBuffer.clear();
1048 void clearCutStack()
1054 docstring selection(size_t sel_index, DocumentClassConstPtr docclass)
1056 if (sel_index >= theCuts.size())
1059 unique_ptr<Buffer> buffer(copyToTempBuffer(theCuts[sel_index].first,
1064 return buffer->paragraphs().back().asString(AS_STR_INSETS | AS_STR_NEWLINES);
1068 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
1069 DocumentClassConstPtr docclass, ErrorList & errorList)
1071 if (cur.inTexted()) {
1072 Text * text = cur.text();
1075 PasteReturnValue prv =
1076 pasteSelectionHelper(cur, parlist, docclass, 0, errorList);
1077 cur.forceBufferUpdate();
1078 cur.clearSelection();
1079 text->setCursor(cur, prv.pit, prv.pos);
1082 // mathed is handled in InsetMathNest/InsetMathGrid
1083 LATTEST(!cur.inMathed());
1087 bool pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
1089 // this does not make sense, if there is nothing to paste
1090 if (!checkPastePossible(sel_index))
1094 pasteParagraphList(cur, theCuts[sel_index].first,
1095 theCuts[sel_index].second, errorList);
1100 bool pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs,
1101 Clipboard::TextType type)
1103 // Use internal clipboard if it is the most recent one
1104 // This overrides asParagraphs and type on purpose!
1105 if (theClipboard().isInternal())
1106 return pasteFromStack(cur, errorList, 0);
1108 // First try LyX format
1109 if ((type == Clipboard::LyXTextType ||
1110 type == Clipboard::LyXOrPlainTextType ||
1111 type == Clipboard::AnyTextType) &&
1112 theClipboard().hasTextContents(Clipboard::LyXTextType)) {
1113 string lyx = theClipboard().getAsLyX();
1115 // For some strange reason gcc 3.2 and 3.3 do not accept
1116 // Buffer buffer(string(), false);
1117 Buffer buffer("", false);
1118 buffer.setUnnamed(true);
1119 if (buffer.readString(lyx)) {
1121 pasteParagraphList(cur, buffer.paragraphs(),
1122 buffer.params().documentClassPtr(), errorList);
1128 // Then try TeX and HTML
1129 Clipboard::TextType types[2] = {Clipboard::HtmlTextType, Clipboard::LaTeXTextType};
1130 string names[2] = {"html", "latexclipboard"};
1131 for (int i = 0; i < 2; ++i) {
1132 if (type != types[i] && type != Clipboard::AnyTextType)
1134 bool available = theClipboard().hasTextContents(types[i]);
1136 // If a specific type was explicitly requested, try to
1137 // interpret plain text: The user told us that the clipboard
1138 // contents is in the desired format
1139 if (!available && type == types[i]) {
1140 types[i] = Clipboard::PlainTextType;
1141 available = theClipboard().hasTextContents(types[i]);
1145 docstring text = theClipboard().getAsText(types[i]);
1146 available = !text.empty();
1148 // For some strange reason gcc 3.2 and 3.3 do not accept
1149 // Buffer buffer(string(), false);
1150 Buffer buffer("", false);
1151 buffer.setUnnamed(true);
1152 available = buffer.importString(names[i], text, errorList);
1154 available = !buffer.paragraphs().empty();
1155 if (available && !buffer.paragraphs()[0].empty()) {
1157 pasteParagraphList(cur, buffer.paragraphs(),
1158 buffer.params().documentClassPtr(), errorList);
1165 // Then try plain text
1166 docstring const text = theClipboard().getAsText(Clipboard::PlainTextType);
1171 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1173 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1178 void pasteSimpleText(Cursor & cur, bool asParagraphs)
1181 // Use internal clipboard if it is the most recent one
1182 if (theClipboard().isInternal()) {
1183 if (!checkPastePossible(0))
1186 ParagraphList const & pars = theCuts[0].first;
1187 ParagraphList::const_iterator it = pars.begin();
1188 for (; it != pars.end(); ++it) {
1189 if (it != pars.begin())
1191 text += (*it).asString();
1193 asParagraphs = false;
1195 // Then try plain text
1196 text = theClipboard().getAsText(Clipboard::PlainTextType);
1203 cutSelection(cur, true, false);
1205 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1207 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1211 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
1212 Clipboard::GraphicsType preferedType)
1214 LASSERT(theClipboard().hasGraphicsContents(preferedType), return);
1216 // get picture from clipboard
1217 FileName filename = theClipboard().getAsGraphics(cur, preferedType);
1218 if (filename.empty())
1221 // create inset for graphic
1222 InsetGraphics * inset = new InsetGraphics(cur.buffer());
1223 InsetGraphicsParams params;
1224 params.filename = support::DocFileName(filename.absFileName(), false);
1225 inset->setParams(params);
1231 void pasteSelection(Cursor & cur, ErrorList & errorList)
1233 if (selectionBuffer.empty())
1236 pasteParagraphList(cur, selectionBuffer[0].first,
1237 selectionBuffer[0].second, errorList);
1241 void replaceSelectionWithString(Cursor & cur, docstring const & str)
1244 DocIterator selbeg = cur.selectionBegin();
1246 // Get font setting before we cut, we need a copy here, not a bare reference.
1248 selbeg.paragraph().getFontSettings(cur.buffer()->params(), selbeg.pos());
1250 // Insert the new string
1251 pos_type pos = cur.selEnd().pos();
1252 Paragraph & par = cur.selEnd().paragraph();
1253 docstring::const_iterator cit = str.begin();
1254 docstring::const_iterator end = str.end();
1255 for (; cit != end; ++cit, ++pos)
1256 par.insertChar(pos, *cit, font, cur.buffer()->params().track_changes);
1258 // Cut the selection
1259 cutSelection(cur, true, false);
1263 void replaceSelection(Cursor & cur)
1265 if (cur.selection())
1266 cutSelection(cur, true, false);
1270 void eraseSelection(Cursor & cur)
1272 //lyxerr << "cap::eraseSelection begin: " << cur << endl;
1273 CursorSlice const & i1 = cur.selBegin();
1274 CursorSlice const & i2 = cur.selEnd();
1275 if (!i1.asInsetMath()) {
1276 LYXERR0("Can't erase this selection");
1282 InsetMath * p = i1.asInsetMath();
1283 if (i1.idx() == i2.idx()) {
1284 i1.cell().erase(i1.pos(), i2.pos());
1285 // We may have deleted i1.cell(cur.pos()).
1286 // Make sure that pos is valid.
1287 if (cur.pos() > cur.lastpos())
1288 cur.pos() = cur.lastpos();
1289 } else if (p->nrows() > 0 && p->ncols() > 0) {
1290 // This is a grid, delete a nice square region
1291 Inset::row_type r1, r2;
1292 Inset::col_type c1, c2;
1293 region(i1, i2, r1, r2, c1, c2);
1294 for (Inset::row_type row = r1; row <= r2; ++row)
1295 for (Inset::col_type col = c1; col <= c2; ++col)
1296 p->cell(p->index(row, col)).clear();
1297 // We've deleted the whole cell. Only pos 0 is valid.
1300 Inset::idx_type idx1 = i1.idx();
1301 Inset::idx_type idx2 = i2.idx();
1304 for (Inset::idx_type idx = idx1 ; idx <= idx2; ++idx)
1305 p->cell(idx).clear();
1306 // We've deleted the whole cell. Only pos 0 is valid.
1310 // need a valid cursor. (Lgb)
1311 cur.clearSelection();
1312 //lyxerr << "cap::eraseSelection end: " << cur << endl;
1316 void selDel(Cursor & cur)
1318 //lyxerr << "cap::selDel" << endl;
1319 if (cur.selection())
1320 eraseSelection(cur);
1324 void selClearOrDel(Cursor & cur)
1326 //lyxerr << "cap::selClearOrDel" << endl;
1327 if (lyxrc.auto_region_delete)
1330 cur.selection(false);
1334 docstring grabSelection(Cursor const & cur)
1336 if (!cur.selection())
1340 // grab selection by glueing multiple cells together. This is not what
1341 // we want because selections spanning multiple cells will get "&" and "\\"
1344 for (DocIterator dit = cur.selectionBegin();
1345 dit != cur.selectionEnd(); dit.forwardPos())
1346 os << asString(dit.cell());
1350 CursorSlice i1 = cur.selBegin();
1351 CursorSlice i2 = cur.selEnd();
1353 if (i1.idx() == i2.idx()) {
1354 if (i1.inset().asInsetMath()) {
1355 MathData::const_iterator it = i1.cell().begin();
1356 Buffer * buf = cur.buffer();
1357 return asString(MathData(buf, it + i1.pos(), it + i2.pos()));
1359 return from_ascii("unknown selection 1");
1363 Inset::row_type r1, r2;
1364 Inset::col_type c1, c2;
1365 region(i1, i2, r1, r2, c1, c2);
1368 if (i1.inset().asInsetMath()) {
1369 for (Inset::row_type row = r1; row <= r2; ++row) {
1372 for (Inset::col_type col = c1; col <= c2; ++col) {
1375 data += asString(i1.asInsetMath()->
1376 cell(i1.asInsetMath()->index(row, col)));
1380 data = from_ascii("unknown selection 2");
1386 void dirtyTabularStack(bool b)
1388 dirty_tabular_stack_ = b;
1392 bool tabularStackDirty()
1394 return dirty_tabular_stack_;