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
10 * Full author contact details are available in file CREDITS.
15 #include "CutAndPaste.h"
18 #include "buffer_funcs.h"
19 #include "bufferparams.h"
22 #include "errorlist.h"
23 #include "funcrequest.h"
25 #include "insetiterator.h"
30 #include "lyxtextclasslist.h"
31 #include "paragraph.h"
32 #include "paragraph_funcs.h"
33 #include "ParagraphParameters.h"
34 #include "ParagraphList_fwd.h"
35 #include "pariterator.h"
38 #include "insets/insetcharstyle.h"
39 #include "insets/insettabular.h"
41 #include "mathed/MathData.h"
42 #include "mathed/InsetMath.h"
43 #include "mathed/MathSupport.h"
45 #include "support/lstrings.h"
47 #include "frontends/Clipboard.h"
49 #include <boost/tuple/tuple.hpp>
54 using lyx::textclass_type;
56 using lyx::support::bformat;
58 using lyx::frontend::Clipboard;
70 typedef std::pair<lyx::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_;
81 class resetParagraph : public std::unary_function<Paragraph, Buffer const &> {
83 resetParagraph(Buffer const & b) : buffer_(b) {}
84 void operator()(Paragraph & p) const {
85 // FIXME: change tracking (MG)
86 // set p's text to INSERTED in CT mode; clear CT info otherwise
88 // ERT paragraphs have the Language latex_language.
89 // This is invalid outside of ERT, so we need to change it
90 // to the buffer language.
91 if (p.ownerCode() == InsetBase::ERT_CODE) {
92 p.changeLanguage(buffer_.params(), latex_language,
93 buffer_.getLanguage());
98 Buffer const & buffer_;
102 void region(CursorSlice const & i1, CursorSlice const & i2,
103 InsetBase::row_type & r1, InsetBase::row_type & r2,
104 InsetBase::col_type & c1, InsetBase::col_type & c2)
106 InsetBase & p = i1.inset();
107 c1 = p.col(i1.idx());
108 c2 = p.col(i2.idx());
111 r1 = p.row(i1.idx());
112 r2 = p.row(i2.idx());
118 bool checkPastePossible(int index)
120 return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
124 pair<PitPosPair, pit_type>
125 pasteSelectionHelper(LCursor & cur, ParagraphList const & parlist,
126 textclass_type textclass, ErrorList & errorlist)
128 Buffer const & buffer = cur.buffer();
129 pit_type pit = cur.pit();
130 pos_type pos = cur.pos();
131 ParagraphList & pars = cur.text()->paragraphs();
134 return make_pair(PitPosPair(pit, pos), pit);
136 BOOST_ASSERT (pos <= pars[pit].size());
138 // Make a copy of the CaP paragraphs.
139 ParagraphList insertion = parlist;
140 textclass_type const tc = buffer.params().textclass;
142 // Now remove all out of the pars which is NOT allowed in the
143 // new environment and set also another font if that is required.
145 // Convert newline to paragraph break in ERT inset.
146 // This should not be here!
147 if (pars[pit].inInset() &&
148 pars[pit].inInset()->lyxCode() == InsetBase::ERT_CODE) {
149 for (ParagraphList::size_type i = 0; i < insertion.size(); ++i) {
150 for (pos_type j = 0; j < insertion[i].size(); ++j) {
151 if (insertion[i].isNewline(j)) {
152 // do not track deletion of newline
153 insertion[i].erase(j, false);
154 breakParagraphConservative(
162 // If we are in an inset which returns forceDefaultParagraphs,
163 // set the paragraphs to default
164 if (cur.inset().forceDefaultParagraphs(cur.idx())) {
165 LyXLayout_ptr const layout =
166 buffer.params().getLyXTextClass().defaultLayout();
167 ParagraphList::iterator const end = insertion.end();
168 for (ParagraphList::iterator par = insertion.begin();
173 // Make sure there is no class difference.
175 // This works without copying any paragraph data because we have
176 // a specialized swap method for ParagraphList. This is important
177 // since we store pointers to insets at some places and we don't
178 // want to invalidate them.
179 insertion.swap(in.paragraphs());
180 lyx::cap::switchBetweenClasses(textclass, tc, in, errorlist);
181 insertion.swap(in.paragraphs());
183 ParagraphList::iterator tmpbuf = insertion.begin();
184 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
186 Paragraph::depth_type max_depth = pars[pit].getMaxDepthAfter();
188 for (; tmpbuf != insertion.end(); ++tmpbuf) {
189 // If we have a negative jump so that the depth would
190 // go below 0 depth then we have to redo the delta to
191 // this new max depth level so that subsequent
192 // paragraphs are aligned correctly to this paragraph
194 if (int(tmpbuf->params().depth()) + depth_delta < 0)
197 // Set the right depth so that we are not too deep or shallow.
198 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
199 if (tmpbuf->params().depth() > max_depth)
200 tmpbuf->params().depth(max_depth);
202 // Only set this from the 2nd on as the 2nd depends
203 // for maxDepth still on pit.
204 if (tmpbuf != insertion.begin())
205 max_depth = tmpbuf->getMaxDepthAfter();
207 // Set the inset owner of this paragraph.
208 tmpbuf->setInsetOwner(pars[pit].inInset());
209 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
210 if (tmpbuf->getChar(i) == Paragraph::META_INSET &&
211 !pars[pit].insetAllowed(tmpbuf->getInset(i)->lyxCode()))
212 // do not track deletion of invalid insets
213 tmpbuf->erase(i--, false);
216 // FIXME: Change tracking (MG)
217 // set tmpbuf's text to INSERTED in CT mode; clear CT info otherwise
220 bool const empty = pars[pit].empty();
222 // Make the buf exactly the same layout as the cursor
224 insertion.begin()->makeSameLayout(pars[pit]);
227 // Prepare the paragraphs and insets for insertion.
228 // A couple of insets store buffer references so need updating.
229 insertion.swap(in.paragraphs());
231 ParIterator fpit = par_iterator_begin(in);
232 ParIterator fend = par_iterator_end(in);
234 for (; fpit != fend; ++fpit) {
235 InsetList::iterator lit = fpit->insetlist.begin();
236 InsetList::iterator eit = fpit->insetlist.end();
238 for (; lit != eit; ++lit) {
239 switch (lit->inset->lyxCode()) {
240 case InsetBase::TABULAR_CODE: {
241 InsetTabular * it = static_cast<InsetTabular*>(lit->inset);
251 insertion.swap(in.paragraphs());
253 // Split the paragraph for inserting the buf if necessary.
255 breakParagraphConservative(buffer.params(), pars, pit, pos);
259 pars.insert(boost::next(pars.begin(), pit),
263 // merge the empty par with the last par of the insertion
264 mergeParagraph(buffer.params(), pars,
265 pit + insertion.size() - 1);
267 pars.insert(boost::next(pars.begin(), pit + 1),
271 // merge the first par of the insertion with the current par
272 mergeParagraph(buffer.params(), pars, pit);
275 pit_type last_paste = pit + insertion.size() - 1;
277 // Store the new cursor position.
279 pos = pars[last_paste].size();
281 // Join (conditionally) last pasted paragraph with next one, i.e.,
282 // the tail of the spliced document paragraph
283 if (!empty && last_paste + 1 != pit_type(pars.size())) {
284 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
285 mergeParagraph(buffer.params(), pars, last_paste);
286 } else if (pars[last_paste + 1].empty()) {
287 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
288 mergeParagraph(buffer.params(), pars, last_paste);
289 } else if (pars[last_paste].empty()) {
290 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
291 mergeParagraph(buffer.params(), pars, last_paste);
293 pars[last_paste + 1].stripLeadingSpaces();
298 return make_pair(PitPosPair(pit, pos), last_paste + 1);
302 PitPosPair eraseSelectionHelper(BufferParams const & params,
303 ParagraphList & pars,
304 pit_type startpit, pit_type endpit,
305 int startpos, int endpos, bool doclear)
307 // Start of selection is really invalid.
308 if (startpit == pit_type(pars.size()) ||
309 (startpos > pars[startpit].size()))
310 return PitPosPair(endpit, endpos);
312 // Start and end is inside same paragraph
313 if (endpit == pit_type(pars.size()) ||
314 startpit == endpit) {
315 endpos -= pars[startpit].erase(startpos, endpos);
316 return PitPosPair(endpit, endpos);
319 // A paragraph break has to be physically removed by merging, but
320 // only if either (1) change tracking is off, or (2) the para break
322 for (pit_type pit = startpit; pit != endpit + 1;) {
323 // FIXME: Change tracking (MG)
324 bool const merge = !params.trackChanges ||
325 pars[pit].lookupChange(pars[pit].size()) ==
326 Change(Change::INSERTED);
327 pos_type const left = ( pit == startpit ? startpos : 0 );
328 pos_type const right = ( pit == endpit ? endpos :
329 pars[pit].size() + 1 );
330 // Logical erase only:
331 pars[pit].erase(left, right);
332 // Separate handling of para break:
333 if (merge && pit != endpit &&
334 (pit + 1 != endpit || pars[pit].hasSameLayout(pars[pit + 1]))) {
335 pos_type const thissize = pars[pit].size();
337 pars[pit + 1].stripLeadingSpaces();
338 mergeParagraph(params, pars, pit);
346 // Ensure legal cursor pos:
349 return PitPosPair(endpit, endpos);
353 void copySelectionHelper(Buffer const & buf, ParagraphList & pars,
354 pit_type startpit, pit_type endpit,
355 int start, int end, textclass_type tc)
357 BOOST_ASSERT(0 <= start && start <= pars[startpit].size());
358 BOOST_ASSERT(0 <= end && end <= pars[endpit].size());
359 BOOST_ASSERT(startpit != endpit || start <= end);
361 // Clone the paragraphs within the selection.
362 ParagraphList paragraphs(boost::next(pars.begin(), startpit),
363 boost::next(pars.begin(), endpit + 1));
365 for_each(paragraphs.begin(), paragraphs.end(), resetParagraph(buf));
367 // Cut out the end of the last paragraph.
368 Paragraph & back = paragraphs.back();
369 back.erase(end, back.size());
371 // Cut out the begin of the first paragraph
372 Paragraph & front = paragraphs.front();
373 front.erase(0, start);
375 theCuts.push(make_pair(paragraphs, tc));
386 string grabAndEraseSelection(LCursor & cur)
388 if (!cur.selection())
390 string res = grabSelection(cur);
396 void switchBetweenClasses(textclass_type c1, textclass_type c2,
397 InsetText & in, ErrorList & errorlist)
399 BOOST_ASSERT(!in.paragraphs().empty());
403 LyXTextClass const & tclass1 = textclasslist[c1];
404 LyXTextClass const & tclass2 = textclasslist[c2];
407 ParIterator end = par_iterator_end(in);
408 for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
409 string const name = it->layout()->name();
410 bool hasLayout = tclass2.hasLayout(name);
413 it->layout(tclass2[name]);
415 it->layout(tclass2.defaultLayout());
417 if (!hasLayout && name != tclass1.defaultLayoutName()) {
418 docstring const s = bformat(
419 _("Layout had to be changed from\n%1$s to %2$s\n"
420 "because of class conversion from\n%3$s to %4$s"),
421 lyx::from_utf8(name), lyx::from_utf8(it->layout()->name()),
422 lyx::from_utf8(tclass1.name()), lyx::from_utf8(tclass2.name()));
423 // To warn the user that something had to be done.
424 errorlist.push_back(ErrorItem(_("Changed Layout"), s,
431 InsetIterator const i_end = inset_iterator_end(in);
432 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
433 if (it->lyxCode() == InsetBase::CHARSTYLE_CODE) {
434 InsetCharStyle & inset =
435 static_cast<InsetCharStyle &>(*it);
436 string const name = inset.params().type;
437 CharStyles::iterator const found_cs =
438 tclass2.charstyle(name);
439 if (found_cs == tclass2.charstyles().end()) {
440 // The character style is undefined in tclass2
441 inset.setUndefined();
442 docstring const s = bformat(_(
443 "Character style %1$s is "
444 "undefined because of class "
445 "conversion from\n%2$s to %3$s"),
446 lyx::from_utf8(name), lyx::from_utf8(tclass1.name()),
447 lyx::from_utf8(tclass2.name()));
448 // To warn the user that something had to be done.
449 errorlist.push_back(ErrorItem(
450 _("Undefined character style"),
451 s, it.paragraph().id(), it.pos(), it.pos() + 1));
452 } else if (inset.undefined()) {
453 // The character style is undefined in
454 // tclass1 and is defined in tclass2
455 inset.setDefined(found_cs);
462 std::vector<docstring> const availableSelections(Buffer const & buffer)
464 vector<docstring> selList;
466 CutStack::const_iterator cit = theCuts.begin();
467 CutStack::const_iterator end = theCuts.end();
468 for (; cit != end; ++cit) {
469 // we do not use cit-> here because gcc 2.9x does not
471 ParagraphList const & pars = (*cit).first;
473 ParagraphList::const_iterator pit = pars.begin();
474 ParagraphList::const_iterator pend = pars.end();
475 for (; pit != pend; ++pit) {
476 asciiSel += pit->asString(buffer, false);
477 if (asciiSel.size() > 25) {
478 asciiSel.replace(22, docstring::npos,
479 lyx::from_ascii("..."));
484 selList.push_back(asciiSel);
491 lyx::size_type numberOfSelections()
493 return theCuts.size();
497 void cutSelection(LCursor & cur, bool doclear, bool realcut)
499 // This doesn't make sense, if there is no selection
500 if (!cur.selection())
503 // OK, we have a selection. This is always between cur.selBegin()
506 if (cur.inTexted()) {
507 LyXText * text = cur.text();
509 // Stuff what we got on the clipboard. Even if there is no selection.
511 // There is a problem with having the stuffing here in that the
512 // larger the selection the slower LyX will get. This can be
513 // solved by running the line below only when the selection has
514 // finished. The solution used currently just works, to make it
515 // faster we need to be more clever and probably also have more
516 // calls to theSelection().put. (Lgb)
517 // theSelection().put(cur.selectionAsString(true));
520 // make sure that the depth behind the selection are restored, too
521 recordUndoSelection(cur);
522 pit_type begpit = cur.selBegin().pit();
523 pit_type endpit = cur.selEnd().pit();
525 int endpos = cur.selEnd().pos();
527 BufferParams const & bp = cur.buffer().params();
529 copySelectionHelper(cur.buffer(),
532 cur.selBegin().pos(), endpos,
536 boost::tie(endpit, endpos) =
537 eraseSelectionHelper(bp,
540 cur.selBegin().pos(), endpos,
543 // sometimes necessary
545 text->paragraphs()[begpit].stripLeadingSpaces();
547 // cutSelection can invalidate the cursor so we need to set
549 // we prefer the end for when tracking changes
553 // need a valid cursor. (Lgb)
554 cur.clearSelection();
555 updateLabels(cur.buffer());
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 // stuff the selection onto the X clipboard, from an explicit copy request
581 theClipboard().put(cur.selectionAsString(true));
583 // this doesn't make sense, if there is no selection
584 if (!cur.selection())
587 if (cur.inTexted()) {
588 LyXText * text = cur.text();
590 // ok we have a selection. This is always between cur.selBegin()
591 // and sel_end cursor
593 // copy behind a space if there is one
594 ParagraphList & pars = text->paragraphs();
595 pos_type pos = cur.selBegin().pos();
596 pit_type par = cur.selBegin().pit();
597 while (pos < pars[par].size()
598 && pars[par].isLineSeparator(pos)
599 && (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
602 copySelectionHelper(cur.buffer(), pars, par, cur.selEnd().pit(),
603 pos, cur.selEnd().pos(), cur.buffer().params().textclass);
606 if (cur.inMathed()) {
607 //lyxerr << "copySelection in mathed" << endl;
609 pars.push_back(Paragraph());
610 BufferParams const & bp = cur.buffer().params();
611 pars.back().layout(bp.getLyXTextClass().defaultLayout());
612 for_each(pars.begin(), pars.end(), resetParagraph(cur.buffer()));
613 pars.back().insert(0, grabSelection(cur), LyXFont());
614 theCuts.push(make_pair(pars, bp.textclass));
616 // tell tabular that a recent copy happened
617 dirtyTabularStack(false);
621 docstring getSelection(Buffer const & buf, size_t sel_index)
623 return sel_index < theCuts.size()
624 ? theCuts[sel_index].first.back().asString(buf, false)
629 void pasteParagraphList(LCursor & cur, ParagraphList const & parlist,
630 textclass_type textclass, ErrorList & errorList)
632 if (cur.inTexted()) {
633 LyXText * text = cur.text();
641 boost::tie(ppp, endpit) =
642 pasteSelectionHelper(cur, parlist,
643 textclass, errorList);
644 updateLabels(cur.buffer());
645 cur.clearSelection();
646 text->setCursor(cur, ppp.first, ppp.second);
649 // mathed is handled in InsetMathNest/InsetMathGrid
650 BOOST_ASSERT(!cur.inMathed());
654 void pasteSelection(LCursor & cur, ErrorList & errorList, size_t sel_index)
656 // this does not make sense, if there is nothing to paste
657 if (!checkPastePossible(sel_index))
660 pasteParagraphList(cur, theCuts[sel_index].first,
661 theCuts[sel_index].second, errorList);
666 // simple replacing. The font of the first selected character is used
667 void replaceSelectionWithString(LCursor & cur, string const & str, bool backwards)
670 DocIterator selbeg = cur.selectionBegin();
672 // Get font setting before we cut
674 selbeg.paragraph().getFontSettings(cur.buffer().params(), selbeg.pos());
676 // Insert the new string
677 pos_type pos = cur.selEnd().pos();
678 Paragraph & par = cur.selEnd().paragraph();
679 string::const_iterator cit = str.begin();
680 string::const_iterator end = str.end();
681 for (; cit != end; ++cit, ++pos)
682 // FIXME: change tracking (MG)
683 par.insertChar(pos, (*cit), font, Change(Change::INSERTED));
686 cutSelection(cur, true, false);
688 // select the replacement
690 selbeg.pos() += str.length();
691 cur.setSelection(selbeg, -str.length());
693 cur.setSelection(selbeg, str.length());
697 void replaceSelection(LCursor & cur)
700 cutSelection(cur, true, false);
704 void eraseSelection(LCursor & cur)
706 //lyxerr << "LCursor::eraseSelection begin: " << cur << endl;
707 CursorSlice const & i1 = cur.selBegin();
708 CursorSlice const & i2 = cur.selEnd();
709 if (i1.inset().asInsetMath()) {
711 if (i1.idx() == i2.idx()) {
712 i1.cell().erase(i1.pos(), i2.pos());
713 // We may have deleted i1.cell(cur.pos()).
714 // Make sure that pos is valid.
715 if (cur.pos() > cur.lastpos())
716 cur.pos() = cur.lastpos();
718 InsetMath * p = i1.asInsetMath();
719 InsetBase::row_type r1, r2;
720 InsetBase::col_type c1, c2;
721 region(i1, i2, r1, r2, c1, c2);
722 for (InsetBase::row_type row = r1; row <= r2; ++row)
723 for (InsetBase::col_type col = c1; col <= c2; ++col)
724 p->cell(p->index(row, col)).clear();
725 // We've deleted the whole cell. Only pos 0 is valid.
728 // need a valid cursor. (Lgb)
729 cur.clearSelection();
731 lyxerr << "can't erase this selection 1" << endl;
733 //lyxerr << "LCursor::eraseSelection end: " << cur << endl;
737 void selDel(LCursor & cur)
739 //lyxerr << "LCursor::selDel" << endl;
745 void selClearOrDel(LCursor & cur)
747 //lyxerr << "LCursor::selClearOrDel" << endl;
748 if (lyxrc.auto_region_delete)
751 cur.selection() = false;
755 string grabSelection(LCursor const & cur)
757 if (!cur.selection())
760 // FIXME: What is wrong with the following?
762 std::ostringstream os;
763 for (DocIterator dit = cur.selectionBegin();
764 dit != cur.selectionEnd(); dit.forwardPos())
765 os << asString(dit.cell());
769 CursorSlice i1 = cur.selBegin();
770 CursorSlice i2 = cur.selEnd();
772 if (i1.idx() == i2.idx()) {
773 if (i1.inset().asInsetMath()) {
774 MathArray::const_iterator it = i1.cell().begin();
775 return asString(MathArray(it + i1.pos(), it + i2.pos()));
777 return "unknown selection 1";
781 InsetBase::row_type r1, r2;
782 InsetBase::col_type c1, c2;
783 region(i1, i2, r1, r2, c1, c2);
786 if (i1.inset().asInsetMath()) {
787 for (InsetBase::row_type row = r1; row <= r2; ++row) {
790 for (InsetBase::col_type col = c1; col <= c2; ++col) {
793 data += asString(i1.asInsetMath()->
794 cell(i1.asInsetMath()->index(row, col)));
798 data = "unknown selection 2";
804 void dirtyTabularStack(bool b)
806 dirty_tabular_stack_ = b;
810 bool tabularStackDirty()
812 return dirty_tabular_stack_;