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"
19 #include "buffer_funcs.h"
20 #include "bufferparams.h"
23 #include "errorlist.h"
24 #include "funcrequest.h"
26 #include "insetiterator.h"
32 #include "lyxtextclasslist.h"
33 #include "paragraph.h"
34 #include "paragraph_funcs.h"
35 #include "ParagraphParameters.h"
36 #include "ParagraphList_fwd.h"
37 #include "pariterator.h"
40 #include "insets/insetcharstyle.h"
41 #include "insets/insettabular.h"
43 #include "mathed/MathData.h"
44 #include "mathed/InsetMath.h"
45 #include "mathed/MathSupport.h"
47 #include "support/lstrings.h"
49 #include "frontends/Clipboard.h"
50 #include "frontends/Selection.h"
52 #include <boost/tuple/tuple.hpp>
59 using support::bformat;
60 using frontend::Clipboard;
72 typedef std::pair<pit_type, int> PitPosPair;
74 typedef limited_stack<pair<ParagraphList, textclass_type> > CutStack;
78 // store whether the tabular stack is newer than the normal copy stack
79 // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
80 // when we (hopefully) have a one-for-all paste mechanism.
81 bool dirty_tabular_stack_ = false;
84 void region(CursorSlice const & i1, CursorSlice const & i2,
85 InsetBase::row_type & r1, InsetBase::row_type & r2,
86 InsetBase::col_type & c1, InsetBase::col_type & c2)
88 InsetBase & p = i1.inset();
100 bool checkPastePossible(int index)
102 return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
106 pair<PitPosPair, pit_type>
107 pasteSelectionHelper(LCursor & cur, ParagraphList const & parlist,
108 textclass_type textclass, ErrorList & errorlist)
110 Buffer const & buffer = cur.buffer();
111 pit_type pit = cur.pit();
112 pos_type pos = cur.pos();
113 ParagraphList & pars = cur.text()->paragraphs();
116 return make_pair(PitPosPair(pit, pos), pit);
118 BOOST_ASSERT (pos <= pars[pit].size());
120 // Make a copy of the CaP paragraphs.
121 ParagraphList insertion = parlist;
122 textclass_type const tc = buffer.params().textclass;
124 // Now remove all out of the pars which is NOT allowed in the
125 // new environment and set also another font if that is required.
127 // Convert newline to paragraph break in ERT inset.
128 // This should not be here!
129 if (pars[pit].inInset() &&
130 pars[pit].inInset()->lyxCode() == InsetBase::ERT_CODE) {
131 for (ParagraphList::size_type i = 0; i < insertion.size(); ++i) {
132 for (pos_type j = 0; j < insertion[i].size(); ++j) {
133 if (insertion[i].isNewline(j)) {
134 // do not track deletion of newline
135 insertion[i].eraseChar(j, false);
136 breakParagraphConservative(
144 // If we are in an inset which returns forceDefaultParagraphs,
145 // set the paragraphs to default
146 if (cur.inset().forceDefaultParagraphs(cur.idx())) {
147 LyXLayout_ptr const layout =
148 buffer.params().getLyXTextClass().defaultLayout();
149 ParagraphList::iterator const end = insertion.end();
150 for (ParagraphList::iterator par = insertion.begin();
155 // Make sure there is no class difference.
157 // This works without copying any paragraph data because we have
158 // a specialized swap method for ParagraphList. This is important
159 // since we store pointers to insets at some places and we don't
160 // want to invalidate them.
161 insertion.swap(in.paragraphs());
162 cap::switchBetweenClasses(textclass, tc, in, errorlist);
163 insertion.swap(in.paragraphs());
165 ParagraphList::iterator tmpbuf = insertion.begin();
166 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
168 depth_type max_depth = pars[pit].getMaxDepthAfter();
170 for (; tmpbuf != insertion.end(); ++tmpbuf) {
171 // If we have a negative jump so that the depth would
172 // go below 0 depth then we have to redo the delta to
173 // this new max depth level so that subsequent
174 // paragraphs are aligned correctly to this paragraph
176 if (int(tmpbuf->params().depth()) + depth_delta < 0)
179 // Set the right depth so that we are not too deep or shallow.
180 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
181 if (tmpbuf->params().depth() > max_depth)
182 tmpbuf->params().depth(max_depth);
184 // Only set this from the 2nd on as the 2nd depends
185 // for maxDepth still on pit.
186 if (tmpbuf != insertion.begin())
187 max_depth = tmpbuf->getMaxDepthAfter();
189 // Set the inset owner of this paragraph.
190 tmpbuf->setInsetOwner(pars[pit].inInset());
191 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
192 if (tmpbuf->getChar(i) == Paragraph::META_INSET &&
193 !pars[pit].insetAllowed(tmpbuf->getInset(i)->lyxCode()))
194 // do not track deletion of invalid insets
195 tmpbuf->eraseChar(i--, false);
198 tmpbuf->setChange(Change(buffer.params().trackChanges ?
199 Change::INSERTED : Change::UNCHANGED));
202 bool const empty = pars[pit].empty();
204 // Make the buf exactly the same layout as the cursor
206 insertion.begin()->makeSameLayout(pars[pit]);
209 // Prepare the paragraphs and insets for insertion.
210 // A couple of insets store buffer references so need updating.
211 insertion.swap(in.paragraphs());
213 ParIterator fpit = par_iterator_begin(in);
214 ParIterator fend = par_iterator_end(in);
216 for (; fpit != fend; ++fpit) {
217 InsetList::const_iterator lit = fpit->insetlist.begin();
218 InsetList::const_iterator eit = fpit->insetlist.end();
220 for (; lit != eit; ++lit) {
221 switch (lit->inset->lyxCode()) {
222 case InsetBase::TABULAR_CODE: {
223 InsetTabular * it = static_cast<InsetTabular*>(lit->inset);
233 insertion.swap(in.paragraphs());
235 // Split the paragraph for inserting the buf if necessary.
237 breakParagraphConservative(buffer.params(), pars, pit, pos);
241 pars.insert(boost::next(pars.begin(), pit),
245 // merge the empty par with the last par of the insertion
246 mergeParagraph(buffer.params(), pars,
247 pit + insertion.size() - 1);
249 pars.insert(boost::next(pars.begin(), pit + 1),
253 // merge the first par of the insertion with the current par
254 mergeParagraph(buffer.params(), pars, pit);
257 pit_type last_paste = pit + insertion.size() - 1;
259 // Store the new cursor position.
261 pos = pars[last_paste].size();
263 // Join (conditionally) last pasted paragraph with next one, i.e.,
264 // the tail of the spliced document paragraph
265 if (!empty && last_paste + 1 != pit_type(pars.size())) {
266 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
267 mergeParagraph(buffer.params(), pars, last_paste);
268 } else if (pars[last_paste + 1].empty()) {
269 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
270 mergeParagraph(buffer.params(), pars, last_paste);
271 } else if (pars[last_paste].empty()) {
272 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
273 mergeParagraph(buffer.params(), pars, last_paste);
275 pars[last_paste + 1].stripLeadingSpaces(buffer.params().trackChanges);
280 return make_pair(PitPosPair(pit, pos), last_paste + 1);
284 PitPosPair eraseSelectionHelper(BufferParams const & params,
285 ParagraphList & pars,
286 pit_type startpit, pit_type endpit,
287 int startpos, int endpos, bool doclear)
289 // Start of selection is really invalid.
290 if (startpit == pit_type(pars.size()) ||
291 (startpos > pars[startpit].size()))
292 return PitPosPair(endpit, endpos);
294 // Start and end is inside same paragraph
295 if (endpit == pit_type(pars.size()) || startpit == endpit) {
296 endpos -= pars[startpit].eraseChars(startpos, endpos, params.trackChanges);
297 return PitPosPair(endpit, endpos);
300 for (pit_type pit = startpit; pit != endpit + 1;) {
301 pos_type const left = (pit == startpit ? startpos : 0);
302 pos_type const right = (pit == endpit ? endpos : pars[pit].size() + 1);
304 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.trackChanges);
306 // Logically erase only, including the end-of-paragraph character
307 pars[pit].eraseChars(left, right, params.trackChanges);
309 // Separate handling of paragraph break:
310 if (merge && pit != endpit &&
311 (pit + 1 != endpit || pars[pit].hasSameLayout(pars[pit + 1]))) {
312 pos_type const thissize = pars[pit].size();
314 pars[pit + 1].stripLeadingSpaces(params.trackChanges);
315 mergeParagraph(params, pars, pit);
323 // Ensure legal cursor pos:
326 return PitPosPair(endpit, endpos);
330 void putClipboard(ParagraphList const & paragraphs, textclass_type textclass,
331 docstring const & plaintext)
333 Buffer buffer(string(), false);
334 buffer.setUnnamed(true);
335 buffer.paragraphs() = paragraphs;
336 buffer.params().textclass = textclass;
337 std::ostringstream lyx;
338 if (buffer.write(lyx))
339 theClipboard().put(lyx.str(), plaintext);
341 theClipboard().put(string(), plaintext);
345 void copySelectionHelper(Buffer const & buf, ParagraphList & pars,
346 pit_type startpit, pit_type endpit,
347 int start, int end, textclass_type tc)
349 BOOST_ASSERT(0 <= start && start <= pars[startpit].size());
350 BOOST_ASSERT(0 <= end && end <= pars[endpit].size());
351 BOOST_ASSERT(startpit != endpit || start <= end);
353 // Clone the paragraphs within the selection.
354 ParagraphList paragraphs(boost::next(pars.begin(), startpit),
355 boost::next(pars.begin(), endpit + 1));
357 ParagraphList::iterator it = paragraphs.begin();
358 ParagraphList::iterator it_end = paragraphs.end();
360 for (; it != it_end; it++) {
361 // ERT paragraphs have the Language latex_language.
362 // This is invalid outside of ERT, so we need to change it
363 // to the buffer language.
364 if (it->ownerCode() == InsetBase::ERT_CODE) {
365 it->changeLanguage(buf.params(), latex_language,
368 it->setInsetOwner(0);
371 // Cut out the end of the last paragraph.
372 Paragraph & back = paragraphs.back();
373 // do not track deletion here; it is an internal action not visible to the user
374 back.eraseChars(end, back.size(), false);
376 // Cut out the begin of the first paragraph
377 Paragraph & front = paragraphs.front();
378 // again, do not track deletion
379 front.eraseChars(0, start, false);
381 theCuts.push(make_pair(paragraphs, tc));
391 docstring grabAndEraseSelection(LCursor & cur)
393 if (!cur.selection())
395 docstring res = grabSelection(cur);
401 void switchBetweenClasses(textclass_type c1, textclass_type c2,
402 InsetText & in, ErrorList & errorlist)
404 BOOST_ASSERT(!in.paragraphs().empty());
408 LyXTextClass const & tclass1 = textclasslist[c1];
409 LyXTextClass const & tclass2 = textclasslist[c2];
412 ParIterator end = par_iterator_end(in);
413 for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
414 string const name = it->layout()->name();
415 bool hasLayout = tclass2.hasLayout(name);
418 it->layout(tclass2[name]);
420 it->layout(tclass2.defaultLayout());
422 if (!hasLayout && name != tclass1.defaultLayoutName()) {
423 docstring const s = bformat(
424 _("Layout had to be changed from\n%1$s to %2$s\n"
425 "because of class conversion from\n%3$s to %4$s"),
426 from_utf8(name), from_utf8(it->layout()->name()),
427 from_utf8(tclass1.name()), from_utf8(tclass2.name()));
428 // To warn the user that something had to be done.
429 errorlist.push_back(ErrorItem(_("Changed Layout"), s,
436 InsetIterator const i_end = inset_iterator_end(in);
437 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
438 if (it->lyxCode() == InsetBase::CHARSTYLE_CODE) {
439 InsetCharStyle & inset =
440 static_cast<InsetCharStyle &>(*it);
441 string const name = inset.params().type;
442 CharStyles::iterator const found_cs =
443 tclass2.charstyle(name);
444 if (found_cs == tclass2.charstyles().end()) {
445 // The character style is undefined in tclass2
446 inset.setUndefined();
447 docstring const s = bformat(_(
448 "Character style %1$s is "
449 "undefined because of class "
450 "conversion from\n%2$s to %3$s"),
451 from_utf8(name), from_utf8(tclass1.name()),
452 from_utf8(tclass2.name()));
453 // To warn the user that something had to be done.
454 errorlist.push_back(ErrorItem(
455 _("Undefined character style"),
456 s, it.paragraph().id(), it.pos(), it.pos() + 1));
457 } else if (inset.undefined()) {
458 // The character style is undefined in
459 // tclass1 and is defined in tclass2
460 inset.setDefined(found_cs);
467 std::vector<docstring> const availableSelections(Buffer const & buffer)
469 vector<docstring> selList;
471 CutStack::const_iterator cit = theCuts.begin();
472 CutStack::const_iterator end = theCuts.end();
473 for (; cit != end; ++cit) {
474 // we do not use cit-> here because gcc 2.9x does not
476 ParagraphList const & pars = (*cit).first;
478 ParagraphList::const_iterator pit = pars.begin();
479 ParagraphList::const_iterator pend = pars.end();
480 for (; pit != pend; ++pit) {
481 asciiSel += pit->asString(buffer, false);
482 if (asciiSel.size() > 25) {
483 asciiSel.replace(22, docstring::npos,
489 selList.push_back(asciiSel);
496 size_type numberOfSelections()
498 return theCuts.size();
502 void cutSelection(LCursor & cur, bool doclear, bool realcut)
504 // This doesn't make sense, if there is no selection
505 if (!cur.selection())
508 // OK, we have a selection. This is always between cur.selBegin()
511 if (cur.inTexted()) {
512 LyXText * text = cur.text();
515 // make sure that the depth behind the selection are restored, too
516 recordUndoSelection(cur);
517 pit_type begpit = cur.selBegin().pit();
518 pit_type endpit = cur.selEnd().pit();
520 int endpos = cur.selEnd().pos();
522 BufferParams const & bp = cur.buffer().params();
524 copySelectionHelper(cur.buffer(),
527 cur.selBegin().pos(), endpos,
529 // Stuff what we got on the clipboard.
530 // Even if there is no selection.
531 putClipboard(theCuts[0].first, theCuts[0].second,
532 cur.selectionAsString(true));
535 boost::tie(endpit, endpos) =
536 eraseSelectionHelper(bp,
539 cur.selBegin().pos(), endpos,
542 // sometimes necessary
544 text->paragraphs()[begpit].stripLeadingSpaces(bp.trackChanges);
546 // cutSelection can invalidate the cursor so we need to set
548 // we prefer the end for when tracking changes
552 // need a valid cursor. (Lgb)
553 cur.clearSelection();
554 updateLabels(cur.buffer());
555 theSelection().haveSelection(false);
557 // tell tabular that a recent copy happened
558 dirtyTabularStack(false);
561 if (cur.inMathed()) {
562 if (cur.selBegin().idx() != cur.selEnd().idx()) {
563 // The current selection spans more than one cell.
565 recordUndoInset(cur);
567 // Record only the current cell to avoid a jumping
578 void copySelection(LCursor & cur)
580 copySelection(cur, cur.selectionAsString(true));
584 void copySelection(LCursor & cur, docstring const & plaintext)
586 copySelectionToStack(cur);
588 // stuff the selection onto the X clipboard, from an explicit copy request
589 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
593 void copySelectionToStack(LCursor & cur)
595 // this doesn't make sense, if there is no selection
596 if (!cur.selection())
599 if (cur.inTexted()) {
600 LyXText * text = cur.text();
602 // ok we have a selection. This is always between cur.selBegin()
603 // and sel_end cursor
605 // copy behind a space if there is one
606 ParagraphList & pars = text->paragraphs();
607 pos_type pos = cur.selBegin().pos();
608 pit_type par = cur.selBegin().pit();
609 while (pos < pars[par].size()
610 && pars[par].isLineSeparator(pos)
611 && (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
614 copySelectionHelper(cur.buffer(), pars, par, cur.selEnd().pit(),
615 pos, cur.selEnd().pos(), cur.buffer().params().textclass);
618 if (cur.inMathed()) {
619 //lyxerr << "copySelection in mathed" << endl;
622 BufferParams const & bp = cur.buffer().params();
623 par.layout(bp.getLyXTextClass().defaultLayout());
624 par.insert(0, grabSelection(cur), LyXFont(), Change(Change::UNCHANGED));
626 theCuts.push(make_pair(pars, bp.textclass));
628 // tell tabular that a recent copy happened
629 dirtyTabularStack(false);
633 docstring getSelection(Buffer const & buf, size_t sel_index)
635 return sel_index < theCuts.size()
636 ? theCuts[sel_index].first.back().asString(buf, false)
641 void pasteParagraphList(LCursor & cur, ParagraphList const & parlist,
642 textclass_type textclass, ErrorList & errorList)
644 if (cur.inTexted()) {
645 LyXText * text = cur.text();
651 boost::tie(ppp, endpit) =
652 pasteSelectionHelper(cur, parlist,
653 textclass, errorList);
654 updateLabels(cur.buffer());
655 cur.clearSelection();
656 text->setCursor(cur.top(), ppp.first, ppp.second);
659 // mathed is handled in InsetMathNest/InsetMathGrid
660 BOOST_ASSERT(!cur.inMathed());
664 void pasteClipboard(LCursor & cur, ErrorList & errorList, bool asParagraphs)
666 // Use internal clipboard if it is the most recent one
667 if (theClipboard().isInternal()) {
668 pasteSelection(cur, errorList, 0);
672 // First try LyX format
673 if (theClipboard().hasLyXContents()) {
674 string lyx = theClipboard().getAsLyX();
676 Buffer buffer(string(), false);
677 buffer.setUnnamed(true);
678 if (buffer.readString(lyx)) {
680 pasteParagraphList(cur, buffer.paragraphs(),
681 buffer.params().textclass, errorList);
688 // Then try plain text
689 docstring const text = theClipboard().getAsText();
694 cur.text()->insertStringAsParagraphs(cur, text);
696 cur.text()->insertStringAsLines(cur, text);
700 void pasteSelection(LCursor & cur, ErrorList & errorList, size_t sel_index)
702 // this does not make sense, if there is nothing to paste
703 if (!checkPastePossible(sel_index))
707 pasteParagraphList(cur, theCuts[sel_index].first,
708 theCuts[sel_index].second, errorList);
713 void replaceSelectionWithString(LCursor & cur, docstring const & str, bool backwards)
716 DocIterator selbeg = cur.selectionBegin();
718 // Get font setting before we cut
720 selbeg.paragraph().getFontSettings(cur.buffer().params(), selbeg.pos());
722 // Insert the new string
723 pos_type pos = cur.selEnd().pos();
724 Paragraph & par = cur.selEnd().paragraph();
725 docstring::const_iterator cit = str.begin();
726 docstring::const_iterator end = str.end();
727 for (; cit != end; ++cit, ++pos)
728 par.insertChar(pos, *cit, font, cur.buffer().params().trackChanges);
731 cutSelection(cur, true, false);
733 // select the replacement
735 selbeg.pos() += str.length();
736 cur.setSelection(selbeg, -int(str.length()));
738 cur.setSelection(selbeg, str.length());
742 void replaceSelection(LCursor & cur)
745 cutSelection(cur, true, false);
749 void eraseSelection(LCursor & cur)
751 //lyxerr << "cap::eraseSelection begin: " << cur << endl;
752 CursorSlice const & i1 = cur.selBegin();
753 CursorSlice const & i2 = cur.selEnd();
754 if (i1.inset().asInsetMath()) {
756 if (i1.idx() == i2.idx()) {
757 i1.cell().erase(i1.pos(), i2.pos());
758 // We may have deleted i1.cell(cur.pos()).
759 // Make sure that pos is valid.
760 if (cur.pos() > cur.lastpos())
761 cur.pos() = cur.lastpos();
763 InsetMath * p = i1.asInsetMath();
764 InsetBase::row_type r1, r2;
765 InsetBase::col_type c1, c2;
766 region(i1, i2, r1, r2, c1, c2);
767 for (InsetBase::row_type row = r1; row <= r2; ++row)
768 for (InsetBase::col_type col = c1; col <= c2; ++col)
769 p->cell(p->index(row, col)).clear();
770 // We've deleted the whole cell. Only pos 0 is valid.
773 // need a valid cursor. (Lgb)
774 cur.clearSelection();
775 theSelection().haveSelection(false);
777 lyxerr << "can't erase this selection 1" << endl;
779 //lyxerr << "cap::eraseSelection end: " << cur << endl;
783 void selDel(LCursor & cur)
785 //lyxerr << "cap::selDel" << endl;
791 void selClearOrDel(LCursor & cur)
793 //lyxerr << "cap::selClearOrDel" << endl;
794 if (lyxrc.auto_region_delete)
797 cur.selection() = false;
801 docstring grabSelection(LCursor const & cur)
803 if (!cur.selection())
806 // FIXME: What is wrong with the following?
808 std::ostringstream os;
809 for (DocIterator dit = cur.selectionBegin();
810 dit != cur.selectionEnd(); dit.forwardPos())
811 os << asString(dit.cell());
815 CursorSlice i1 = cur.selBegin();
816 CursorSlice i2 = cur.selEnd();
818 if (i1.idx() == i2.idx()) {
819 if (i1.inset().asInsetMath()) {
820 MathArray::const_iterator it = i1.cell().begin();
821 return asString(MathArray(it + i1.pos(), it + i2.pos()));
823 return from_ascii("unknown selection 1");
827 InsetBase::row_type r1, r2;
828 InsetBase::col_type c1, c2;
829 region(i1, i2, r1, r2, c1, c2);
832 if (i1.inset().asInsetMath()) {
833 for (InsetBase::row_type row = r1; row <= r2; ++row) {
836 for (InsetBase::col_type col = c1; col <= c2; ++col) {
839 data += asString(i1.asInsetMath()->
840 cell(i1.asInsetMath()->index(row, col)));
844 data = from_ascii("unknown selection 2");
850 void dirtyTabularStack(bool b)
852 dirty_tabular_stack_ = b;
856 bool tabularStackDirty()
858 return dirty_tabular_stack_;