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/TempFile.h"
65 #include "frontends/alert.h"
66 #include "frontends/Clipboard.h"
67 #include "frontends/Selection.h"
69 #include <boost/tuple/tuple.hpp>
70 #include <boost/next_prior.hpp>
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_par, pos_type r_pos, bool r_nu) :
104 par(r_par), 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 = cur.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);
173 } else { // check if we need to reset from plain layout
174 Layout const & defaultLayout = newDocClass->defaultLayout();
175 Layout const & plainLayout = newDocClass->plainLayout();
176 ParagraphList::iterator const end = insertion.end();
177 ParagraphList::iterator par = insertion.begin();
178 for (; par != end; ++par) {
179 Layout const & parLayout = par->layout();
180 if (parLayout == plainLayout)
181 par->setLayout(defaultLayout);
185 InsetText in(cur.buffer());
186 // Make sure there is no class difference.
187 in.paragraphs().clear();
188 // This works without copying any paragraph data because we have
189 // a specialized swap method for ParagraphList. This is important
190 // since we store pointers to insets at some places and we don't
191 // want to invalidate them.
192 insertion.swap(in.paragraphs());
193 cap::switchBetweenClasses(oldDocClass, newDocClass, in, errorlist);
194 insertion.swap(in.paragraphs());
196 ParagraphList::iterator tmpbuf = insertion.begin();
197 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
199 depth_type max_depth = pars[pit].getMaxDepthAfter();
201 for (; tmpbuf != insertion.end(); ++tmpbuf) {
202 // If we have a negative jump so that the depth would
203 // go below 0 depth then we have to redo the delta to
204 // this new max depth level so that subsequent
205 // paragraphs are aligned correctly to this paragraph
207 if (int(tmpbuf->params().depth()) + depth_delta < 0)
210 // Set the right depth so that we are not too deep or shallow.
211 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
212 if (tmpbuf->params().depth() > max_depth)
213 tmpbuf->params().depth(max_depth);
215 // Set max_depth for the next paragraph
216 max_depth = tmpbuf->getMaxDepthAfter();
218 // Set the inset owner of this paragraph.
219 tmpbuf->setInsetOwner(target_inset);
220 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
221 // do not track deletion of invalid insets
222 if (Inset * inset = tmpbuf->getInset(i))
223 if (!target_inset->insetAllowed(inset->lyxCode()))
224 tmpbuf->eraseChar(i--, false);
227 tmpbuf->setChange(Change(buffer.params().track_changes ?
228 Change::INSERTED : Change::UNCHANGED));
231 bool const empty = pars[pit].empty();
233 // Make the buf exactly the same layout as the cursor
235 insertion.begin()->makeSameLayout(pars[pit]);
238 // Prepare the paragraphs and insets for insertion.
239 insertion.swap(in.paragraphs());
241 InsetIterator const i_end = inset_iterator_end(in);
242 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
243 // Even though this will also be done later, it has to be done here
244 // since some inset might going to try to access
245 // the buffer() member.
246 it->setBuffer(const_cast<Buffer &>(buffer));
247 switch (it->lyxCode()) {
249 case MATH_HULL_CODE: {
250 // check for equation labels and resolve duplicates
251 InsetMathHull * ins = it->asInsetMath()->asHullInset();
252 std::vector<InsetLabel *> labels = ins->getLabels();
253 for (size_t i = 0; i != labels.size(); ++i) {
256 InsetLabel * lab = labels[i];
257 docstring const oldname = lab->getParam("name");
258 lab->updateLabel(oldname);
259 // We need to update the buffer reference cache.
261 docstring const newname = lab->getParam("name");
262 if (oldname == newname)
264 // adapt the references
265 for (InsetIterator itt = inset_iterator_begin(in);
266 itt != i_end; ++itt) {
267 if (itt->lyxCode() == REF_CODE) {
268 InsetCommand * ref = itt->asInsetCommand();
269 if (ref->getParam("reference") == oldname)
270 ref->setParam("reference", newname);
271 } else if (itt->lyxCode() == MATH_REF_CODE) {
272 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
273 // this is necessary to prevent an uninitialized
274 // buffer when the RefInset is in a MathBox.
275 // FIXME audit setBuffer calls
276 mi->setBuffer(const_cast<Buffer &>(buffer));
277 if (mi->getTarget() == oldname)
278 mi->changeTarget(newname);
286 // check for duplicates
287 InsetLabel & lab = static_cast<InsetLabel &>(*it);
288 docstring const oldname = lab.getParam("name");
289 lab.updateLabel(oldname);
290 // We need to update the buffer reference cache.
292 docstring const newname = lab.getParam("name");
293 if (oldname == newname)
295 // adapt the references
296 for (InsetIterator itt = inset_iterator_begin(in); itt != i_end; ++itt) {
297 if (itt->lyxCode() == REF_CODE) {
298 InsetCommand & ref = static_cast<InsetCommand &>(*itt);
299 if (ref.getParam("reference") == oldname)
300 ref.setParam("reference", newname);
301 } else if (itt->lyxCode() == MATH_REF_CODE) {
302 InsetMathRef * mi = itt->asInsetMath()->asRefInset();
303 // this is necessary to prevent an uninitialized
304 // buffer when the RefInset is in a MathBox.
305 // FIXME audit setBuffer calls
306 mi->setBuffer(const_cast<Buffer &>(buffer));
307 if (mi->getTarget() == oldname)
308 mi->changeTarget(newname);
315 InsetInclude & inc = static_cast<InsetInclude &>(*it);
317 // We need to update the list of included files.
323 // check for duplicates
324 InsetBibitem & bib = static_cast<InsetBibitem &>(*it);
325 docstring const oldkey = bib.getParam("key");
326 bib.updateCommand(oldkey, false);
327 // We need to update the buffer reference cache.
329 docstring const newkey = bib.getParam("key");
330 if (oldkey == newkey)
332 // adapt the references
333 for (InsetIterator itt = inset_iterator_begin(in);
334 itt != i_end; ++itt) {
335 if (itt->lyxCode() == CITE_CODE) {
336 InsetCommand * ref = itt->asInsetCommand();
337 if (ref->getParam("key") == oldkey)
338 ref->setParam("key", newkey);
345 // check if branch is known to target buffer
347 InsetBranch & br = static_cast<InsetBranch &>(*it);
348 docstring const name = br.branch();
351 bool const is_child = (&buffer != buffer.masterBuffer());
352 BranchList branchlist = buffer.params().branchlist();
353 if ((!is_child && branchlist.find(name))
354 || (is_child && (branchlist.find(name)
355 || buffer.masterBuffer()->params().branchlist().find(name))))
358 // This is for a temporary buffer, so simply create the branch.
359 // Must not use lyx::dispatch(), since tmpbuffer has no view.
361 tmpbuffer->dispatch(FuncRequest(LFUN_BRANCH_ADD, name), dr);
363 docstring text = bformat(
364 _("The pasted branch \"%1$s\" is undefined.\n"
365 "Do you want to add it to the document's branch list?"),
367 if (frontend::Alert::prompt(_("Unknown branch"),
368 text, 0, 1, _("&Add"), _("&Don't Add")) != 0)
370 lyx::dispatch(FuncRequest(LFUN_BRANCH_ADD, name));
372 // We need to update the list of branches.
381 insertion.swap(in.paragraphs());
383 // Split the paragraph for inserting the buf if necessary.
385 breakParagraphConservative(buffer.params(), pars, pit, pos);
389 pars.insert(boost::next(pars.begin(), pit),
393 // merge the empty par with the last par of the insertion
394 mergeParagraph(buffer.params(), pars,
395 pit + insertion.size() - 1);
397 pars.insert(boost::next(pars.begin(), pit + 1),
401 // merge the first par of the insertion with the current par
402 mergeParagraph(buffer.params(), pars, pit);
405 // Store the new cursor position.
406 pit_type last_paste = pit + insertion.size() - 1;
407 pit_type startpit = pit;
409 pos = pars[last_paste].size();
411 // FIXME Should we do it here, or should we let updateBuffer() do it?
412 // Set paragraph buffers. It's important to do this right away
413 // before something calls Inset::buffer() and causes a crash.
414 for (pit_type p = startpit; p <= pit; ++p)
415 pars[p].setBuffer(const_cast<Buffer &>(buffer));
417 // Join (conditionally) last pasted paragraph with next one, i.e.,
418 // the tail of the spliced document paragraph
419 if (!empty && last_paste + 1 != pit_type(pars.size())) {
420 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
421 mergeParagraph(buffer.params(), pars, last_paste);
422 } else if (pars[last_paste + 1].empty()) {
423 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
424 mergeParagraph(buffer.params(), pars, last_paste);
425 } else if (pars[last_paste].empty()) {
426 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
427 mergeParagraph(buffer.params(), pars, last_paste);
429 pars[last_paste + 1].stripLeadingSpaces(buffer.params().track_changes);
434 return PasteReturnValue(pit, pos, need_update);
438 PitPosPair eraseSelectionHelper(BufferParams const & params,
439 ParagraphList & pars,
440 pit_type startpit, pit_type endpit,
441 int startpos, int endpos)
443 // Start of selection is really invalid.
444 if (startpit == pit_type(pars.size()) ||
445 (startpos > pars[startpit].size()))
446 return PitPosPair(endpit, endpos);
448 // Start and end is inside same paragraph
449 if (endpit == pit_type(pars.size()) || startpit == endpit) {
450 endpos -= pars[startpit].eraseChars(startpos, endpos, params.track_changes);
451 return PitPosPair(endpit, endpos);
454 for (pit_type pit = startpit; pit != endpit + 1;) {
455 pos_type const left = (pit == startpit ? startpos : 0);
456 pos_type right = (pit == endpit ? endpos : pars[pit].size() + 1);
457 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.track_changes);
459 // Logically erase only, including the end-of-paragraph character
460 pars[pit].eraseChars(left, right, params.track_changes);
462 // Separate handling of paragraph break:
463 if (merge && pit != endpit &&
465 || pars[pit].hasSameLayout(pars[endpit])
466 || pars[endpit].size() == endpos)) {
467 if (pit + 1 == endpit)
468 endpos += pars[pit].size();
469 mergeParagraph(params, pars, pit);
475 // Ensure legal cursor pos:
478 return PitPosPair(endpit, endpos);
482 void putClipboard(ParagraphList const & paragraphs,
483 DocumentClassConstPtr docclass, docstring const & plaintext)
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);
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);
524 // We don't want to produce images that are not used. Therefore,
525 // output formulas as MathML. Even if this is not understood by all
526 // applications, the number that can parse it should go up in the future.
527 buffer->params().html_math_output = BufferParams::MathML;
529 // Make sure MarkAsExporting is deleted before buffer is
531 // The Buffer is being used to export. This is necessary so that the
532 // updateMacros call will record the needed information.
533 MarkAsExporting mex(buffer);
535 buffer->updateBuffer(Buffer::UpdateMaster, OutputUpdate);
536 buffer->updateMacros();
537 buffer->updateMacroInstances(OutputUpdate);
542 if (buffer->write(oslyx))
546 odocstringstream oshtml;
547 OutputParams runparams(encodings.fromLyXName("utf8"));
548 // We do not need to produce images, etc.
549 runparams.dryrun = true;
550 // We are not interested in errors (bug 8866)
551 runparams.silent = true;
552 buffer->writeLyXHTMLSource(oshtml, runparams, Buffer::FullSource);
554 theClipboard().put(lyx, oshtml.str(), plaintext);
562 /// return true if the whole ParagraphList is deleted
563 static bool isFullyDeleted(ParagraphList const & pars)
565 pit_type const pars_size = static_cast<pit_type>(pars.size());
567 // check all paragraphs
568 for (pit_type pit = 0; pit < pars_size; ++pit) {
569 if (!pars[pit].empty()) // prevent assertion failure
570 if (!pars[pit].isDeleted(0, pars[pit].size()))
577 void copySelectionHelper(Buffer const & buf, Text const & text,
578 pit_type startpit, pit_type endpit,
579 int start, int end, DocumentClassConstPtr dc, CutStack & cutstack)
581 ParagraphList const & pars = text.paragraphs();
583 // In most of these cases, we can try to recover.
584 LASSERT(0 <= start, start = 0);
585 LASSERT(start <= pars[startpit].size(), start = pars[startpit].size());
586 LASSERT(0 <= end, end = 0);
587 LASSERT(end <= pars[endpit].size(), end = pars[endpit].size());
588 LASSERT(startpit != endpit || start <= end, return);
590 // Clone the paragraphs within the selection.
591 ParagraphList copy_pars(boost::next(pars.begin(), startpit),
592 boost::next(pars.begin(), endpit + 1));
594 // Remove the end of the last paragraph; afterwards, remove the
595 // beginning of the first paragraph. Keep this order - there may only
596 // be one paragraph! Do not track deletions here; this is an internal
597 // action not visible to the user
599 Paragraph & back = copy_pars.back();
600 back.eraseChars(end, back.size(), false);
601 Paragraph & front = copy_pars.front();
602 front.eraseChars(0, start, false);
604 ParagraphList::iterator it = copy_pars.begin();
605 ParagraphList::iterator it_end = copy_pars.end();
607 for (; it != it_end; ++it) {
608 // Since we have a copy of the paragraphs, the insets
609 // do not have a proper buffer reference. It makes
610 // sense to add them temporarily, because the
611 // operations below depend on that (acceptChanges included).
612 it->setBuffer(const_cast<Buffer &>(buf));
613 // PassThru paragraphs have the Language
614 // latex_language. This is invalid for others, so we
615 // need to change it to the buffer language.
616 if (it->isPassThru())
617 it->changeLanguage(buf.params(),
618 latex_language, buf.language());
621 // do not copy text (also nested in insets) which is marked as
622 // deleted, unless the whole selection was deleted
623 if (!isFullyDeleted(copy_pars))
624 acceptChanges(copy_pars, buf.params());
626 rejectChanges(copy_pars, buf.params());
629 // do some final cleanup now, to make sure that the paragraphs
630 // are not linked to something else.
631 it = copy_pars.begin();
632 for (; it != it_end; ++it) {
633 it->setBuffer(*static_cast<Buffer *>(0));
634 it->setInsetOwner(0);
637 cutstack.push(make_pair(copy_pars, dc));
647 void region(CursorSlice const & i1, CursorSlice const & i2,
648 Inset::row_type & r1, Inset::row_type & r2,
649 Inset::col_type & c1, Inset::col_type & c2)
651 Inset & p = i1.inset();
652 c1 = p.col(i1.idx());
653 c2 = p.col(i2.idx());
656 r1 = p.row(i1.idx());
657 r2 = p.row(i2.idx());
663 docstring grabAndEraseSelection(Cursor & cur)
665 if (!cur.selection())
667 docstring res = grabSelection(cur);
673 bool reduceSelectionToOneCell(Cursor & cur)
675 if (!cur.selection() || !cur.inMathed())
678 CursorSlice i1 = cur.selBegin();
679 CursorSlice i2 = cur.selEnd();
680 if (!i1.inset().asInsetMath())
683 // the easy case: do nothing if only one cell is selected
684 if (i1.idx() == i2.idx())
689 cur.top().pos() = cur.top().lastpos();
695 bool multipleCellsSelected(Cursor const & cur)
697 if (!cur.selection() || !cur.inMathed())
700 CursorSlice i1 = cur.selBegin();
701 CursorSlice i2 = cur.selEnd();
702 if (!i1.inset().asInsetMath())
705 if (i1.idx() == i2.idx())
712 void switchBetweenClasses(DocumentClassConstPtr oldone,
713 DocumentClassConstPtr newone, InsetText & in, ErrorList & errorlist)
717 LBUFERR(!in.paragraphs().empty());
718 if (oldone == newone)
721 DocumentClass const & oldtc = *oldone;
722 DocumentClass const & newtc = *newone;
725 ParIterator it = par_iterator_begin(in);
726 ParIterator end = par_iterator_end(in);
727 // for remembering which layouts we've had to add
728 set<docstring> newlayouts;
729 for (; it != end; ++it) {
730 docstring const name = it->layout().name();
732 // the pasted text will keep their own layout name. If this layout does
733 // not exist in the new document, it will behave like a standard layout.
734 bool const added_one = newtc.addLayoutIfNeeded(name);
736 newlayouts.insert(name);
738 if (added_one || newlayouts.find(name) != newlayouts.end()) {
740 docstring const s = bformat(_("Layout `%1$s' was not found."), name);
742 ErrorItem(_("Layout Not Found"), s, it->id(), 0, it->size()));
745 if (in.usePlainLayout())
746 it->setLayout(newtc.plainLayout());
748 it->setLayout(newtc[name]);
751 // character styles and hidden table cells
752 InsetIterator const i_end = inset_iterator_end(in);
753 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
754 InsetCode const code = it->lyxCode();
755 if (code == FLEX_CODE) {
756 // FIXME: Should we verify all InsetCollapsable?
757 docstring const layoutName = it->layoutName();
758 docstring const & n = newone->insetLayout(layoutName).name();
759 bool const is_undefined = n.empty() ||
760 n == DocumentClass::plainInsetLayout().name();
764 // The flex inset is undefined in newtc
765 docstring const oldname = from_utf8(oldtc.name());
766 docstring const newname = from_utf8(newtc.name());
768 if (oldname == newname)
769 s = bformat(_("Flex inset %1$s is undefined after "
770 "reloading `%2$s' layout."), layoutName, oldname);
772 s = bformat(_("Flex inset %1$s is undefined because of "
773 "conversion from `%2$s' layout to `%3$s'."),
774 layoutName, oldname, newname);
775 // To warn the user that something had to be done.
776 errorlist.push_back(ErrorItem(
777 _("Undefined flex inset"),
778 s, it.paragraph().id(), it.pos(), it.pos() + 1));
779 } else if (code == TABULAR_CODE) {
780 // The recursion above does not catch paragraphs in "hidden" cells,
781 // i.e., ones that are part of a multirow or multicolum. So we need
782 // to handle those separately.
783 // This is the cause of bug #9049.
784 InsetTabular * table = it->asInsetTabular();
785 table->setLayoutForHiddenCells(newtc);
791 vector<docstring> availableSelections(Buffer const * buf)
793 vector<docstring> selList;
797 CutStack::const_iterator cit = theCuts.begin();
798 CutStack::const_iterator end = theCuts.end();
799 for (; cit != end; ++cit) {
800 // we do not use cit-> here because gcc 2.9x does not
802 ParagraphList const & pars = (*cit).first;
804 ParagraphList::const_iterator pit = pars.begin();
805 ParagraphList::const_iterator pend = pars.end();
806 for (; pit != pend; ++pit) {
807 Paragraph par(*pit, 0, 26);
808 // adapt paragraph to current buffer.
809 par.setBuffer(const_cast<Buffer &>(*buf));
810 asciiSel += par.asString(AS_STR_INSETS);
811 if (asciiSel.size() > 25) {
812 asciiSel.replace(22, docstring::npos,
818 selList.push_back(asciiSel);
825 size_type numberOfSelections()
827 return theCuts.size();
831 void cutSelection(Cursor & cur, bool doclear, bool realcut)
833 // This doesn't make sense, if there is no selection
834 if (!cur.selection())
837 // OK, we have a selection. This is always between cur.selBegin()
840 if (cur.inTexted()) {
841 Text * text = cur.text();
846 // make sure that the depth behind the selection are restored, too
847 cur.recordUndoSelection();
848 pit_type begpit = cur.selBegin().pit();
849 pit_type endpit = cur.selEnd().pit();
851 int endpos = cur.selEnd().pos();
853 BufferParams const & bp = cur.buffer()->params();
855 copySelectionHelper(*cur.buffer(),
858 cur.selBegin().pos(), endpos,
859 bp.documentClassPtr(), theCuts);
860 // Stuff what we got on the clipboard.
861 // Even if there is no selection.
862 putClipboard(theCuts[0].first, theCuts[0].second,
863 cur.selectionAsString(true));
866 if (begpit != endpit)
867 cur.screenUpdateFlags(Update::Force | Update::FitCursor);
869 boost::tie(endpit, endpos) =
870 eraseSelectionHelper(bp,
873 cur.selBegin().pos(), endpos);
875 // cutSelection can invalidate the cursor so we need to set
877 // we prefer the end for when tracking changes
881 // sometimes necessary
883 && text->paragraphs()[begpit].stripLeadingSpaces(bp.track_changes))
886 // need a valid cursor. (Lgb)
887 cur.clearSelection();
889 // After a cut operation, we must make sure that the Buffer is updated
890 // because some further operation might need updated label information for
891 // example. So we cannot just use "cur.forceBufferUpdate()" here.
893 cur.buffer()->updateBuffer();
895 // tell tabular that a recent copy happened
896 dirtyTabularStack(false);
899 if (cur.inMathed()) {
900 if (cur.selBegin().idx() != cur.selEnd().idx()) {
901 // The current selection spans more than one cell.
903 cur.recordUndoInset();
905 // Record only the current cell to avoid a jumping
916 void copySelection(Cursor const & cur)
918 copySelection(cur, cur.selectionAsString(true));
922 void copyInset(Cursor const & cur, Inset * inset, docstring const & plaintext)
926 BufferParams const & bp = cur.buffer()->params();
927 par.setLayout(bp.documentClass().plainLayout());
928 Font font(inherit_font, bp.language);
929 par.insertInset(0, inset, font, Change(Change::UNCHANGED));
931 theCuts.push(make_pair(pars, bp.documentClassPtr()));
933 // stuff the selection onto the X clipboard, from an explicit copy request
934 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
940 void copySelectionToStack(Cursor const & cur, CutStack & cutstack)
942 // this doesn't make sense, if there is no selection
943 if (!cur.selection())
946 // copySelection can not yet handle the case of cross idx selection
947 if (cur.selBegin().idx() != cur.selEnd().idx())
950 if (cur.inTexted()) {
951 Text * text = cur.text();
953 // ok we have a selection. This is always between cur.selBegin()
954 // and sel_end cursor
956 // copy behind a space if there is one
957 ParagraphList & pars = text->paragraphs();
958 pos_type pos = cur.selBegin().pos();
959 pit_type par = cur.selBegin().pit();
960 while (pos < pars[par].size() &&
961 pars[par].isLineSeparator(pos) &&
962 (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
965 copySelectionHelper(*cur.buffer(), *text, par, cur.selEnd().pit(),
966 pos, cur.selEnd().pos(),
967 cur.buffer()->params().documentClassPtr(), cutstack);
969 // Reset the dirty_tabular_stack_ flag only when something
970 // is copied to the clipboard (not to the selectionBuffer).
971 if (&cutstack == &theCuts)
972 dirtyTabularStack(false);
975 if (cur.inMathed()) {
976 //lyxerr << "copySelection in mathed" << endl;
979 BufferParams const & bp = cur.buffer()->params();
980 // FIXME This should be the plain layout...right?
981 par.setLayout(bp.documentClass().plainLayout());
982 par.insert(0, grabSelection(cur), Font(), Change(Change::UNCHANGED));
984 cutstack.push(make_pair(pars, bp.documentClassPtr()));
991 void copySelectionToStack()
993 if (!selectionBuffer.empty())
994 theCuts.push(selectionBuffer[0]);
998 void copySelection(Cursor const & cur, docstring const & plaintext)
1000 // In tablemode, because copy and paste actually use special table stack
1001 // we do not attempt to get selected paragraphs under cursor. Instead, a
1002 // paragraph with the plain text version is generated so that table cells
1003 // can be pasted as pure text somewhere else.
1004 if (cur.selBegin().idx() != cur.selEnd().idx()) {
1007 BufferParams const & bp = cur.buffer()->params();
1008 par.setLayout(bp.documentClass().plainLayout());
1009 par.insert(0, plaintext, Font(), Change(Change::UNCHANGED));
1010 pars.push_back(par);
1011 theCuts.push(make_pair(pars, bp.documentClassPtr()));
1013 copySelectionToStack(cur, theCuts);
1016 // stuff the selection onto the X clipboard, from an explicit copy request
1017 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
1021 void saveSelection(Cursor const & cur)
1023 // This function is called, not when a selection is formed, but when
1024 // a selection is cleared. Therefore, multiple keyboard selection
1025 // will not repeatively trigger this function (bug 3877).
1027 && cur.selBegin() == cur.bv().cursor().selBegin()
1028 && cur.selEnd() == cur.bv().cursor().selEnd()) {
1029 LYXERR(Debug::SELECTION, "saveSelection: '" << cur.selectionAsString(true) << "'");
1030 copySelectionToStack(cur, selectionBuffer);
1037 return !selectionBuffer.empty();
1041 void clearSelection()
1043 selectionBuffer.clear();
1047 void clearCutStack()
1053 docstring selection(size_t sel_index)
1055 return sel_index < theCuts.size()
1056 ? theCuts[sel_index].first.back().asString(AS_STR_INSETS | AS_STR_NEWLINES)
1061 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
1062 DocumentClassConstPtr docclass, ErrorList & errorList)
1064 if (cur.inTexted()) {
1065 Text * text = cur.text();
1068 PasteReturnValue prv =
1069 pasteSelectionHelper(cur, parlist, docclass, 0, errorList);
1070 cur.forceBufferUpdate();
1071 cur.clearSelection();
1072 text->setCursor(cur, prv.par, prv.pos);
1075 // mathed is handled in InsetMathNest/InsetMathGrid
1076 LATTEST(!cur.inMathed());
1080 bool pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
1082 // this does not make sense, if there is nothing to paste
1083 if (!checkPastePossible(sel_index))
1087 pasteParagraphList(cur, theCuts[sel_index].first,
1088 theCuts[sel_index].second, errorList);
1093 bool pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs,
1094 Clipboard::TextType type)
1096 // Use internal clipboard if it is the most recent one
1097 // This overrides asParagraphs and type on purpose!
1098 if (theClipboard().isInternal())
1099 return pasteFromStack(cur, errorList, 0);
1101 // First try LyX format
1102 if ((type == Clipboard::LyXTextType ||
1103 type == Clipboard::LyXOrPlainTextType ||
1104 type == Clipboard::AnyTextType) &&
1105 theClipboard().hasTextContents(Clipboard::LyXTextType)) {
1106 string lyx = theClipboard().getAsLyX();
1108 // For some strange reason gcc 3.2 and 3.3 do not accept
1109 // Buffer buffer(string(), false);
1110 Buffer buffer("", false);
1111 buffer.setUnnamed(true);
1112 if (buffer.readString(lyx)) {
1114 pasteParagraphList(cur, buffer.paragraphs(),
1115 buffer.params().documentClassPtr(), errorList);
1121 // Then try TeX and HTML
1122 Clipboard::TextType types[2] = {Clipboard::HtmlTextType, Clipboard::LaTeXTextType};
1123 string names[2] = {"html", "latexclipboard"};
1124 for (int i = 0; i < 2; ++i) {
1125 if (type != types[i] && type != Clipboard::AnyTextType)
1127 bool available = theClipboard().hasTextContents(types[i]);
1129 // If a specific type was explicitly requested, try to
1130 // interpret plain text: The user told us that the clipboard
1131 // contents is in the desired format
1132 if (!available && type == types[i]) {
1133 types[i] = Clipboard::PlainTextType;
1134 available = theClipboard().hasTextContents(types[i]);
1138 docstring text = theClipboard().getAsText(types[i]);
1139 available = !text.empty();
1141 // For some strange reason gcc 3.2 and 3.3 do not accept
1142 // Buffer buffer(string(), false);
1143 Buffer buffer("", false);
1144 buffer.setUnnamed(true);
1145 available = buffer.importString(names[i], text, errorList);
1147 available = !buffer.paragraphs().empty();
1148 if (available && !buffer.paragraphs()[0].empty()) {
1150 pasteParagraphList(cur, buffer.paragraphs(),
1151 buffer.params().documentClassPtr(), errorList);
1158 // Then try plain text
1159 docstring const text = theClipboard().getAsText(Clipboard::PlainTextType);
1164 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1166 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1171 void pasteSimpleText(Cursor & cur, bool asParagraphs)
1174 // Use internal clipboard if it is the most recent one
1175 if (theClipboard().isInternal()) {
1176 if (!checkPastePossible(0))
1179 ParagraphList const & pars = theCuts[0].first;
1180 ParagraphList::const_iterator it = pars.begin();
1181 for (; it != pars.end(); ++it) {
1182 if (it != pars.begin())
1184 text += (*it).asString();
1186 asParagraphs = false;
1188 // Then try plain text
1189 text = theClipboard().getAsText(Clipboard::PlainTextType);
1196 cutSelection(cur, true, false);
1198 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1200 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1204 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
1205 Clipboard::GraphicsType preferedType)
1207 LASSERT(theClipboard().hasGraphicsContents(preferedType), return);
1209 // get picture from clipboard
1210 FileName filename = theClipboard().getAsGraphics(cur, preferedType);
1211 if (filename.empty())
1214 // create inset for graphic
1215 InsetGraphics * inset = new InsetGraphics(cur.buffer());
1216 InsetGraphicsParams params;
1217 params.filename = support::DocFileName(filename.absFileName(), false);
1218 inset->setParams(params);
1224 void pasteSelection(Cursor & cur, ErrorList & errorList)
1226 if (selectionBuffer.empty())
1229 pasteParagraphList(cur, selectionBuffer[0].first,
1230 selectionBuffer[0].second, errorList);
1234 void replaceSelectionWithString(Cursor & cur, docstring const & str)
1237 DocIterator selbeg = cur.selectionBegin();
1239 // Get font setting before we cut, we need a copy here, not a bare reference.
1241 selbeg.paragraph().getFontSettings(cur.buffer()->params(), selbeg.pos());
1243 // Insert the new string
1244 pos_type pos = cur.selEnd().pos();
1245 Paragraph & par = cur.selEnd().paragraph();
1246 docstring::const_iterator cit = str.begin();
1247 docstring::const_iterator end = str.end();
1248 for (; cit != end; ++cit, ++pos)
1249 par.insertChar(pos, *cit, font, cur.buffer()->params().track_changes);
1251 // Cut the selection
1252 cutSelection(cur, true, false);
1256 void replaceSelection(Cursor & cur)
1258 if (cur.selection())
1259 cutSelection(cur, true, false);
1263 void eraseSelection(Cursor & cur)
1265 //lyxerr << "cap::eraseSelection begin: " << cur << endl;
1266 CursorSlice const & i1 = cur.selBegin();
1267 CursorSlice const & i2 = cur.selEnd();
1268 if (!i1.asInsetMath()) {
1269 LYXERR0("Can't erase this selection");
1275 InsetMath * p = i1.asInsetMath();
1276 if (i1.idx() == i2.idx()) {
1277 i1.cell().erase(i1.pos(), i2.pos());
1278 // We may have deleted i1.cell(cur.pos()).
1279 // Make sure that pos is valid.
1280 if (cur.pos() > cur.lastpos())
1281 cur.pos() = cur.lastpos();
1282 } else if (p->nrows() > 0 && p->ncols() > 0) {
1283 // This is a grid, delete a nice square region
1284 Inset::row_type r1, r2;
1285 Inset::col_type c1, c2;
1286 region(i1, i2, r1, r2, c1, c2);
1287 for (Inset::row_type row = r1; row <= r2; ++row)
1288 for (Inset::col_type col = c1; col <= c2; ++col)
1289 p->cell(p->index(row, col)).clear();
1290 // We've deleted the whole cell. Only pos 0 is valid.
1293 Inset::idx_type idx1 = i1.idx();
1294 Inset::idx_type idx2 = i2.idx();
1297 for (Inset::idx_type idx = idx1 ; idx <= idx2; ++idx)
1298 p->cell(idx).clear();
1299 // We've deleted the whole cell. Only pos 0 is valid.
1303 // need a valid cursor. (Lgb)
1304 cur.clearSelection();
1305 //lyxerr << "cap::eraseSelection end: " << cur << endl;
1309 void selDel(Cursor & cur)
1311 //lyxerr << "cap::selDel" << endl;
1312 if (cur.selection())
1313 eraseSelection(cur);
1317 void selClearOrDel(Cursor & cur)
1319 //lyxerr << "cap::selClearOrDel" << endl;
1320 if (lyxrc.auto_region_delete)
1323 cur.setSelection(false);
1327 docstring grabSelection(Cursor const & cur)
1329 if (!cur.selection())
1333 // grab selection by glueing multiple cells together. This is not what
1334 // we want because selections spanning multiple cells will get "&" and "\\"
1337 for (DocIterator dit = cur.selectionBegin();
1338 dit != cur.selectionEnd(); dit.forwardPos())
1339 os << asString(dit.cell());
1343 CursorSlice i1 = cur.selBegin();
1344 CursorSlice i2 = cur.selEnd();
1346 if (i1.idx() == i2.idx()) {
1347 if (i1.inset().asInsetMath()) {
1348 MathData::const_iterator it = i1.cell().begin();
1349 Buffer * buf = cur.buffer();
1350 return asString(MathData(buf, it + i1.pos(), it + i2.pos()));
1352 return from_ascii("unknown selection 1");
1356 Inset::row_type r1, r2;
1357 Inset::col_type c1, c2;
1358 region(i1, i2, r1, r2, c1, c2);
1361 if (i1.inset().asInsetMath()) {
1362 for (Inset::row_type row = r1; row <= r2; ++row) {
1365 for (Inset::col_type col = c1; col <= c2; ++col) {
1368 data += asString(i1.asInsetMath()->
1369 cell(i1.asInsetMath()->index(row, col)));
1373 data = from_ascii("unknown selection 2");
1379 void dirtyTabularStack(bool b)
1381 dirty_tabular_stack_ = b;
1385 bool tabularStackDirty()
1387 return dirty_tabular_stack_;