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>
57 using support::bformat;
58 using frontend::Clipboard;
70 typedef std::pair<pit_type, int> PitPosPair;
72 typedef limited_stack<pair<ParagraphList, textclass_type> > CutStack;
76 // store whether the tabular stack is newer than the normal copy stack
77 // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
78 // when we (hopefully) have a one-for-all paste mechanism.
79 bool dirty_tabular_stack_ = false;
82 void region(CursorSlice const & i1, CursorSlice const & i2,
83 InsetBase::row_type & r1, InsetBase::row_type & r2,
84 InsetBase::col_type & c1, InsetBase::col_type & c2)
86 InsetBase & p = i1.inset();
98 bool checkPastePossible(int index)
100 return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
104 pair<PitPosPair, pit_type>
105 pasteSelectionHelper(LCursor & cur, ParagraphList const & parlist,
106 textclass_type textclass, ErrorList & errorlist)
108 Buffer const & buffer = cur.buffer();
109 pit_type pit = cur.pit();
110 pos_type pos = cur.pos();
111 ParagraphList & pars = cur.text()->paragraphs();
114 return make_pair(PitPosPair(pit, pos), pit);
116 BOOST_ASSERT (pos <= pars[pit].size());
118 // Make a copy of the CaP paragraphs.
119 ParagraphList insertion = parlist;
120 textclass_type const tc = buffer.params().textclass;
122 // Now remove all out of the pars which is NOT allowed in the
123 // new environment and set also another font if that is required.
125 // Convert newline to paragraph break in ERT inset.
126 // This should not be here!
127 if (pars[pit].inInset() &&
128 pars[pit].inInset()->lyxCode() == InsetBase::ERT_CODE) {
129 for (ParagraphList::size_type i = 0; i < insertion.size(); ++i) {
130 for (pos_type j = 0; j < insertion[i].size(); ++j) {
131 if (insertion[i].isNewline(j)) {
132 // do not track deletion of newline
133 insertion[i].eraseChar(j, false);
134 breakParagraphConservative(
142 // If we are in an inset which returns forceDefaultParagraphs,
143 // set the paragraphs to default
144 if (cur.inset().forceDefaultParagraphs(cur.idx())) {
145 LyXLayout_ptr const layout =
146 buffer.params().getLyXTextClass().defaultLayout();
147 ParagraphList::iterator const end = insertion.end();
148 for (ParagraphList::iterator par = insertion.begin();
153 // Make sure there is no class difference.
155 // This works without copying any paragraph data because we have
156 // a specialized swap method for ParagraphList. This is important
157 // since we store pointers to insets at some places and we don't
158 // want to invalidate them.
159 insertion.swap(in.paragraphs());
160 cap::switchBetweenClasses(textclass, tc, in, errorlist);
161 insertion.swap(in.paragraphs());
163 ParagraphList::iterator tmpbuf = insertion.begin();
164 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
166 depth_type max_depth = pars[pit].getMaxDepthAfter();
168 for (; tmpbuf != insertion.end(); ++tmpbuf) {
169 // If we have a negative jump so that the depth would
170 // go below 0 depth then we have to redo the delta to
171 // this new max depth level so that subsequent
172 // paragraphs are aligned correctly to this paragraph
174 if (int(tmpbuf->params().depth()) + depth_delta < 0)
177 // Set the right depth so that we are not too deep or shallow.
178 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
179 if (tmpbuf->params().depth() > max_depth)
180 tmpbuf->params().depth(max_depth);
182 // Only set this from the 2nd on as the 2nd depends
183 // for maxDepth still on pit.
184 if (tmpbuf != insertion.begin())
185 max_depth = tmpbuf->getMaxDepthAfter();
187 // Set the inset owner of this paragraph.
188 tmpbuf->setInsetOwner(pars[pit].inInset());
189 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
190 if (tmpbuf->getChar(i) == Paragraph::META_INSET &&
191 !pars[pit].insetAllowed(tmpbuf->getInset(i)->lyxCode()))
192 // do not track deletion of invalid insets
193 tmpbuf->eraseChar(i--, false);
196 tmpbuf->setChange(Change(buffer.params().trackChanges ?
197 Change::INSERTED : Change::UNCHANGED));
200 bool const empty = pars[pit].empty();
202 // Make the buf exactly the same layout as the cursor
204 insertion.begin()->makeSameLayout(pars[pit]);
207 // Prepare the paragraphs and insets for insertion.
208 // A couple of insets store buffer references so need updating.
209 insertion.swap(in.paragraphs());
211 ParIterator fpit = par_iterator_begin(in);
212 ParIterator fend = par_iterator_end(in);
214 for (; fpit != fend; ++fpit) {
215 InsetList::const_iterator lit = fpit->insetlist.begin();
216 InsetList::const_iterator eit = fpit->insetlist.end();
218 for (; lit != eit; ++lit) {
219 switch (lit->inset->lyxCode()) {
220 case InsetBase::TABULAR_CODE: {
221 InsetTabular * it = static_cast<InsetTabular*>(lit->inset);
231 insertion.swap(in.paragraphs());
233 // Split the paragraph for inserting the buf if necessary.
235 breakParagraphConservative(buffer.params(), pars, pit, pos);
239 pars.insert(boost::next(pars.begin(), pit),
243 // merge the empty par with the last par of the insertion
244 mergeParagraph(buffer.params(), pars,
245 pit + insertion.size() - 1);
247 pars.insert(boost::next(pars.begin(), pit + 1),
251 // merge the first par of the insertion with the current par
252 mergeParagraph(buffer.params(), pars, pit);
255 pit_type last_paste = pit + insertion.size() - 1;
257 // Store the new cursor position.
259 pos = pars[last_paste].size();
261 // Join (conditionally) last pasted paragraph with next one, i.e.,
262 // the tail of the spliced document paragraph
263 if (!empty && last_paste + 1 != pit_type(pars.size())) {
264 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
265 mergeParagraph(buffer.params(), pars, last_paste);
266 } else if (pars[last_paste + 1].empty()) {
267 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
268 mergeParagraph(buffer.params(), pars, last_paste);
269 } else if (pars[last_paste].empty()) {
270 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
271 mergeParagraph(buffer.params(), pars, last_paste);
273 pars[last_paste + 1].stripLeadingSpaces(buffer.params().trackChanges);
278 return make_pair(PitPosPair(pit, pos), last_paste + 1);
282 PitPosPair eraseSelectionHelper(BufferParams const & params,
283 ParagraphList & pars,
284 pit_type startpit, pit_type endpit,
285 int startpos, int endpos, bool doclear)
287 // Start of selection is really invalid.
288 if (startpit == pit_type(pars.size()) ||
289 (startpos > pars[startpit].size()))
290 return PitPosPair(endpit, endpos);
292 // Start and end is inside same paragraph
293 if (endpit == pit_type(pars.size()) || startpit == endpit) {
294 endpos -= pars[startpit].eraseChars(startpos, endpos, params.trackChanges);
295 return PitPosPair(endpit, endpos);
298 for (pit_type pit = startpit; pit != endpit + 1;) {
299 pos_type const left = (pit == startpit ? startpos : 0);
300 pos_type const right = (pit == endpit ? endpos : pars[pit].size() + 1);
302 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.trackChanges);
304 // Logically erase only, including the end-of-paragraph character
305 pars[pit].eraseChars(left, right, params.trackChanges);
307 // Separate handling of paragraph break:
308 if (merge && pit != endpit &&
309 (pit + 1 != endpit || pars[pit].hasSameLayout(pars[pit + 1]))) {
310 pos_type const thissize = pars[pit].size();
312 pars[pit + 1].stripLeadingSpaces(params.trackChanges);
313 mergeParagraph(params, pars, pit);
321 // Ensure legal cursor pos:
324 return PitPosPair(endpit, endpos);
328 void putClipboard(ParagraphList const & paragraphs, textclass_type textclass,
329 docstring const & plaintext)
331 Buffer buffer(string(), false);
332 buffer.setUnnamed(true);
333 buffer.paragraphs() = paragraphs;
334 buffer.params().textclass = textclass;
335 std::ostringstream lyx;
336 if (buffer.write(lyx))
337 theClipboard().put(lyx.str(), plaintext);
339 theClipboard().put(string(), plaintext);
343 void copySelectionHelper(Buffer const & buf, ParagraphList & pars,
344 pit_type startpit, pit_type endpit,
345 int start, int end, textclass_type tc)
347 BOOST_ASSERT(0 <= start && start <= pars[startpit].size());
348 BOOST_ASSERT(0 <= end && end <= pars[endpit].size());
349 BOOST_ASSERT(startpit != endpit || start <= end);
351 // Clone the paragraphs within the selection.
352 ParagraphList paragraphs(boost::next(pars.begin(), startpit),
353 boost::next(pars.begin(), endpit + 1));
355 ParagraphList::iterator it = paragraphs.begin();
356 ParagraphList::iterator it_end = paragraphs.end();
358 for (; it != it_end; it++) {
359 // ERT paragraphs have the Language latex_language.
360 // This is invalid outside of ERT, so we need to change it
361 // to the buffer language.
362 if (it->ownerCode() == InsetBase::ERT_CODE) {
363 it->changeLanguage(buf.params(), latex_language,
366 it->setInsetOwner(0);
369 // Cut out the end of the last paragraph.
370 Paragraph & back = paragraphs.back();
371 // do not track deletion here; it is an internal action not visible to the user
372 back.eraseChars(end, back.size(), false);
374 // Cut out the begin of the first paragraph
375 Paragraph & front = paragraphs.front();
376 // again, do not track deletion
377 front.eraseChars(0, start, false);
379 theCuts.push(make_pair(paragraphs, tc));
389 docstring grabAndEraseSelection(LCursor & cur)
391 if (!cur.selection())
393 docstring res = grabSelection(cur);
399 void switchBetweenClasses(textclass_type c1, textclass_type c2,
400 InsetText & in, ErrorList & errorlist)
402 BOOST_ASSERT(!in.paragraphs().empty());
406 LyXTextClass const & tclass1 = textclasslist[c1];
407 LyXTextClass const & tclass2 = textclasslist[c2];
410 ParIterator end = par_iterator_end(in);
411 for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
412 string const name = it->layout()->name();
413 bool hasLayout = tclass2.hasLayout(name);
416 it->layout(tclass2[name]);
418 it->layout(tclass2.defaultLayout());
420 if (!hasLayout && name != tclass1.defaultLayoutName()) {
421 docstring const s = bformat(
422 _("Layout had to be changed from\n%1$s to %2$s\n"
423 "because of class conversion from\n%3$s to %4$s"),
424 from_utf8(name), from_utf8(it->layout()->name()),
425 from_utf8(tclass1.name()), from_utf8(tclass2.name()));
426 // To warn the user that something had to be done.
427 errorlist.push_back(ErrorItem(_("Changed Layout"), s,
434 InsetIterator const i_end = inset_iterator_end(in);
435 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
436 if (it->lyxCode() == InsetBase::CHARSTYLE_CODE) {
437 InsetCharStyle & inset =
438 static_cast<InsetCharStyle &>(*it);
439 string const name = inset.params().type;
440 CharStyles::iterator const found_cs =
441 tclass2.charstyle(name);
442 if (found_cs == tclass2.charstyles().end()) {
443 // The character style is undefined in tclass2
444 inset.setUndefined();
445 docstring const s = bformat(_(
446 "Character style %1$s is "
447 "undefined because of class "
448 "conversion from\n%2$s to %3$s"),
449 from_utf8(name), from_utf8(tclass1.name()),
450 from_utf8(tclass2.name()));
451 // To warn the user that something had to be done.
452 errorlist.push_back(ErrorItem(
453 _("Undefined character style"),
454 s, it.paragraph().id(), it.pos(), it.pos() + 1));
455 } else if (inset.undefined()) {
456 // The character style is undefined in
457 // tclass1 and is defined in tclass2
458 inset.setDefined(found_cs);
465 std::vector<docstring> const availableSelections(Buffer const & buffer)
467 vector<docstring> selList;
469 CutStack::const_iterator cit = theCuts.begin();
470 CutStack::const_iterator end = theCuts.end();
471 for (; cit != end; ++cit) {
472 // we do not use cit-> here because gcc 2.9x does not
474 ParagraphList const & pars = (*cit).first;
476 ParagraphList::const_iterator pit = pars.begin();
477 ParagraphList::const_iterator pend = pars.end();
478 for (; pit != pend; ++pit) {
479 asciiSel += pit->asString(buffer, false);
480 if (asciiSel.size() > 25) {
481 asciiSel.replace(22, docstring::npos,
487 selList.push_back(asciiSel);
494 size_type numberOfSelections()
496 return theCuts.size();
500 void cutSelection(LCursor & cur, bool doclear, bool realcut)
502 // This doesn't make sense, if there is no selection
503 if (!cur.selection())
506 // OK, we have a selection. This is always between cur.selBegin()
509 if (cur.inTexted()) {
510 LyXText * text = cur.text();
513 // make sure that the depth behind the selection are restored, too
514 recordUndoSelection(cur);
515 pit_type begpit = cur.selBegin().pit();
516 pit_type endpit = cur.selEnd().pit();
518 int endpos = cur.selEnd().pos();
520 BufferParams const & bp = cur.buffer().params();
522 copySelectionHelper(cur.buffer(),
525 cur.selBegin().pos(), endpos,
527 // Stuff what we got on the clipboard.
528 // Even if there is no selection.
529 putClipboard(theCuts[0].first, theCuts[0].second,
530 cur.selectionAsString(true));
533 boost::tie(endpit, endpos) =
534 eraseSelectionHelper(bp,
537 cur.selBegin().pos(), endpos,
540 // sometimes necessary
542 text->paragraphs()[begpit].stripLeadingSpaces(bp.trackChanges);
544 // cutSelection can invalidate the cursor so we need to set
546 // we prefer the end for when tracking changes
550 // need a valid cursor. (Lgb)
551 cur.clearSelection();
552 updateLabels(cur.buffer());
553 theSelection().haveSelection(false);
555 // tell tabular that a recent copy happened
556 dirtyTabularStack(false);
559 if (cur.inMathed()) {
560 if (cur.selBegin().idx() != cur.selEnd().idx()) {
561 // The current selection spans more than one cell.
563 recordUndoInset(cur);
565 // Record only the current cell to avoid a jumping
576 void copySelection(LCursor & cur)
578 copySelection(cur, cur.selectionAsString(true));
582 void copySelection(LCursor & cur, docstring const & plaintext)
584 copySelectionToStack(cur);
586 // stuff the selection onto the X clipboard, from an explicit copy request
587 putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
591 void copySelectionToStack(LCursor & cur)
593 // this doesn't make sense, if there is no selection
594 if (!cur.selection())
597 if (cur.inTexted()) {
598 LyXText * text = cur.text();
600 // ok we have a selection. This is always between cur.selBegin()
601 // and sel_end cursor
603 // copy behind a space if there is one
604 ParagraphList & pars = text->paragraphs();
605 pos_type pos = cur.selBegin().pos();
606 pit_type par = cur.selBegin().pit();
607 while (pos < pars[par].size()
608 && pars[par].isLineSeparator(pos)
609 && (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
612 copySelectionHelper(cur.buffer(), pars, par, cur.selEnd().pit(),
613 pos, cur.selEnd().pos(), cur.buffer().params().textclass);
616 if (cur.inMathed()) {
617 //lyxerr << "copySelection in mathed" << endl;
620 BufferParams const & bp = cur.buffer().params();
621 par.layout(bp.getLyXTextClass().defaultLayout());
622 par.insert(0, grabSelection(cur), LyXFont(), Change(Change::UNCHANGED));
624 theCuts.push(make_pair(pars, bp.textclass));
626 // tell tabular that a recent copy happened
627 dirtyTabularStack(false);
631 docstring getSelection(Buffer const & buf, size_t sel_index)
633 return sel_index < theCuts.size()
634 ? theCuts[sel_index].first.back().asString(buf, false)
639 void pasteParagraphList(LCursor & cur, ParagraphList const & parlist,
640 textclass_type textclass, ErrorList & errorList)
642 if (cur.inTexted()) {
643 LyXText * text = cur.text();
649 boost::tie(ppp, endpit) =
650 pasteSelectionHelper(cur, parlist,
651 textclass, errorList);
652 updateLabels(cur.buffer());
653 cur.clearSelection();
654 text->setCursor(cur.top(), ppp.first, ppp.second);
657 // mathed is handled in InsetMathNest/InsetMathGrid
658 BOOST_ASSERT(!cur.inMathed());
662 void pasteClipboard(LCursor & cur, ErrorList & errorList, bool asParagraphs)
664 // Use internal clipboard if it is the most recent one
665 if (theClipboard().isInternal()) {
666 pasteSelection(cur, errorList, 0);
670 // First try LyX format
671 if (theClipboard().hasLyXContents()) {
672 string lyx = theClipboard().getAsLyX();
674 Buffer buffer(string(), false);
675 buffer.setUnnamed(true);
676 if (buffer.readString(lyx)) {
678 pasteParagraphList(cur, buffer.paragraphs(),
679 buffer.params().textclass, errorList);
686 // Then try plain text
687 docstring const text = theClipboard().getAsText();
692 cur.text()->insertStringAsParagraphs(cur, text);
694 cur.text()->insertStringAsLines(cur, text);
698 void pasteSelection(LCursor & cur, ErrorList & errorList, size_t sel_index)
700 // this does not make sense, if there is nothing to paste
701 if (!checkPastePossible(sel_index))
705 pasteParagraphList(cur, theCuts[sel_index].first,
706 theCuts[sel_index].second, errorList);
711 void replaceSelectionWithString(LCursor & cur, docstring const & str, bool backwards)
714 DocIterator selbeg = cur.selectionBegin();
716 // Get font setting before we cut
718 selbeg.paragraph().getFontSettings(cur.buffer().params(), selbeg.pos());
720 // Insert the new string
721 pos_type pos = cur.selEnd().pos();
722 Paragraph & par = cur.selEnd().paragraph();
723 docstring::const_iterator cit = str.begin();
724 docstring::const_iterator end = str.end();
725 for (; cit != end; ++cit, ++pos)
726 par.insertChar(pos, *cit, font, cur.buffer().params().trackChanges);
729 cutSelection(cur, true, false);
731 // select the replacement
733 selbeg.pos() += str.length();
734 cur.setSelection(selbeg, -int(str.length()));
736 cur.setSelection(selbeg, str.length());
740 void replaceSelection(LCursor & cur)
743 cutSelection(cur, true, false);
747 void eraseSelection(LCursor & cur)
749 //lyxerr << "cap::eraseSelection begin: " << cur << endl;
750 CursorSlice const & i1 = cur.selBegin();
751 CursorSlice const & i2 = cur.selEnd();
752 if (i1.inset().asInsetMath()) {
754 if (i1.idx() == i2.idx()) {
755 i1.cell().erase(i1.pos(), i2.pos());
756 // We may have deleted i1.cell(cur.pos()).
757 // Make sure that pos is valid.
758 if (cur.pos() > cur.lastpos())
759 cur.pos() = cur.lastpos();
761 InsetMath * p = i1.asInsetMath();
762 InsetBase::row_type r1, r2;
763 InsetBase::col_type c1, c2;
764 region(i1, i2, r1, r2, c1, c2);
765 for (InsetBase::row_type row = r1; row <= r2; ++row)
766 for (InsetBase::col_type col = c1; col <= c2; ++col)
767 p->cell(p->index(row, col)).clear();
768 // We've deleted the whole cell. Only pos 0 is valid.
771 // need a valid cursor. (Lgb)
772 cur.clearSelection();
773 theSelection().haveSelection(false);
775 lyxerr << "can't erase this selection 1" << endl;
777 //lyxerr << "cap::eraseSelection end: " << cur << endl;
781 void selDel(LCursor & cur)
783 //lyxerr << "cap::selDel" << endl;
789 void selClearOrDel(LCursor & cur)
791 //lyxerr << "cap::selClearOrDel" << endl;
792 if (lyxrc.auto_region_delete)
795 cur.selection() = false;
799 docstring grabSelection(LCursor const & cur)
801 if (!cur.selection())
804 // FIXME: What is wrong with the following?
806 std::ostringstream os;
807 for (DocIterator dit = cur.selectionBegin();
808 dit != cur.selectionEnd(); dit.forwardPos())
809 os << asString(dit.cell());
813 CursorSlice i1 = cur.selBegin();
814 CursorSlice i2 = cur.selEnd();
816 if (i1.idx() == i2.idx()) {
817 if (i1.inset().asInsetMath()) {
818 MathArray::const_iterator it = i1.cell().begin();
819 return asString(MathArray(it + i1.pos(), it + i2.pos()));
821 return from_ascii("unknown selection 1");
825 InsetBase::row_type r1, r2;
826 InsetBase::col_type c1, c2;
827 region(i1, i2, r1, r2, c1, c2);
830 if (i1.inset().asInsetMath()) {
831 for (InsetBase::row_type row = r1; row <= r2; ++row) {
834 for (InsetBase::col_type col = c1; col <= c2; ++col) {
837 data += asString(i1.asInsetMath()->
838 cell(i1.asInsetMath()->index(row, col)));
842 data = from_ascii("unknown selection 2");
848 void dirtyTabularStack(bool b)
850 dirty_tabular_stack_ = b;
854 bool tabularStackDirty()
856 return dirty_tabular_stack_;