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>
53 using lyx::textclass_type;
55 using lyx::support::bformat;
57 using lyx::frontend::Clipboard;
69 typedef std::pair<lyx::pit_type, int> PitPosPair;
71 typedef limited_stack<pair<ParagraphList, textclass_type> > CutStack;
75 // store whether the tabular stack is newer than the normal copy stack
76 // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
77 // when we (hopefully) have a one-for-all paste mechanism.
78 bool dirty_tabular_stack_;
80 class resetParagraph : public std::unary_function<Paragraph, Buffer const &> {
82 resetParagraph(Buffer const & b) : buffer_(b) {}
83 void operator()(Paragraph & p) const {
84 // FIXME: change tracking (MG)
85 // set p's text to INSERTED in CT mode; clear CT info otherwise
87 // ERT paragraphs have the Language latex_language.
88 // This is invalid outside of ERT, so we need to change it
89 // to the buffer language.
90 if (p.ownerCode() == InsetBase::ERT_CODE) {
91 p.changeLanguage(buffer_.params(), latex_language,
92 buffer_.getLanguage());
97 Buffer const & buffer_;
101 void region(CursorSlice const & i1, CursorSlice const & i2,
102 InsetBase::row_type & r1, InsetBase::row_type & r2,
103 InsetBase::col_type & c1, InsetBase::col_type & c2)
105 InsetBase & p = i1.inset();
106 c1 = p.col(i1.idx());
107 c2 = p.col(i2.idx());
110 r1 = p.row(i1.idx());
111 r2 = p.row(i2.idx());
117 bool checkPastePossible(int index)
119 return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
123 pair<PitPosPair, pit_type>
124 pasteSelectionHelper(LCursor & cur, ParagraphList const & parlist,
125 textclass_type textclass, ErrorList & errorlist)
127 Buffer const & buffer = cur.buffer();
128 pit_type pit = cur.pit();
129 pos_type pos = cur.pos();
130 ParagraphList & pars = cur.text()->paragraphs();
133 return make_pair(PitPosPair(pit, pos), pit);
135 BOOST_ASSERT (pos <= pars[pit].size());
137 // Make a copy of the CaP paragraphs.
138 ParagraphList insertion = parlist;
139 textclass_type const tc = buffer.params().textclass;
141 // Now remove all out of the pars which is NOT allowed in the
142 // new environment and set also another font if that is required.
144 // Convert newline to paragraph break in ERT inset.
145 // This should not be here!
146 if (pars[pit].inInset() &&
147 pars[pit].inInset()->lyxCode() == InsetBase::ERT_CODE) {
148 for (ParagraphList::size_type i = 0; i < insertion.size(); ++i) {
149 for (pos_type j = 0; j < insertion[i].size(); ++j) {
150 if (insertion[i].isNewline(j)) {
151 insertion[i].erase(j);
152 breakParagraphConservative(
160 // If we are in an inset which returns forceDefaultParagraphs,
161 // set the paragraphs to default
162 if (cur.inset().forceDefaultParagraphs(cur.idx())) {
163 LyXLayout_ptr const layout =
164 buffer.params().getLyXTextClass().defaultLayout();
165 ParagraphList::iterator const end = insertion.end();
166 for (ParagraphList::iterator par = insertion.begin();
171 // Make sure there is no class difference.
173 // This works without copying any paragraph data because we have
174 // a specialized swap method for ParagraphList. This is important
175 // since we store pointers to insets at some places and we don't
176 // want to invalidate them.
177 insertion.swap(in.paragraphs());
178 lyx::cap::switchBetweenClasses(textclass, tc, in, errorlist);
179 insertion.swap(in.paragraphs());
181 ParagraphList::iterator tmpbuf = insertion.begin();
182 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
184 Paragraph::depth_type max_depth = pars[pit].getMaxDepthAfter();
186 for (; tmpbuf != insertion.end(); ++tmpbuf) {
187 // If we have a negative jump so that the depth would
188 // go below 0 depth then we have to redo the delta to
189 // this new max depth level so that subsequent
190 // paragraphs are aligned correctly to this paragraph
192 if (int(tmpbuf->params().depth()) + depth_delta < 0)
195 // Set the right depth so that we are not too deep or shallow.
196 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
197 if (tmpbuf->params().depth() > max_depth)
198 tmpbuf->params().depth(max_depth);
200 // Only set this from the 2nd on as the 2nd depends
201 // for maxDepth still on pit.
202 if (tmpbuf != insertion.begin())
203 max_depth = tmpbuf->getMaxDepthAfter();
205 // Set the inset owner of this paragraph.
206 tmpbuf->setInsetOwner(pars[pit].inInset());
207 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
208 if (tmpbuf->getChar(i) == Paragraph::META_INSET &&
209 !pars[pit].insetAllowed(tmpbuf->getInset(i)->lyxCode()))
213 // FIXME: Change tracking (MG)
214 // set tmpbuf's text to INSERTED in CT mode; clear CT info otherwise
217 bool const empty = pars[pit].empty();
219 // Make the buf exactly the same layout as the cursor
221 insertion.begin()->makeSameLayout(pars[pit]);
224 // Prepare the paragraphs and insets for insertion.
225 // A couple of insets store buffer references so need updating.
226 insertion.swap(in.paragraphs());
228 ParIterator fpit = par_iterator_begin(in);
229 ParIterator fend = par_iterator_end(in);
231 for (; fpit != fend; ++fpit) {
232 InsetList::iterator lit = fpit->insetlist.begin();
233 InsetList::iterator eit = fpit->insetlist.end();
235 for (; lit != eit; ++lit) {
236 switch (lit->inset->lyxCode()) {
237 case InsetBase::TABULAR_CODE: {
238 InsetTabular * it = static_cast<InsetTabular*>(lit->inset);
248 insertion.swap(in.paragraphs());
250 // Split the paragraph for inserting the buf if necessary.
252 breakParagraphConservative(buffer.params(), pars, pit, pos);
256 pars.insert(boost::next(pars.begin(), pit),
260 // merge the empty par with the last par of the insertion
261 mergeParagraph(buffer.params(), pars,
262 pit + insertion.size() - 1);
264 pars.insert(boost::next(pars.begin(), pit + 1),
268 // merge the first par of the insertion with the current par
269 mergeParagraph(buffer.params(), pars, pit);
272 pit_type last_paste = pit + insertion.size() - 1;
274 // Store the new cursor position.
276 pos = pars[last_paste].size();
278 // Join (conditionally) last pasted paragraph with next one, i.e.,
279 // the tail of the spliced document paragraph
280 if (!empty && last_paste + 1 != pit_type(pars.size())) {
281 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
282 mergeParagraph(buffer.params(), pars, last_paste);
283 } else if (pars[last_paste + 1].empty()) {
284 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
285 mergeParagraph(buffer.params(), pars, last_paste);
286 } else if (pars[last_paste].empty()) {
287 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
288 mergeParagraph(buffer.params(), pars, last_paste);
290 pars[last_paste + 1].stripLeadingSpaces();
295 return make_pair(PitPosPair(pit, pos), last_paste + 1);
299 PitPosPair eraseSelectionHelper(BufferParams const & params,
300 ParagraphList & pars,
301 pit_type startpit, pit_type endpit,
302 int startpos, int endpos, bool doclear)
304 // Start of selection is really invalid.
305 if (startpit == pit_type(pars.size()) ||
306 (startpos > pars[startpit].size()))
307 return PitPosPair(endpit, endpos);
309 // Start and end is inside same paragraph
310 if (endpit == pit_type(pars.size()) ||
311 startpit == endpit) {
312 endpos -= pars[startpit].erase(startpos, endpos);
313 return PitPosPair(endpit, endpos);
316 // A paragraph break has to be physically removed by merging, but
317 // only if either (1) change tracking is off, or (2) the para break
319 for (pit_type pit = startpit; pit != endpit + 1;) {
320 // FIXME: Change tracking (MG)
321 bool const merge = !params.trackChanges ||
322 pars[pit].lookupChange(pars[pit].size()) ==
324 pos_type const left = ( pit == startpit ? startpos : 0 );
325 pos_type const right = ( pit == endpit ? endpos :
326 pars[pit].size() + 1 );
327 // Logical erase only:
328 pars[pit].erase(left, right);
329 // Separate handling of para break:
330 if (merge && pit != endpit &&
331 (pit + 1 != endpit || pars[pit].hasSameLayout(pars[pit + 1]))) {
332 pos_type const thissize = pars[pit].size();
334 pars[pit + 1].stripLeadingSpaces();
335 mergeParagraph(params, pars, pit);
343 // Ensure legal cursor pos:
346 return PitPosPair(endpit, endpos);
350 void copySelectionHelper(Buffer const & buf, ParagraphList & pars,
351 pit_type startpit, pit_type endpit,
352 int start, int end, textclass_type tc)
354 BOOST_ASSERT(0 <= start && start <= pars[startpit].size());
355 BOOST_ASSERT(0 <= end && end <= pars[endpit].size());
356 BOOST_ASSERT(startpit != endpit || start <= end);
358 // Clone the paragraphs within the selection.
359 ParagraphList paragraphs(boost::next(pars.begin(), startpit),
360 boost::next(pars.begin(), endpit + 1));
362 for_each(paragraphs.begin(), paragraphs.end(), resetParagraph(buf));
364 // Cut out the end of the last paragraph.
365 Paragraph & back = paragraphs.back();
366 back.erase(end, back.size());
368 // Cut out the begin of the first paragraph
369 Paragraph & front = paragraphs.front();
370 front.erase(0, start);
372 theCuts.push(make_pair(paragraphs, tc));
383 string grabAndEraseSelection(LCursor & cur)
385 if (!cur.selection())
387 string res = grabSelection(cur);
393 void switchBetweenClasses(textclass_type c1, textclass_type c2,
394 InsetText & in, ErrorList & errorlist)
396 BOOST_ASSERT(!in.paragraphs().empty());
400 LyXTextClass const & tclass1 = textclasslist[c1];
401 LyXTextClass const & tclass2 = textclasslist[c2];
404 ParIterator end = par_iterator_end(in);
405 for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
406 string const name = it->layout()->name();
407 bool hasLayout = tclass2.hasLayout(name);
410 it->layout(tclass2[name]);
412 it->layout(tclass2.defaultLayout());
414 if (!hasLayout && name != tclass1.defaultLayoutName()) {
415 docstring const s = bformat(
416 _("Layout had to be changed from\n%1$s to %2$s\n"
417 "because of class conversion from\n%3$s to %4$s"),
418 lyx::from_utf8(name), lyx::from_utf8(it->layout()->name()),
419 lyx::from_utf8(tclass1.name()), lyx::from_utf8(tclass2.name()));
420 // To warn the user that something had to be done.
421 errorlist.push_back(ErrorItem(_("Changed Layout"), s,
428 InsetIterator const i_end = inset_iterator_end(in);
429 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
430 if (it->lyxCode() == InsetBase::CHARSTYLE_CODE) {
431 InsetCharStyle & inset =
432 static_cast<InsetCharStyle &>(*it);
433 string const name = inset.params().type;
434 CharStyles::iterator const found_cs =
435 tclass2.charstyle(name);
436 if (found_cs == tclass2.charstyles().end()) {
437 // The character style is undefined in tclass2
438 inset.setUndefined();
439 docstring const s = bformat(_(
440 "Character style %1$s is "
441 "undefined because of class "
442 "conversion from\n%2$s to %3$s"),
443 lyx::from_utf8(name), lyx::from_utf8(tclass1.name()),
444 lyx::from_utf8(tclass2.name()));
445 // To warn the user that something had to be done.
446 errorlist.push_back(ErrorItem(
447 _("Undefined character style"),
448 s, it.paragraph().id(), it.pos(), it.pos() + 1));
449 } else if (inset.undefined()) {
450 // The character style is undefined in
451 // tclass1 and is defined in tclass2
452 inset.setDefined(found_cs);
459 std::vector<string> const availableSelections(Buffer const & buffer)
461 vector<string> selList;
463 CutStack::const_iterator cit = theCuts.begin();
464 CutStack::const_iterator end = theCuts.end();
465 for (; cit != end; ++cit) {
466 // we do not use cit-> here because gcc 2.9x does not
468 ParagraphList const & pars = (*cit).first;
470 ParagraphList::const_iterator pit = pars.begin();
471 ParagraphList::const_iterator pend = pars.end();
472 for (; pit != pend; ++pit) {
473 asciiSel += pit->asString(buffer, false);
474 if (asciiSel.size() > 25) {
475 asciiSel.replace(22, string::npos, "...");
480 selList.push_back(asciiSel);
487 lyx::size_type numberOfSelections()
489 return theCuts.size();
493 void cutSelection(LCursor & cur, bool doclear, bool realcut)
495 // This doesn't make sense, if there is no selection
496 if (!cur.selection())
499 // OK, we have a selection. This is always between cur.selBegin()
502 if (cur.inTexted()) {
503 LyXText * text = cur.text();
505 // Stuff what we got on the clipboard. Even if there is no selection.
507 // There is a problem with having the stuffing here in that the
508 // larger the selection the slower LyX will get. This can be
509 // solved by running the line below only when the selection has
510 // finished. The solution used currently just works, to make it
511 // faster we need to be more clever and probably also have more
512 // calls to theSelection().put. (Lgb)
513 // theSelection().put(cur.selectionAsString(true));
516 // make sure that the depth behind the selection are restored, too
517 recordUndoSelection(cur);
518 pit_type begpit = cur.selBegin().pit();
519 pit_type endpit = cur.selEnd().pit();
521 int endpos = cur.selEnd().pos();
523 BufferParams const & bp = cur.buffer().params();
525 copySelectionHelper(cur.buffer(),
528 cur.selBegin().pos(), endpos,
532 boost::tie(endpit, endpos) =
533 eraseSelectionHelper(bp,
536 cur.selBegin().pos(), endpos,
539 // sometimes necessary
541 text->paragraphs()[begpit].stripLeadingSpaces();
543 // cutSelection can invalidate the cursor so we need to set
545 // we prefer the end for when tracking changes
549 // need a valid cursor. (Lgb)
550 cur.clearSelection();
551 updateLabels(cur.buffer());
553 // tell tabular that a recent copy happened
554 dirtyTabularStack(false);
557 if (cur.inMathed()) {
558 if (cur.selBegin().idx() != cur.selEnd().idx()) {
559 // The current selection spans more than one cell.
561 recordUndoInset(cur);
563 // Record only the current cell to avoid a jumping
574 void copySelection(LCursor & cur)
576 // stuff the selection onto the X clipboard, from an explicit copy request
577 theClipboard().put(cur.selectionAsString(true));
579 // this doesn't make sense, if there is no selection
580 if (!cur.selection())
583 if (cur.inTexted()) {
584 LyXText * text = cur.text();
586 // ok we have a selection. This is always between cur.selBegin()
587 // and sel_end cursor
589 // copy behind a space if there is one
590 ParagraphList & pars = text->paragraphs();
591 pos_type pos = cur.selBegin().pos();
592 pit_type par = cur.selBegin().pit();
593 while (pos < pars[par].size()
594 && pars[par].isLineSeparator(pos)
595 && (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
598 copySelectionHelper(cur.buffer(), pars, par, cur.selEnd().pit(),
599 pos, cur.selEnd().pos(), cur.buffer().params().textclass);
602 if (cur.inMathed()) {
603 //lyxerr << "copySelection in mathed" << endl;
605 pars.push_back(Paragraph());
606 BufferParams const & bp = cur.buffer().params();
607 pars.back().layout(bp.getLyXTextClass().defaultLayout());
608 for_each(pars.begin(), pars.end(), resetParagraph(cur.buffer()));
609 pars.back().insert(0, grabSelection(cur), LyXFont());
610 theCuts.push(make_pair(pars, bp.textclass));
612 // tell tabular that a recent copy happened
613 dirtyTabularStack(false);
617 std::string getSelection(Buffer const & buf, size_t sel_index)
619 return sel_index < theCuts.size()
620 ? theCuts[sel_index].first.back().asString(buf, false)
625 void pasteParagraphList(LCursor & cur, ParagraphList const & parlist,
626 textclass_type textclass, ErrorList & errorList)
628 if (cur.inTexted()) {
629 LyXText * text = cur.text();
637 boost::tie(ppp, endpit) =
638 pasteSelectionHelper(cur, parlist,
639 textclass, errorList);
640 updateLabels(cur.buffer());
641 cur.clearSelection();
642 text->setCursor(cur, ppp.first, ppp.second);
645 // mathed is handled in InsetMathNest/InsetMathGrid
646 BOOST_ASSERT(!cur.inMathed());
650 void pasteSelection(LCursor & cur, ErrorList & errorList, size_t sel_index)
652 // this does not make sense, if there is nothing to paste
653 if (!checkPastePossible(sel_index))
656 pasteParagraphList(cur, theCuts[sel_index].first,
657 theCuts[sel_index].second, errorList);
662 // simple replacing. The font of the first selected character is used
663 void replaceSelectionWithString(LCursor & cur, string const & str, bool backwards)
666 DocIterator selbeg = cur.selectionBegin();
668 // Get font setting before we cut
670 selbeg.paragraph().getFontSettings(cur.buffer().params(), selbeg.pos());
672 // Insert the new string
673 pos_type pos = cur.selEnd().pos();
674 Paragraph & par = cur.selEnd().paragraph();
675 string::const_iterator cit = str.begin();
676 string::const_iterator end = str.end();
677 for (; cit != end; ++cit, ++pos)
678 par.insertChar(pos, (*cit), font);
681 cutSelection(cur, true, false);
683 // select the replacement
685 selbeg.pos() += str.length();
686 cur.setSelection(selbeg, -str.length());
688 cur.setSelection(selbeg, str.length());
692 void replaceSelection(LCursor & cur)
695 cutSelection(cur, true, false);
699 void eraseSelection(LCursor & cur)
701 //lyxerr << "LCursor::eraseSelection begin: " << cur << endl;
702 CursorSlice const & i1 = cur.selBegin();
703 CursorSlice const & i2 = cur.selEnd();
704 if (i1.inset().asInsetMath()) {
706 if (i1.idx() == i2.idx()) {
707 i1.cell().erase(i1.pos(), i2.pos());
708 // We may have deleted i1.cell(cur.pos()).
709 // Make sure that pos is valid.
710 if (cur.pos() > cur.lastpos())
711 cur.pos() = cur.lastpos();
713 InsetMath * p = i1.asInsetMath();
714 InsetBase::row_type r1, r2;
715 InsetBase::col_type c1, c2;
716 region(i1, i2, r1, r2, c1, c2);
717 for (InsetBase::row_type row = r1; row <= r2; ++row)
718 for (InsetBase::col_type col = c1; col <= c2; ++col)
719 p->cell(p->index(row, col)).clear();
720 // We've deleted the whole cell. Only pos 0 is valid.
723 // need a valid cursor. (Lgb)
724 cur.clearSelection();
726 lyxerr << "can't erase this selection 1" << endl;
728 //lyxerr << "LCursor::eraseSelection end: " << cur << endl;
732 void selDel(LCursor & cur)
734 //lyxerr << "LCursor::selDel" << endl;
740 void selClearOrDel(LCursor & cur)
742 //lyxerr << "LCursor::selClearOrDel" << endl;
743 if (lyxrc.auto_region_delete)
746 cur.selection() = false;
750 string grabSelection(LCursor const & cur)
752 if (!cur.selection())
755 // FIXME: What is wrong with the following?
757 std::ostringstream os;
758 for (DocIterator dit = cur.selectionBegin();
759 dit != cur.selectionEnd(); dit.forwardPos())
760 os << asString(dit.cell());
764 CursorSlice i1 = cur.selBegin();
765 CursorSlice i2 = cur.selEnd();
767 if (i1.idx() == i2.idx()) {
768 if (i1.inset().asInsetMath()) {
769 MathArray::const_iterator it = i1.cell().begin();
770 return asString(MathArray(it + i1.pos(), it + i2.pos()));
772 return "unknown selection 1";
776 InsetBase::row_type r1, r2;
777 InsetBase::col_type c1, c2;
778 region(i1, i2, r1, r2, c1, c2);
781 if (i1.inset().asInsetMath()) {
782 for (InsetBase::row_type row = r1; row <= r2; ++row) {
785 for (InsetBase::col_type col = c1; col <= c2; ++col) {
788 data += asString(i1.asInsetMath()->
789 cell(i1.asInsetMath()->index(row, col)));
793 data = "unknown selection 2";
799 void dirtyTabularStack(bool b)
801 dirty_tabular_stack_ = b;
805 bool tabularStackDirty()
807 return dirty_tabular_stack_;