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>
66 using support::bformat;
67 using frontend::Clipboard;
71 typedef std::pair<pit_type, int> PitPosPair;
73 typedef limited_stack<pair<ParagraphList, textclass_type> > CutStack;
77 // store whether the tabular stack is newer than the normal copy stack
78 // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
79 // when we (hopefully) have a one-for-all paste mechanism.
80 bool dirty_tabular_stack_ = false;
83 void region(CursorSlice const & i1, CursorSlice const & i2,
84 InsetBase::row_type & r1, InsetBase::row_type & r2,
85 InsetBase::col_type & c1, InsetBase::col_type & c2)
87 InsetBase & p = i1.inset();
99 bool checkPastePossible(int index)
101 return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
105 pair<PitPosPair, pit_type>
106 pasteSelectionHelper(LCursor & cur, ParagraphList const & parlist,
107 textclass_type textclass, ErrorList & errorlist)
109 Buffer const & buffer = cur.buffer();
110 pit_type pit = cur.pit();
111 pos_type pos = cur.pos();
112 ParagraphList & pars = cur.text()->paragraphs();
115 return make_pair(PitPosPair(pit, pos), pit);
117 BOOST_ASSERT (pos <= pars[pit].size());
119 // Make a copy of the CaP paragraphs.
120 ParagraphList insertion = parlist;
121 textclass_type const tc = buffer.params().textclass;
123 // Now remove all out of the pars which is NOT allowed in the
124 // new environment and set also another font if that is required.
126 // Convert newline to paragraph break in ERT inset.
127 // This should not be here!
128 if (pars[pit].inInset() &&
129 pars[pit].inInset()->lyxCode() == InsetBase::ERT_CODE) {
130 for (ParagraphList::size_type i = 0; i < insertion.size(); ++i) {
131 for (pos_type j = 0; j < insertion[i].size(); ++j) {
132 if (insertion[i].isNewline(j)) {
133 // do not track deletion of newline
134 insertion[i].eraseChar(j, false);
135 breakParagraphConservative(
143 // If we are in an inset which returns forceDefaultParagraphs,
144 // set the paragraphs to default
145 if (cur.inset().forceDefaultParagraphs(cur.idx())) {
146 LyXLayout_ptr const layout =
147 buffer.params().getLyXTextClass().defaultLayout();
148 ParagraphList::iterator const end = insertion.end();
149 for (ParagraphList::iterator par = insertion.begin();
154 // Make sure there is no class difference.
156 // This works without copying any paragraph data because we have
157 // a specialized swap method for ParagraphList. This is important
158 // since we store pointers to insets at some places and we don't
159 // want to invalidate them.
160 insertion.swap(in.paragraphs());
161 cap::switchBetweenClasses(textclass, tc, in, errorlist);
162 insertion.swap(in.paragraphs());
164 ParagraphList::iterator tmpbuf = insertion.begin();
165 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
167 depth_type max_depth = pars[pit].getMaxDepthAfter();
169 for (; tmpbuf != insertion.end(); ++tmpbuf) {
170 // If we have a negative jump so that the depth would
171 // go below 0 depth then we have to redo the delta to
172 // this new max depth level so that subsequent
173 // paragraphs are aligned correctly to this paragraph
175 if (int(tmpbuf->params().depth()) + depth_delta < 0)
178 // Set the right depth so that we are not too deep or shallow.
179 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
180 if (tmpbuf->params().depth() > max_depth)
181 tmpbuf->params().depth(max_depth);
183 // Only set this from the 2nd on as the 2nd depends
184 // for maxDepth still on pit.
185 if (tmpbuf != insertion.begin())
186 max_depth = tmpbuf->getMaxDepthAfter();
188 // Set the inset owner of this paragraph.
189 tmpbuf->setInsetOwner(pars[pit].inInset());
190 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
191 if (tmpbuf->getChar(i) == Paragraph::META_INSET &&
192 !pars[pit].insetAllowed(tmpbuf->getInset(i)->lyxCode()))
193 // do not track deletion of invalid insets
194 tmpbuf->eraseChar(i--, false);
197 tmpbuf->setChange(Change(buffer.params().trackChanges ?
198 Change::INSERTED : Change::UNCHANGED));
201 bool const empty = pars[pit].empty();
203 // Make the buf exactly the same layout as the cursor
205 insertion.begin()->makeSameLayout(pars[pit]);
208 // Prepare the paragraphs and insets for insertion.
209 // A couple of insets store buffer references so need updating.
210 insertion.swap(in.paragraphs());
212 ParIterator fpit = par_iterator_begin(in);
213 ParIterator fend = par_iterator_end(in);
215 for (; fpit != fend; ++fpit) {
216 InsetList::const_iterator lit = fpit->insetlist.begin();
217 InsetList::const_iterator eit = fpit->insetlist.end();
219 for (; lit != eit; ++lit) {
220 switch (lit->inset->lyxCode()) {
221 case InsetBase::TABULAR_CODE: {
222 InsetTabular * it = static_cast<InsetTabular*>(lit->inset);
232 insertion.swap(in.paragraphs());
234 // Split the paragraph for inserting the buf if necessary.
236 breakParagraphConservative(buffer.params(), pars, pit, pos);
240 pars.insert(boost::next(pars.begin(), pit),
244 // merge the empty par with the last par of the insertion
245 mergeParagraph(buffer.params(), pars,
246 pit + insertion.size() - 1);
248 pars.insert(boost::next(pars.begin(), pit + 1),
252 // merge the first par of the insertion with the current par
253 mergeParagraph(buffer.params(), pars, pit);
256 pit_type last_paste = pit + insertion.size() - 1;
258 // Store the new cursor position.
260 pos = pars[last_paste].size();
262 // Join (conditionally) last pasted paragraph with next one, i.e.,
263 // the tail of the spliced document paragraph
264 if (!empty && last_paste + 1 != pit_type(pars.size())) {
265 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
266 mergeParagraph(buffer.params(), pars, last_paste);
267 } else if (pars[last_paste + 1].empty()) {
268 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
269 mergeParagraph(buffer.params(), pars, last_paste);
270 } else if (pars[last_paste].empty()) {
271 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
272 mergeParagraph(buffer.params(), pars, last_paste);
274 pars[last_paste + 1].stripLeadingSpaces(buffer.params().trackChanges);
279 return make_pair(PitPosPair(pit, pos), last_paste + 1);
283 PitPosPair eraseSelectionHelper(BufferParams const & params,
284 ParagraphList & pars,
285 pit_type startpit, pit_type endpit,
286 int startpos, int endpos, bool doclear)
288 // Start of selection is really invalid.
289 if (startpit == pit_type(pars.size()) ||
290 (startpos > pars[startpit].size()))
291 return PitPosPair(endpit, endpos);
293 // Start and end is inside same paragraph
294 if (endpit == pit_type(pars.size()) || startpit == endpit) {
295 endpos -= pars[startpit].eraseChars(startpos, endpos, params.trackChanges);
296 return PitPosPair(endpit, endpos);
299 for (pit_type pit = startpit; pit != endpit + 1;) {
300 pos_type const left = (pit == startpit ? startpos : 0);
301 pos_type const right = (pit == endpit ? endpos : pars[pit].size() + 1);
303 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.trackChanges);
305 // Logically erase only, including the end-of-paragraph character
306 pars[pit].eraseChars(left, right, params.trackChanges);
308 // Separate handling of paragraph break:
309 if (merge && pit != endpit &&
310 (pit + 1 != endpit || pars[pit].hasSameLayout(pars[pit + 1]))) {
311 pos_type const thissize = pars[pit].size();
313 pars[pit + 1].stripLeadingSpaces(params.trackChanges);
314 mergeParagraph(params, pars, pit);
322 // Ensure legal cursor pos:
325 return PitPosPair(endpit, endpos);
329 void putClipboard(ParagraphList const & paragraphs, textclass_type textclass,
330 docstring const & plaintext)
332 Buffer buffer(string(), false);
333 buffer.setUnnamed(true);
334 buffer.paragraphs() = paragraphs;
335 buffer.params().textclass = textclass;
336 std::ostringstream lyx;
337 if (buffer.write(lyx))
338 theClipboard().put(lyx.str(), plaintext);
340 theClipboard().put(string(), plaintext);
344 void copySelectionHelper(Buffer const & buf, ParagraphList & pars,
345 pit_type startpit, pit_type endpit,
346 int start, int end, textclass_type tc)
348 BOOST_ASSERT(0 <= start && start <= pars[startpit].size());
349 BOOST_ASSERT(0 <= end && end <= pars[endpit].size());
350 BOOST_ASSERT(startpit != endpit || start <= end);
352 // Clone the paragraphs within the selection.
353 ParagraphList paragraphs(boost::next(pars.begin(), startpit),
354 boost::next(pars.begin(), endpit + 1));
356 ParagraphList::iterator it = paragraphs.begin();
357 ParagraphList::iterator it_end = paragraphs.end();
359 for (; it != it_end; it++) {
360 // ERT paragraphs have the Language latex_language.
361 // This is invalid outside of ERT, so we need to change it
362 // to the buffer language.
363 if (it->ownerCode() == InsetBase::ERT_CODE) {
364 it->changeLanguage(buf.params(), latex_language,
367 it->setInsetOwner(0);
370 // Cut out the end of the last paragraph.
371 Paragraph & back = paragraphs.back();
372 // do not track deletion here; it is an internal action not visible to the user
373 back.eraseChars(end, back.size(), false);
375 // Cut out the begin of the first paragraph
376 Paragraph & front = paragraphs.front();
377 // again, do not track deletion
378 front.eraseChars(0, start, false);
380 theCuts.push(make_pair(paragraphs, tc));
390 docstring grabAndEraseSelection(LCursor & cur)
392 if (!cur.selection())
394 docstring res = grabSelection(cur);
400 void switchBetweenClasses(textclass_type c1, textclass_type c2,
401 InsetText & in, ErrorList & errorlist)
403 BOOST_ASSERT(!in.paragraphs().empty());
407 LyXTextClass const & tclass1 = textclasslist[c1];
408 LyXTextClass const & tclass2 = textclasslist[c2];
411 ParIterator end = par_iterator_end(in);
412 for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
413 string const name = it->layout()->name();
414 bool hasLayout = tclass2.hasLayout(name);
417 it->layout(tclass2[name]);
419 it->layout(tclass2.defaultLayout());
421 if (!hasLayout && name != tclass1.defaultLayoutName()) {
422 docstring const s = bformat(
423 _("Layout had to be changed from\n%1$s to %2$s\n"
424 "because of class conversion from\n%3$s to %4$s"),
425 from_utf8(name), from_utf8(it->layout()->name()),
426 from_utf8(tclass1.name()), from_utf8(tclass2.name()));
427 // To warn the user that something had to be done.
428 errorlist.push_back(ErrorItem(_("Changed Layout"), s,
435 InsetIterator const i_end = inset_iterator_end(in);
436 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
437 if (it->lyxCode() == InsetBase::CHARSTYLE_CODE) {
438 InsetCharStyle & inset =
439 static_cast<InsetCharStyle &>(*it);
440 string const name = inset.params().type;
441 CharStyles::iterator const found_cs =
442 tclass2.charstyle(name);
443 if (found_cs == tclass2.charstyles().end()) {
444 // The character style is undefined in tclass2
445 inset.setUndefined();
446 docstring const s = bformat(_(
447 "Character style %1$s is "
448 "undefined because of class "
449 "conversion from\n%2$s to %3$s"),
450 from_utf8(name), from_utf8(tclass1.name()),
451 from_utf8(tclass2.name()));
452 // To warn the user that something had to be done.
453 errorlist.push_back(ErrorItem(
454 _("Undefined character style"),
455 s, it.paragraph().id(), it.pos(), it.pos() + 1));
456 } else if (inset.undefined()) {
457 // The character style is undefined in
458 // tclass1 and is defined in tclass2
459 inset.setDefined(found_cs);
466 std::vector<docstring> const availableSelections(Buffer const & buffer)
468 vector<docstring> selList;
470 CutStack::const_iterator cit = theCuts.begin();
471 CutStack::const_iterator end = theCuts.end();
472 for (; cit != end; ++cit) {
473 // we do not use cit-> here because gcc 2.9x does not
475 ParagraphList const & pars = (*cit).first;
477 ParagraphList::const_iterator pit = pars.begin();
478 ParagraphList::const_iterator pend = pars.end();
479 for (; pit != pend; ++pit) {
480 asciiSel += pit->asString(buffer, false);
481 if (asciiSel.size() > 25) {
482 asciiSel.replace(22, docstring::npos,
488 selList.push_back(asciiSel);
495 size_type numberOfSelections()
497 return theCuts.size();
501 void cutSelection(LCursor & cur, bool doclear, bool realcut)
503 // This doesn't make sense, if there is no selection
504 if (!cur.selection())
507 // OK, we have a selection. This is always between cur.selBegin()
510 if (cur.inTexted()) {
511 LyXText * text = cur.text();
514 // make sure that the depth behind the selection are restored, too
515 recordUndoSelection(cur);
516 pit_type begpit = cur.selBegin().pit();
517 pit_type endpit = cur.selEnd().pit();
519 int endpos = cur.selEnd().pos();
521 BufferParams const & bp = cur.buffer().params();
523 copySelectionHelper(cur.buffer(),
526 cur.selBegin().pos(), endpos,
528 // Stuff what we got on the clipboard.
529 // Even if there is no selection.
530 putClipboard(theCuts[0].first, theCuts[0].second,
531 cur.selectionAsString(true));
534 boost::tie(endpit, endpos) =
535 eraseSelectionHelper(bp,
538 cur.selBegin().pos(), endpos,
541 // sometimes necessary
543 text->paragraphs()[begpit].stripLeadingSpaces(bp.trackChanges);
545 // cutSelection can invalidate the cursor so we need to set
547 // we prefer the end for when tracking changes
551 // need a valid cursor. (Lgb)
552 cur.clearSelection();
553 updateLabels(cur.buffer());
554 theSelection().haveSelection(false);
556 // tell tabular that a recent copy happened
557 dirtyTabularStack(false);
560 if (cur.inMathed()) {
561 if (cur.selBegin().idx() != cur.selEnd().idx()) {
562 // The current selection spans more than one cell.
564 recordUndoInset(cur);
566 // Record only the current cell to avoid a jumping
577 void copySelection(LCursor & cur)
579 copySelection(cur, cur.selectionAsString(true));
583 void copySelection(LCursor & cur, docstring const & plaintext)
585 copySelectionToStack(cur);
587 // stuff the selection onto the X clipboard, from an explicit copy request
588 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
592 void copySelectionToStack(LCursor & cur)
594 // this doesn't make sense, if there is no selection
595 if (!cur.selection())
598 if (cur.inTexted()) {
599 LyXText * text = cur.text();
601 // ok we have a selection. This is always between cur.selBegin()
602 // and sel_end cursor
604 // copy behind a space if there is one
605 ParagraphList & pars = text->paragraphs();
606 pos_type pos = cur.selBegin().pos();
607 pit_type par = cur.selBegin().pit();
608 while (pos < pars[par].size()
609 && pars[par].isLineSeparator(pos)
610 && (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
613 copySelectionHelper(cur.buffer(), pars, par, cur.selEnd().pit(),
614 pos, cur.selEnd().pos(), cur.buffer().params().textclass);
617 if (cur.inMathed()) {
618 //lyxerr << "copySelection in mathed" << endl;
621 BufferParams const & bp = cur.buffer().params();
622 par.layout(bp.getLyXTextClass().defaultLayout());
623 par.insert(0, grabSelection(cur), LyXFont(), Change(Change::UNCHANGED));
625 theCuts.push(make_pair(pars, bp.textclass));
627 // tell tabular that a recent copy happened
628 dirtyTabularStack(false);
632 docstring getSelection(Buffer const & buf, size_t sel_index)
634 return sel_index < theCuts.size()
635 ? theCuts[sel_index].first.back().asString(buf, false)
640 void pasteParagraphList(LCursor & cur, ParagraphList const & parlist,
641 textclass_type textclass, ErrorList & errorList)
643 if (cur.inTexted()) {
644 LyXText * text = cur.text();
650 boost::tie(ppp, endpit) =
651 pasteSelectionHelper(cur, parlist,
652 textclass, errorList);
653 updateLabels(cur.buffer());
654 cur.clearSelection();
655 text->setCursor(cur.top(), ppp.first, ppp.second);
658 // mathed is handled in InsetMathNest/InsetMathGrid
659 BOOST_ASSERT(!cur.inMathed());
663 void pasteClipboard(LCursor & cur, ErrorList & errorList, bool asParagraphs)
665 // Use internal clipboard if it is the most recent one
666 if (theClipboard().isInternal()) {
667 pasteSelection(cur, errorList, 0);
671 // First try LyX format
672 if (theClipboard().hasLyXContents()) {
673 string lyx = theClipboard().getAsLyX();
675 Buffer buffer(string(), false);
676 buffer.setUnnamed(true);
677 if (buffer.readString(lyx)) {
679 pasteParagraphList(cur, buffer.paragraphs(),
680 buffer.params().textclass, errorList);
687 // Then try plain text
688 docstring const text = theClipboard().getAsText();
693 cur.text()->insertStringAsParagraphs(cur, text);
695 cur.text()->insertStringAsLines(cur, text);
699 void pasteSelection(LCursor & cur, ErrorList & errorList, size_t sel_index)
701 // this does not make sense, if there is nothing to paste
702 if (!checkPastePossible(sel_index))
706 pasteParagraphList(cur, theCuts[sel_index].first,
707 theCuts[sel_index].second, errorList);
712 void replaceSelectionWithString(LCursor & cur, docstring const & str, bool backwards)
715 DocIterator selbeg = cur.selectionBegin();
717 // Get font setting before we cut
719 selbeg.paragraph().getFontSettings(cur.buffer().params(), selbeg.pos());
721 // Insert the new string
722 pos_type pos = cur.selEnd().pos();
723 Paragraph & par = cur.selEnd().paragraph();
724 docstring::const_iterator cit = str.begin();
725 docstring::const_iterator end = str.end();
726 for (; cit != end; ++cit, ++pos)
727 par.insertChar(pos, *cit, font, cur.buffer().params().trackChanges);
730 cutSelection(cur, true, false);
732 // select the replacement
734 selbeg.pos() += str.length();
735 cur.setSelection(selbeg, -int(str.length()));
737 cur.setSelection(selbeg, str.length());
741 void replaceSelection(LCursor & cur)
744 cutSelection(cur, true, false);
748 void eraseSelection(LCursor & cur)
750 //lyxerr << "cap::eraseSelection begin: " << cur << endl;
751 CursorSlice const & i1 = cur.selBegin();
752 CursorSlice const & i2 = cur.selEnd();
753 if (i1.inset().asInsetMath()) {
755 if (i1.idx() == i2.idx()) {
756 i1.cell().erase(i1.pos(), i2.pos());
757 // We may have deleted i1.cell(cur.pos()).
758 // Make sure that pos is valid.
759 if (cur.pos() > cur.lastpos())
760 cur.pos() = cur.lastpos();
762 InsetMath * p = i1.asInsetMath();
763 InsetBase::row_type r1, r2;
764 InsetBase::col_type c1, c2;
765 region(i1, i2, r1, r2, c1, c2);
766 for (InsetBase::row_type row = r1; row <= r2; ++row)
767 for (InsetBase::col_type col = c1; col <= c2; ++col)
768 p->cell(p->index(row, col)).clear();
769 // We've deleted the whole cell. Only pos 0 is valid.
772 // need a valid cursor. (Lgb)
773 cur.clearSelection();
774 theSelection().haveSelection(false);
776 lyxerr << "can't erase this selection 1" << endl;
778 //lyxerr << "cap::eraseSelection end: " << cur << endl;
782 void selDel(LCursor & cur)
784 //lyxerr << "cap::selDel" << endl;
790 void selClearOrDel(LCursor & cur)
792 //lyxerr << "cap::selClearOrDel" << endl;
793 if (lyxrc.auto_region_delete)
796 cur.selection() = false;
800 docstring grabSelection(LCursor const & cur)
802 if (!cur.selection())
805 // FIXME: What is wrong with the following?
807 std::ostringstream os;
808 for (DocIterator dit = cur.selectionBegin();
809 dit != cur.selectionEnd(); dit.forwardPos())
810 os << asString(dit.cell());
814 CursorSlice i1 = cur.selBegin();
815 CursorSlice i2 = cur.selEnd();
817 if (i1.idx() == i2.idx()) {
818 if (i1.inset().asInsetMath()) {
819 MathArray::const_iterator it = i1.cell().begin();
820 return asString(MathArray(it + i1.pos(), it + i2.pos()));
822 return from_ascii("unknown selection 1");
826 InsetBase::row_type r1, r2;
827 InsetBase::col_type c1, c2;
828 region(i1, i2, r1, r2, c1, c2);
831 if (i1.inset().asInsetMath()) {
832 for (InsetBase::row_type row = r1; row <= r2; ++row) {
835 for (InsetBase::col_type col = c1; col <= c2; ++col) {
838 data += asString(i1.asInsetMath()->
839 cell(i1.asInsetMath()->index(row, col)));
843 data = from_ascii("unknown selection 2");
849 void dirtyTabularStack(bool b)
851 dirty_tabular_stack_ = b;
855 bool tabularStackDirty()
857 return dirty_tabular_stack_;