2 * \file CutAndPaste.cpp
3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
7 * \author Lars Gullik Bjønnes
8 * \author Alfredo Braunstein
11 * Full author contact details are available in file CREDITS.
16 #include "CutAndPaste.h"
18 #include "BranchList.h"
20 #include "buffer_funcs.h"
21 #include "BufferList.h"
22 #include "BufferParams.h"
23 #include "BufferView.h"
27 #include "ErrorList.h"
29 #include "FuncRequest.h"
30 #include "InsetIterator.h"
31 #include "InsetList.h"
36 #include "Paragraph.h"
37 #include "ParagraphParameters.h"
38 #include "ParIterator.h"
39 #include "TextClass.h"
41 #include "insets/InsetBibitem.h"
42 #include "insets/InsetBranch.h"
43 #include "insets/InsetCommand.h"
44 #include "insets/InsetFlex.h"
45 #include "insets/InsetGraphics.h"
46 #include "insets/InsetGraphicsParams.h"
47 #include "insets/InsetInclude.h"
48 #include "insets/InsetLabel.h"
49 #include "insets/InsetTabular.h"
51 #include "mathed/MathData.h"
52 #include "mathed/InsetMath.h"
53 #include "mathed/InsetMathHull.h"
54 #include "mathed/InsetMathRef.h"
55 #include "mathed/MathSupport.h"
57 #include "support/debug.h"
58 #include "support/docstream.h"
59 #include "support/gettext.h"
60 #include "support/lassert.h"
61 #include "support/limited_stack.h"
62 #include "support/lstrings.h"
63 #include "support/lyxalgo.h"
64 #include "support/TempFile.h"
65 #include "support/unique_ptr.h"
67 #include "frontends/alert.h"
68 #include "frontends/Clipboard.h"
69 #include "frontends/Selection.h"
75 using namespace lyx::support;
76 using lyx::frontend::Clipboard;
82 typedef pair<pit_type, int> PitPosPair;
84 typedef limited_stack<pair<ParagraphList, DocumentClassConstPtr> > CutStack;
87 // persistent selection, cleared until the next selection
88 CutStack selectionBuffer(1);
90 // store whether the tabular stack is newer than the normal copy stack
91 // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
92 // when we (hopefully) have a one-for-all paste mechanism.
93 bool dirty_tabular_stack_ = false;
96 bool checkPastePossible(int index)
98 return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
102 struct PasteReturnValue {
103 PasteReturnValue(pit_type r_pit, pos_type r_pos, bool r_nu) :
104 pit(r_pit), pos(r_pos), needupdate(r_nu)
113 pasteSelectionHelper(DocIterator const & cur, ParagraphList const & parlist,
114 DocumentClassConstPtr oldDocClass, Buffer * tmpbuffer,
115 ErrorList & errorlist)
117 Buffer const & buffer = *cur.buffer();
118 pit_type pit = cur.pit();
119 pos_type pos = cur.pos();
120 bool need_update = false;
123 return PasteReturnValue(pit, pos, need_update);
125 InsetText * target_inset = cur.inset().asInsetText();
127 InsetTabular * it = cur.inset().asInsetTabular();
128 target_inset = it ? it->cell(cur.idx())->asInsetText() : 0;
130 LASSERT(target_inset, return PasteReturnValue(pit, pos, need_update));
132 ParagraphList & pars = target_inset->paragraphs();
133 LASSERT(pos <= pars[pit].size(),
134 return PasteReturnValue(pit, pos, need_update));
136 // Make a copy of the CaP paragraphs.
137 ParagraphList insertion = parlist;
139 // Now remove all out of the pars which is NOT allowed in the
140 // new environment and set also another font if that is required.
142 // Convert newline to paragraph break in ParbreakIsNewline
143 if (target_inset->getLayout().parbreakIsNewline()
144 || pars[pit].layout().parbreak_is_newline) {
145 for (size_t i = 0; i != insertion.size(); ++i) {
146 for (pos_type j = 0; j != insertion[i].size(); ++j) {
147 if (insertion[i].isNewline(j)) {
148 // do not track deletion of newline
149 insertion[i].eraseChar(j, false);
150 insertion[i].setInsetOwner(target_inset);
151 breakParagraphConservative(
160 // set the paragraphs to plain layout if necessary
161 DocumentClassConstPtr newDocClass = buffer.params().documentClassPtr();
162 if (cur.inset().usePlainLayout()) {
163 bool forcePlainLayout = target_inset->forcePlainLayout();
164 Layout const & plainLayout = newDocClass->plainLayout();
165 Layout const & defaultLayout = newDocClass->defaultLayout();
166 ParagraphList::iterator const end = insertion.end();
167 ParagraphList::iterator par = insertion.begin();
168 for (; par != end; ++par) {
169 Layout const & parLayout = par->layout();
170 if (forcePlainLayout || parLayout == defaultLayout)
171 par->setLayout(plainLayout);
174 // check if we need to reset from plain layout
175 Layout const & defaultLayout = newDocClass->defaultLayout();
176 Layout const & plainLayout = newDocClass->plainLayout();
177 ParagraphList::iterator const end = insertion.end();
178 ParagraphList::iterator par = insertion.begin();
179 for (; par != end; ++par) {
180 Layout const & parLayout = par->layout();
181 if (parLayout == plainLayout)
182 par->setLayout(defaultLayout);
186 InsetText in(cur.buffer());
187 // Make sure there is no class difference.
188 in.paragraphs().clear();
189 // This works without copying any paragraph data because we have
190 // a specialized swap method for ParagraphList. This is important
191 // since we store pointers to insets at some places and we don't
192 // want to invalidate them.
193 insertion.swap(in.paragraphs());
194 cap::switchBetweenClasses(oldDocClass, newDocClass, in, errorlist);
195 insertion.swap(in.paragraphs());
197 ParagraphList::iterator tmpbuf = insertion.begin();
198 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
200 depth_type max_depth = pars[pit].getMaxDepthAfter();
202 for (; tmpbuf != insertion.end(); ++tmpbuf) {
203 // If we have a negative jump so that the depth would
204 // go below 0 depth then we have to redo the delta to
205 // this new max depth level so that subsequent
206 // paragraphs are aligned correctly to this paragraph
208 if (int(tmpbuf->params().depth()) + depth_delta < 0)
211 // Set the right depth so that we are not too deep or shallow.
212 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
213 if (tmpbuf->params().depth() > max_depth)
214 tmpbuf->params().depth(max_depth);
216 // Set max_depth for the next paragraph
217 max_depth = tmpbuf->getMaxDepthAfter();
219 // Set the inset owner of this paragraph.
220 tmpbuf->setInsetOwner(target_inset);
221 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
222 // do not track deletion of invalid insets
223 if (Inset * inset = tmpbuf->getInset(i))
224 if (!target_inset->insetAllowed(inset->lyxCode()))
225 tmpbuf->eraseChar(i--, false);
228 tmpbuf->setChange(Change(buffer.params().track_changes ?
229 Change::INSERTED : Change::UNCHANGED));
232 bool const empty = pars[pit].empty();
234 // Make the buf exactly the same layout as the cursor
236 insertion.begin()->makeSameLayout(pars[pit]);
239 // Prepare the paragraphs and insets for insertion.
240 insertion.swap(in.paragraphs());
242 InsetIterator const i_end = inset_iterator_end(in);
243 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
244 // Even though this will also be done later, it has to be done here
245 // since some inset might going to try to access
246 // the buffer() member.
247 it->setBuffer(const_cast<Buffer &>(buffer));
248 switch (it->lyxCode()) {
250 case MATH_HULL_CODE: {
251 // check for equation labels and resolve duplicates
252 InsetMathHull * ins = it->asInsetMath()->asHullInset();
253 std::vector<InsetLabel *> labels = ins->getLabels();
254 for (size_t i = 0; i != labels.size(); ++i) {
257 InsetLabel * lab = labels[i];
258 docstring const oldname = lab->getParam("name");
259 lab->updateLabel(oldname);
260 // We need to update the buffer reference cache.
262 docstring const newname = lab->getParam("name");
263 if (oldname == newname)
265 // adapt the references
266 for (InsetIterator itt = inset_iterator_begin(in);
267 itt != i_end; ++itt) {
268 if (itt->lyxCode() == REF_CODE) {
269 InsetCommand * ref = itt->asInsetCommand();
270 if (ref->getParam("reference") == oldname)
271 ref->setParam("reference", newname);
272 } else if (itt->lyxCode() == MATH_REF_CODE) {
273 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
274 // this is necessary to prevent an uninitialized
275 // buffer when the RefInset is in a MathBox.
276 // FIXME audit setBuffer calls
277 mi->setBuffer(const_cast<Buffer &>(buffer));
278 if (mi->getTarget() == oldname)
279 mi->changeTarget(newname);
287 // check for duplicates
288 InsetLabel & lab = static_cast<InsetLabel &>(*it);
289 docstring const oldname = lab.getParam("name");
290 lab.updateLabel(oldname);
291 // We need to update the buffer reference cache.
293 docstring const newname = lab.getParam("name");
294 if (oldname == newname)
296 // adapt the references
297 for (InsetIterator itt = inset_iterator_begin(in); itt != i_end; ++itt) {
298 if (itt->lyxCode() == REF_CODE) {
299 InsetCommand & ref = static_cast<InsetCommand &>(*itt);
300 if (ref.getParam("reference") == oldname)
301 ref.setParam("reference", newname);
302 } else if (itt->lyxCode() == MATH_REF_CODE) {
303 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
304 // this is necessary to prevent an uninitialized
305 // buffer when the RefInset is in a MathBox.
306 // FIXME audit setBuffer calls
307 mi->setBuffer(const_cast<Buffer &>(buffer));
308 if (mi->getTarget() == oldname)
309 mi->changeTarget(newname);
316 InsetInclude & inc = static_cast<InsetInclude &>(*it);
318 // We need to update the list of included files.
324 // check for duplicates
325 InsetBibitem & bib = static_cast<InsetBibitem &>(*it);
326 docstring const oldkey = bib.getParam("key");
327 bib.updateCommand(oldkey, false);
328 // We need to update the buffer reference cache.
330 docstring const newkey = bib.getParam("key");
331 if (oldkey == newkey)
333 // adapt the references
334 for (InsetIterator itt = inset_iterator_begin(in);
335 itt != i_end; ++itt) {
336 if (itt->lyxCode() == CITE_CODE) {
337 InsetCommand * ref = itt->asInsetCommand();
338 if (ref->getParam("key") == oldkey)
339 ref->setParam("key", newkey);
346 // check if branch is known to target buffer
348 InsetBranch & br = static_cast<InsetBranch &>(*it);
349 docstring const name = br.branch();
352 bool const is_child = (&buffer != buffer.masterBuffer());
353 BranchList branchlist = buffer.params().branchlist();
354 if ((!is_child && branchlist.find(name))
355 || (is_child && (branchlist.find(name)
356 || buffer.masterBuffer()->params().branchlist().find(name))))
359 // This is for a temporary buffer, so simply create the branch.
360 // Must not use lyx::dispatch(), since tmpbuffer has no view.
362 tmpbuffer->dispatch(FuncRequest(LFUN_BRANCH_ADD, name), dr);
364 docstring text = bformat(
365 _("The pasted branch \"%1$s\" is undefined.\n"
366 "Do you want to add it to the document's branch list?"),
368 if (frontend::Alert::prompt(_("Unknown branch"),
369 text, 0, 1, _("&Add"), _("&Don't Add")) != 0)
371 lyx::dispatch(FuncRequest(LFUN_BRANCH_ADD, name));
373 // We need to update the list of branches.
382 insertion.swap(in.paragraphs());
384 // Split the paragraph for inserting the buf if necessary.
386 breakParagraphConservative(buffer.params(), pars, pit, pos);
390 pars.insert(lyx::next(pars.begin(), pit),
394 // merge the empty par with the last par of the insertion
395 mergeParagraph(buffer.params(), pars,
396 pit + insertion.size() - 1);
398 pars.insert(lyx::next(pars.begin(), pit + 1),
402 // merge the first par of the insertion with the current par
403 mergeParagraph(buffer.params(), pars, pit);
406 // Store the new cursor position.
407 pit_type last_paste = pit + insertion.size() - 1;
408 pit_type startpit = pit;
410 pos = pars[last_paste].size();
412 // FIXME Should we do it here, or should we let updateBuffer() do it?
413 // Set paragraph buffers. It's important to do this right away
414 // before something calls Inset::buffer() and causes a crash.
415 for (pit_type p = startpit; p <= pit; ++p)
416 pars[p].setBuffer(const_cast<Buffer &>(buffer));
418 // Join (conditionally) last pasted paragraph with next one, i.e.,
419 // the tail of the spliced document paragraph
420 if (!empty && last_paste + 1 != pit_type(pars.size())) {
421 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
422 mergeParagraph(buffer.params(), pars, last_paste);
423 } else if (pars[last_paste + 1].empty()) {
424 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
425 mergeParagraph(buffer.params(), pars, last_paste);
426 } else if (pars[last_paste].empty()) {
427 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
428 mergeParagraph(buffer.params(), pars, last_paste);
430 pars[last_paste + 1].stripLeadingSpaces(buffer.params().track_changes);
435 return PasteReturnValue(pit, pos, need_update);
439 PitPosPair eraseSelectionHelper(BufferParams const & params,
440 ParagraphList & pars,
441 pit_type startpit, pit_type endpit,
442 int startpos, int endpos)
444 // Start of selection is really invalid.
445 if (startpit == pit_type(pars.size()) ||
446 (startpos > pars[startpit].size()))
447 return PitPosPair(endpit, endpos);
449 // Start and end is inside same paragraph
450 if (endpit == pit_type(pars.size()) || startpit == endpit) {
451 endpos -= pars[startpit].eraseChars(startpos, endpos, params.track_changes);
452 return PitPosPair(endpit, endpos);
455 for (pit_type pit = startpit; pit != endpit + 1;) {
456 pos_type const left = (pit == startpit ? startpos : 0);
457 pos_type right = (pit == endpit ? endpos : pars[pit].size() + 1);
458 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.track_changes);
460 // Logically erase only, including the end-of-paragraph character
461 pars[pit].eraseChars(left, right, params.track_changes);
463 // Separate handling of paragraph break:
464 if (merge && pit != endpit &&
466 || pars[pit].hasSameLayout(pars[endpit])
467 || pars[endpit].size() == endpos)) {
468 if (pit + 1 == endpit)
469 endpos += pars[pit].size();
470 mergeParagraph(params, pars, pit);
476 // Ensure legal cursor pos:
479 return PitPosPair(endpit, endpos);
483 Buffer * copyToTempBuffer(ParagraphList const & paragraphs, DocumentClassConstPtr docclass)
485 // This used to need to be static to avoid a memory leak. It no longer needs
486 // to be so, but the alternative is to construct a new one of these (with a
487 // new temporary directory, etc) every time, and then to destroy it. So maybe
488 // it's worth just keeping this one around.
490 static TempFile tempfile("clipboard.internal");
491 tempfile.setAutoRemove(false);
492 static Buffer * staticbuffer = theBufferList().newInternalBuffer(
493 tempfile.name().absFileName());
495 // These two things only really need doing the first time.
496 staticbuffer->setUnnamed(true);
497 staticbuffer->inset().setBuffer(*staticbuffer);
499 // Use a clone for the complicated stuff so that we do not need to clean
500 // up in order to avoid a crash.
501 Buffer * buffer = staticbuffer->cloneBufferOnly();
502 LASSERT(buffer, return 0);
504 // This needs doing every time.
505 // Since setDocumentClass() causes deletion of the old document class
506 // we need to reset all layout pointers in paragraphs (otherwise they
507 // would be dangling).
508 ParIterator const end = buffer->par_iterator_end();
509 for (ParIterator it = buffer->par_iterator_begin(); it != end; ++it) {
510 docstring const name = it->layout().name();
511 if (docclass->hasLayout(name))
512 it->setLayout((*docclass)[name]);
514 it->setPlainOrDefaultLayout(*docclass);
516 buffer->params().setDocumentClass(docclass);
518 // we will use pasteSelectionHelper to copy the paragraphs into the
519 // temporary Buffer, since it does a lot of things to fix them up.
520 DocIterator dit = doc_iterator_begin(buffer, &buffer->inset());
522 pasteSelectionHelper(dit, paragraphs, docclass, buffer, el);
528 void putClipboard(ParagraphList const & paragraphs,
529 DocumentClassConstPtr docclass, docstring const & plaintext)
531 Buffer * buffer = copyToTempBuffer(paragraphs, docclass);
532 if (!buffer) // already asserted in copyToTempBuffer()
535 // We don't want to produce images that are not used. Therefore,
536 // output formulas as MathML. Even if this is not understood by all
537 // applications, the number that can parse it should go up in the future.
538 buffer->params().html_math_output = BufferParams::MathML;
540 // Make sure MarkAsExporting is deleted before buffer is
542 // The Buffer is being used to export. This is necessary so that the
543 // updateMacros call will record the needed information.
544 MarkAsExporting mex(buffer);
546 buffer->updateBuffer(Buffer::UpdateMaster, OutputUpdate);
547 buffer->updateMacros();
548 buffer->updateMacroInstances(OutputUpdate);
553 if (buffer->write(oslyx))
557 odocstringstream oshtml;
558 OutputParams runparams(encodings.fromLyXName("utf8"));
559 // We do not need to produce images, etc.
560 runparams.dryrun = true;
561 // We are not interested in errors (bug 8866)
562 runparams.silent = true;
563 buffer->writeLyXHTMLSource(oshtml, runparams, Buffer::FullSource);
565 theClipboard().put(lyx, oshtml.str(), plaintext);
573 /// return true if the whole ParagraphList is deleted
574 static bool isFullyDeleted(ParagraphList const & pars)
576 pit_type const pars_size = static_cast<pit_type>(pars.size());
578 // check all paragraphs
579 for (pit_type pit = 0; pit < pars_size; ++pit) {
580 if (!pars[pit].empty()) // prevent assertion failure
581 if (!pars[pit].isDeleted(0, pars[pit].size()))
588 void copySelectionHelper(Buffer const & buf, Text const & text,
589 pit_type startpit, pit_type endpit,
590 int start, int end, DocumentClassConstPtr dc, CutStack & cutstack)
592 ParagraphList const & pars = text.paragraphs();
594 // In most of these cases, we can try to recover.
595 LASSERT(0 <= start, start = 0);
596 LASSERT(start <= pars[startpit].size(), start = pars[startpit].size());
597 LASSERT(0 <= end, end = 0);
598 LASSERT(end <= pars[endpit].size(), end = pars[endpit].size());
599 LASSERT(startpit != endpit || start <= end, return);
601 // Clone the paragraphs within the selection.
602 ParagraphList copy_pars(lyx::next(pars.begin(), startpit),
603 lyx::next(pars.begin(), endpit + 1));
605 // Remove the end of the last paragraph; afterwards, remove the
606 // beginning of the first paragraph. Keep this order - there may only
607 // be one paragraph! Do not track deletions here; this is an internal
608 // action not visible to the user
610 Paragraph & back = copy_pars.back();
611 back.eraseChars(end, back.size(), false);
612 Paragraph & front = copy_pars.front();
613 front.eraseChars(0, start, false);
615 ParagraphList::iterator it = copy_pars.begin();
616 ParagraphList::iterator it_end = copy_pars.end();
618 for (; it != it_end; ++it) {
619 // Since we have a copy of the paragraphs, the insets
620 // do not have a proper buffer reference. It makes
621 // sense to add them temporarily, because the
622 // operations below depend on that (acceptChanges included).
623 it->setBuffer(const_cast<Buffer &>(buf));
624 // PassThru paragraphs have the Language
625 // latex_language. This is invalid for others, so we
626 // need to change it to the buffer language.
627 if (it->isPassThru())
628 it->changeLanguage(buf.params(),
629 latex_language, buf.language());
632 // do not copy text (also nested in insets) which is marked as
633 // deleted, unless the whole selection was deleted
634 if (!isFullyDeleted(copy_pars))
635 acceptChanges(copy_pars, buf.params());
637 rejectChanges(copy_pars, buf.params());
640 // do some final cleanup now, to make sure that the paragraphs
641 // are not linked to something else.
642 it = copy_pars.begin();
643 for (; it != it_end; ++it) {
644 it->setBuffer(*static_cast<Buffer *>(0));
645 it->setInsetOwner(0);
648 cutstack.push(make_pair(copy_pars, dc));
658 void region(CursorSlice const & i1, CursorSlice const & i2,
659 Inset::row_type & r1, Inset::row_type & r2,
660 Inset::col_type & c1, Inset::col_type & c2)
662 Inset & p = i1.inset();
663 c1 = p.col(i1.idx());
664 c2 = p.col(i2.idx());
667 r1 = p.row(i1.idx());
668 r2 = p.row(i2.idx());
674 docstring grabAndEraseSelection(Cursor & cur)
676 if (!cur.selection())
678 docstring res = grabSelection(cur);
684 bool reduceSelectionToOneCell(Cursor & cur)
686 if (!cur.selection() || !cur.inMathed())
689 CursorSlice i1 = cur.selBegin();
690 CursorSlice i2 = cur.selEnd();
691 if (!i1.inset().asInsetMath())
694 // the easy case: do nothing if only one cell is selected
695 if (i1.idx() == i2.idx())
700 cur.top().pos() = cur.top().lastpos();
706 bool multipleCellsSelected(Cursor const & cur)
708 if (!cur.selection() || !cur.inMathed())
711 CursorSlice i1 = cur.selBegin();
712 CursorSlice i2 = cur.selEnd();
713 if (!i1.inset().asInsetMath())
716 if (i1.idx() == i2.idx())
723 void switchBetweenClasses(DocumentClassConstPtr oldone,
724 DocumentClassConstPtr newone, InsetText & in, ErrorList & errorlist)
728 LBUFERR(!in.paragraphs().empty());
729 if (oldone == newone)
732 DocumentClass const & oldtc = *oldone;
733 DocumentClass const & newtc = *newone;
736 ParIterator it = par_iterator_begin(in);
737 ParIterator end = par_iterator_end(in);
738 // for remembering which layouts we've had to add
739 set<docstring> newlayouts;
740 for (; it != end; ++it) {
741 docstring const name = it->layout().name();
743 // the pasted text will keep their own layout name. If this layout does
744 // not exist in the new document, it will behave like a standard layout.
745 bool const added_one = newtc.addLayoutIfNeeded(name);
747 newlayouts.insert(name);
749 if (added_one || newlayouts.find(name) != newlayouts.end()) {
751 docstring const s = bformat(_("Layout `%1$s' was not found."), name);
753 ErrorItem(_("Layout Not Found"), s, it->id(), 0, it->size()));
756 if (in.usePlainLayout())
757 it->setLayout(newtc.plainLayout());
759 it->setLayout(newtc[name]);
762 // character styles and hidden table cells
763 InsetIterator const i_end = inset_iterator_end(in);
764 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
765 InsetCode const code = it->lyxCode();
766 if (code == FLEX_CODE) {
767 // FIXME: Should we verify all InsetCollapsable?
768 docstring const layoutName = it->layoutName();
769 docstring const & n = newone->insetLayout(layoutName).name();
770 bool const is_undefined = n.empty() ||
771 n == DocumentClass::plainInsetLayout().name();
775 // The flex inset is undefined in newtc
776 docstring const oldname = from_utf8(oldtc.name());
777 docstring const newname = from_utf8(newtc.name());
779 if (oldname == newname)
780 s = bformat(_("Flex inset %1$s is undefined after "
781 "reloading `%2$s' layout."), layoutName, oldname);
783 s = bformat(_("Flex inset %1$s is undefined because of "
784 "conversion from `%2$s' layout to `%3$s'."),
785 layoutName, oldname, newname);
786 // To warn the user that something had to be done.
787 errorlist.push_back(ErrorItem(
788 _("Undefined flex inset"),
789 s, it.paragraph().id(), it.pos(), it.pos() + 1));
790 } else if (code == TABULAR_CODE) {
791 // The recursion above does not catch paragraphs in "hidden" cells,
792 // i.e., ones that are part of a multirow or multicolum. So we need
793 // to handle those separately.
794 // This is the cause of bug #9049.
795 InsetTabular * table = it->asInsetTabular();
796 table->setLayoutForHiddenCells(newtc);
802 vector<docstring> availableSelections(Buffer const * buf)
804 vector<docstring> selList;
808 CutStack::const_iterator cit = theCuts.begin();
809 CutStack::const_iterator end = theCuts.end();
810 for (; cit != end; ++cit) {
811 // we do not use cit-> here because gcc 2.9x does not
813 ParagraphList const & pars = (*cit).first;
815 ParagraphList::const_iterator pit = pars.begin();
816 ParagraphList::const_iterator pend = pars.end();
817 for (; pit != pend; ++pit) {
818 Paragraph par(*pit, 0, 46);
819 // adapt paragraph to current buffer.
820 par.setBuffer(const_cast<Buffer &>(*buf));
821 textSel += par.asString(AS_STR_INSETS);
822 if (textSel.size() > 45) {
823 support::truncateWithEllipsis(textSel,45);
827 selList.push_back(textSel);
834 size_type numberOfSelections()
836 return theCuts.size();
840 void cutSelection(Cursor & cur, bool doclear, bool realcut)
842 // This doesn't make sense, if there is no selection
843 if (!cur.selection())
846 // OK, we have a selection. This is always between cur.selBegin()
849 if (cur.inTexted()) {
850 Text * text = cur.text();
855 // make sure that the depth behind the selection are restored, too
856 cur.recordUndoSelection();
857 pit_type begpit = cur.selBegin().pit();
858 pit_type endpit = cur.selEnd().pit();
860 int endpos = cur.selEnd().pos();
862 BufferParams const & bp = cur.buffer()->params();
864 copySelectionHelper(*cur.buffer(),
867 cur.selBegin().pos(), endpos,
868 bp.documentClassPtr(), theCuts);
869 // Stuff what we got on the clipboard.
870 // Even if there is no selection.
871 putClipboard(theCuts[0].first, theCuts[0].second,
872 cur.selectionAsString(true));
875 if (begpit != endpit)
876 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
878 tie(endpit, endpos) =
879 eraseSelectionHelper(bp, text->paragraphs(), begpit, endpit,
880 cur.selBegin().pos(), endpos);
882 // cutSelection can invalidate the cursor so we need to set
884 // we prefer the end for when tracking changes
888 // sometimes necessary
890 && text->paragraphs()[begpit].stripLeadingSpaces(bp.track_changes))
893 // need a valid cursor. (Lgb)
894 cur.clearSelection();
896 // After a cut operation, we must make sure that the Buffer is updated
897 // because some further operation might need updated label information for
898 // example. So we cannot just use "cur.forceBufferUpdate()" here.
900 cur.buffer()->updateBuffer();
902 // tell tabular that a recent copy happened
903 dirtyTabularStack(false);
906 if (cur.inMathed()) {
907 if (cur.selBegin().idx() != cur.selEnd().idx()) {
908 // The current selection spans more than one cell.
910 cur.recordUndoInset();
912 // Record only the current cell to avoid a jumping
923 void copySelection(Cursor const & cur)
925 copySelection(cur, cur.selectionAsString(true));
929 void copyInset(Cursor const & cur, Inset * inset, docstring const & plaintext)
933 BufferParams const & bp = cur.buffer()->params();
934 par.setLayout(bp.documentClass().plainLayout());
935 Font font(inherit_font, bp.language);
936 par.insertInset(0, inset, font, Change(Change::UNCHANGED));
938 theCuts.push(make_pair(pars, bp.documentClassPtr()));
940 // stuff the selection onto the X clipboard, from an explicit copy request
941 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
947 void copySelectionToStack(Cursor const & cur, CutStack & cutstack)
949 // this doesn't make sense, if there is no selection
950 if (!cur.selection())
953 // copySelection can not yet handle the case of cross idx selection
954 if (cur.selBegin().idx() != cur.selEnd().idx())
957 if (cur.inTexted()) {
958 Text * text = cur.text();
960 // ok we have a selection. This is always between cur.selBegin()
961 // and sel_end cursor
962 copySelectionHelper(*cur.buffer(), *text,
963 cur.selBegin().pit(), cur.selEnd().pit(),
964 cur.selBegin().pos(), cur.selEnd().pos(),
965 cur.buffer()->params().documentClassPtr(),
967 // Reset the dirty_tabular_stack_ flag only when something
968 // is copied to the clipboard (not to the selectionBuffer).
969 if (&cutstack == &theCuts)
970 dirtyTabularStack(false);
973 if (cur.inMathed()) {
974 //lyxerr << "copySelection in mathed" << endl;
977 BufferParams const & bp = cur.buffer()->params();
978 // FIXME This should be the plain layout...right?
979 par.setLayout(bp.documentClass().plainLayout());
980 par.insert(0, grabSelection(cur), Font(), Change(Change::UNCHANGED));
982 cutstack.push(make_pair(pars, bp.documentClassPtr()));
989 void copySelectionToStack()
991 if (!selectionBuffer.empty())
992 theCuts.push(selectionBuffer[0]);
996 void copySelection(Cursor const & cur, docstring const & plaintext)
998 // In tablemode, because copy and paste actually use special table stack
999 // we do not attempt to get selected paragraphs under cursor. Instead, a
1000 // paragraph with the plain text version is generated so that table cells
1001 // can be pasted as pure text somewhere else.
1002 if (cur.selBegin().idx() != cur.selEnd().idx()) {
1005 BufferParams const & bp = cur.buffer()->params();
1006 par.setLayout(bp.documentClass().plainLayout());
1007 par.insert(0, plaintext, Font(), Change(Change::UNCHANGED));
1008 pars.push_back(par);
1009 theCuts.push(make_pair(pars, bp.documentClassPtr()));
1011 copySelectionToStack(cur, theCuts);
1014 // stuff the selection onto the X clipboard, from an explicit copy request
1015 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
1019 void saveSelection(Cursor const & cur)
1021 // This function is called, not when a selection is formed, but when
1022 // a selection is cleared. Therefore, multiple keyboard selection
1023 // will not repeatively trigger this function (bug 3877).
1025 && cur.selBegin() == cur.bv().cursor().selBegin()
1026 && cur.selEnd() == cur.bv().cursor().selEnd()) {
1027 LYXERR(Debug::SELECTION, "saveSelection: '" << cur.selectionAsString(true) << "'");
1028 copySelectionToStack(cur, selectionBuffer);
1035 return !selectionBuffer.empty();
1039 void clearSelection()
1041 selectionBuffer.clear();
1045 void clearCutStack()
1051 docstring selection(size_t sel_index, DocumentClassConstPtr docclass)
1053 if (sel_index >= theCuts.size())
1056 unique_ptr<Buffer> buffer(copyToTempBuffer(theCuts[sel_index].first,
1061 return buffer->paragraphs().back().asString(AS_STR_INSETS | AS_STR_NEWLINES);
1065 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
1066 DocumentClassConstPtr docclass, ErrorList & errorList)
1068 if (cur.inTexted()) {
1069 Text * text = cur.text();
1072 PasteReturnValue prv =
1073 pasteSelectionHelper(cur, parlist, docclass, 0, errorList);
1074 cur.forceBufferUpdate();
1075 cur.clearSelection();
1076 text->setCursor(cur, prv.pit, prv.pos);
1079 // mathed is handled in InsetMathNest/InsetMathGrid
1080 LATTEST(!cur.inMathed());
1084 bool pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
1086 // this does not make sense, if there is nothing to paste
1087 if (!checkPastePossible(sel_index))
1091 pasteParagraphList(cur, theCuts[sel_index].first,
1092 theCuts[sel_index].second, errorList);
1097 bool pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs,
1098 Clipboard::TextType type)
1100 // Use internal clipboard if it is the most recent one
1101 // This overrides asParagraphs and type on purpose!
1102 if (theClipboard().isInternal())
1103 return pasteFromStack(cur, errorList, 0);
1105 // First try LyX format
1106 if ((type == Clipboard::LyXTextType ||
1107 type == Clipboard::LyXOrPlainTextType ||
1108 type == Clipboard::AnyTextType) &&
1109 theClipboard().hasTextContents(Clipboard::LyXTextType)) {
1110 string lyx = theClipboard().getAsLyX();
1112 // For some strange reason gcc 3.2 and 3.3 do not accept
1113 // Buffer buffer(string(), false);
1114 Buffer buffer("", false);
1115 buffer.setUnnamed(true);
1116 if (buffer.readString(lyx)) {
1118 pasteParagraphList(cur, buffer.paragraphs(),
1119 buffer.params().documentClassPtr(), errorList);
1125 // Then try TeX and HTML
1126 Clipboard::TextType types[2] = {Clipboard::HtmlTextType, Clipboard::LaTeXTextType};
1127 string names[2] = {"html", "latexclipboard"};
1128 for (int i = 0; i < 2; ++i) {
1129 if (type != types[i] && type != Clipboard::AnyTextType)
1131 bool available = theClipboard().hasTextContents(types[i]);
1133 // If a specific type was explicitly requested, try to
1134 // interpret plain text: The user told us that the clipboard
1135 // contents is in the desired format
1136 if (!available && type == types[i]) {
1137 types[i] = Clipboard::PlainTextType;
1138 available = theClipboard().hasTextContents(types[i]);
1142 docstring text = theClipboard().getAsText(types[i]);
1143 available = !text.empty();
1145 // For some strange reason gcc 3.2 and 3.3 do not accept
1146 // Buffer buffer(string(), false);
1147 Buffer buffer("", false);
1148 buffer.setUnnamed(true);
1149 available = buffer.importString(names[i], text, errorList);
1151 available = !buffer.paragraphs().empty();
1152 if (available && !buffer.paragraphs()[0].empty()) {
1154 pasteParagraphList(cur, buffer.paragraphs(),
1155 buffer.params().documentClassPtr(), errorList);
1162 // Then try plain text
1163 docstring const text = theClipboard().getAsText(Clipboard::PlainTextType);
1168 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1170 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1171 cur.forceBufferUpdate();
1176 void pasteSimpleText(Cursor & cur, bool asParagraphs)
1179 // Use internal clipboard if it is the most recent one
1180 if (theClipboard().isInternal()) {
1181 if (!checkPastePossible(0))
1184 ParagraphList const & pars = theCuts[0].first;
1185 ParagraphList::const_iterator it = pars.begin();
1186 for (; it != pars.end(); ++it) {
1187 if (it != pars.begin())
1189 text += (*it).asString();
1191 asParagraphs = false;
1193 // Then try plain text
1194 text = theClipboard().getAsText(Clipboard::PlainTextType);
1201 cutSelection(cur, true, false);
1203 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1205 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1209 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
1210 Clipboard::GraphicsType preferedType)
1212 LASSERT(theClipboard().hasGraphicsContents(preferedType), return);
1214 // get picture from clipboard
1215 FileName filename = theClipboard().getAsGraphics(cur, preferedType);
1216 if (filename.empty())
1219 // create inset for graphic
1220 InsetGraphics * inset = new InsetGraphics(cur.buffer());
1221 InsetGraphicsParams params;
1222 params.filename = support::DocFileName(filename.absFileName(), false);
1223 inset->setParams(params);
1229 void pasteSelection(Cursor & cur, ErrorList & errorList)
1231 if (selectionBuffer.empty())
1234 pasteParagraphList(cur, selectionBuffer[0].first,
1235 selectionBuffer[0].second, errorList);
1239 void replaceSelectionWithString(Cursor & cur, docstring const & str)
1242 DocIterator selbeg = cur.selectionBegin();
1244 // Get font setting before we cut, we need a copy here, not a bare reference.
1246 selbeg.paragraph().getFontSettings(cur.buffer()->params(), selbeg.pos());
1248 // Insert the new string
1249 pos_type pos = cur.selEnd().pos();
1250 Paragraph & par = cur.selEnd().paragraph();
1251 docstring::const_iterator cit = str.begin();
1252 docstring::const_iterator end = str.end();
1253 for (; cit != end; ++cit, ++pos)
1254 par.insertChar(pos, *cit, font, cur.buffer()->params().track_changes);
1256 // Cut the selection
1257 cutSelection(cur, true, false);
1261 void replaceSelection(Cursor & cur)
1263 if (cur.selection())
1264 cutSelection(cur, true, false);
1268 void eraseSelection(Cursor & cur)
1270 //lyxerr << "cap::eraseSelection begin: " << cur << endl;
1271 CursorSlice const & i1 = cur.selBegin();
1272 CursorSlice const & i2 = cur.selEnd();
1273 if (!i1.asInsetMath()) {
1274 LYXERR0("Can't erase this selection");
1280 InsetMath * p = i1.asInsetMath();
1281 if (i1.idx() == i2.idx()) {
1282 i1.cell().erase(i1.pos(), i2.pos());
1283 // We may have deleted i1.cell(cur.pos()).
1284 // Make sure that pos is valid.
1285 if (cur.pos() > cur.lastpos())
1286 cur.pos() = cur.lastpos();
1287 } else if (p->nrows() > 0 && p->ncols() > 0) {
1288 // This is a grid, delete a nice square region
1289 Inset::row_type r1, r2;
1290 Inset::col_type c1, c2;
1291 region(i1, i2, r1, r2, c1, c2);
1292 for (Inset::row_type row = r1; row <= r2; ++row)
1293 for (Inset::col_type col = c1; col <= c2; ++col)
1294 p->cell(p->index(row, col)).clear();
1295 // We've deleted the whole cell. Only pos 0 is valid.
1298 Inset::idx_type idx1 = i1.idx();
1299 Inset::idx_type idx2 = i2.idx();
1302 for (Inset::idx_type idx = idx1 ; idx <= idx2; ++idx)
1303 p->cell(idx).clear();
1304 // We've deleted the whole cell. Only pos 0 is valid.
1308 // need a valid cursor. (Lgb)
1309 cur.clearSelection();
1310 //lyxerr << "cap::eraseSelection end: " << cur << endl;
1314 void selDel(Cursor & cur)
1316 //lyxerr << "cap::selDel" << endl;
1317 if (cur.selection())
1318 eraseSelection(cur);
1322 void selClearOrDel(Cursor & cur)
1324 //lyxerr << "cap::selClearOrDel" << endl;
1325 if (lyxrc.auto_region_delete)
1328 cur.selection(false);
1332 docstring grabSelection(Cursor const & cur)
1334 if (!cur.selection())
1338 // grab selection by glueing multiple cells together. This is not what
1339 // we want because selections spanning multiple cells will get "&" and "\\"
1342 for (DocIterator dit = cur.selectionBegin();
1343 dit != cur.selectionEnd(); dit.forwardPos())
1344 os << asString(dit.cell());
1348 CursorSlice i1 = cur.selBegin();
1349 CursorSlice i2 = cur.selEnd();
1351 if (i1.idx() == i2.idx()) {
1352 if (i1.inset().asInsetMath()) {
1353 MathData::const_iterator it = i1.cell().begin();
1354 Buffer * buf = cur.buffer();
1355 return asString(MathData(buf, it + i1.pos(), it + i2.pos()));
1357 return from_ascii("unknown selection 1");
1361 Inset::row_type r1, r2;
1362 Inset::col_type c1, c2;
1363 region(i1, i2, r1, r2, c1, c2);
1366 if (i1.inset().asInsetMath()) {
1367 for (Inset::row_type row = r1; row <= r2; ++row) {
1370 for (Inset::col_type col = c1; col <= c2; ++col) {
1373 data += asString(i1.asInsetMath()->
1374 cell(i1.asInsetMath()->index(row, col)));
1378 data = from_ascii("unknown selection 2");
1384 void dirtyTabularStack(bool b)
1386 dirty_tabular_stack_ = b;
1390 bool tabularStackDirty()
1392 return dirty_tabular_stack_;