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"
20 #include "BufferView.h"
23 #include "errorlist.h"
24 #include "funcrequest.h"
26 #include "insetiterator.h"
31 #include "lyxtextclasslist.h"
32 #include "paragraph.h"
33 #include "paragraph_funcs.h"
34 #include "ParagraphParameters.h"
35 #include "ParagraphList_fwd.h"
36 #include "pariterator.h"
39 #include "insets/insetcharstyle.h"
40 #include "insets/insettabular.h"
42 #include "mathed/MathData.h"
43 #include "mathed/InsetMath.h"
44 #include "mathed/MathSupport.h"
46 #include "support/lstrings.h"
48 #include "frontends/Gui.h"
49 #include "frontends/LyXView.h"
50 #include "frontends/Clipboard.h"
52 #include <boost/tuple/tuple.hpp>
56 using lyx::textclass_type;
58 using lyx::support::bformat;
60 using lyx::frontend::Gui;
61 using lyx::frontend::Clipboard;
73 typedef std::pair<lyx::pit_type, int> PitPosPair;
75 typedef limited_stack<pair<ParagraphList, textclass_type> > CutStack;
79 // store whether the tabular stack is newer than the normal copy stack
80 // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
81 // when we (hopefully) have a one-for-all paste mechanism.
82 bool dirty_tabular_stack_;
84 class resetParagraph : public std::unary_function<Paragraph, Buffer const &> {
86 resetParagraph(Buffer const & b) : buffer_(b) {}
87 void operator()(Paragraph & p) const {
89 // ERT paragraphs have the Language latex_language.
90 // This is invalid outside of ERT, so we need to change it
91 // to the buffer language.
92 if (p.ownerCode() == InsetBase::ERT_CODE) {
93 p.changeLanguage(buffer_.params(), latex_language,
94 buffer_.getLanguage());
99 Buffer const & buffer_;
103 void region(CursorSlice const & i1, CursorSlice const & i2,
104 InsetBase::row_type & r1, InsetBase::row_type & r2,
105 InsetBase::col_type & c1, InsetBase::col_type & c2)
107 InsetBase & p = i1.inset();
108 c1 = p.col(i1.idx());
109 c2 = p.col(i2.idx());
112 r1 = p.row(i1.idx());
113 r2 = p.row(i2.idx());
119 bool checkPastePossible(int index)
121 return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
125 pair<PitPosPair, pit_type>
126 pasteSelectionHelper(LCursor & cur, ParagraphList const & parlist,
127 textclass_type textclass, ErrorList & errorlist)
129 Buffer const & buffer = cur.buffer();
130 pit_type pit = cur.pit();
131 pos_type pos = cur.pos();
132 ParagraphList & pars = cur.text()->paragraphs();
135 return make_pair(PitPosPair(pit, pos), pit);
137 BOOST_ASSERT (pos <= pars[pit].size());
139 // Make a copy of the CaP paragraphs.
140 ParagraphList insertion = parlist;
141 textclass_type const tc = buffer.params().textclass;
143 // Now remove all out of the pars which is NOT allowed in the
144 // new environment and set also another font if that is required.
146 // Convert newline to paragraph break in ERT inset.
147 // This should not be here!
148 if (pars[pit].inInset() &&
149 pars[pit].inInset()->lyxCode() == InsetBase::ERT_CODE) {
150 for (ParagraphList::size_type i = 0; i < insertion.size(); ++i) {
151 for (pos_type j = 0; j < insertion[i].size(); ++j) {
152 if (insertion[i].isNewline(j)) {
153 insertion[i].erase(j);
154 breakParagraphConservative(
162 // If we are in an inset which returns forceDefaultParagraphs,
163 // set the paragraphs to default
164 // FIXME: pars[pit].forceDefaultParagraphs() should be enough,
165 // but returns the wrong values for tabular cells!
166 if (cur.inset().forceDefaultParagraphs(cur.idx())) {
167 LyXLayout_ptr const layout =
168 buffer.params().getLyXTextClass().defaultLayout();
169 ParagraphList::iterator const end = insertion.end();
170 for (ParagraphList::iterator par = insertion.begin();
175 // Make sure there is no class difference.
177 // This works without copying any paragraph data because we have
178 // a specialized swap method for ParagraphList. This is important
179 // since we store pointers to insets at some places and we don't
180 // want to invalidate them.
181 insertion.swap(in.paragraphs());
182 lyx::cap::switchBetweenClasses(textclass, tc, in, errorlist);
183 insertion.swap(in.paragraphs());
185 ParagraphList::iterator tmpbuf = insertion.begin();
186 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
188 Paragraph::depth_type max_depth = pars[pit].getMaxDepthAfter();
190 for (; tmpbuf != insertion.end(); ++tmpbuf) {
191 // If we have a negative jump so that the depth would
192 // go below 0 depth then we have to redo the delta to
193 // this new max depth level so that subsequent
194 // paragraphs are aligned correctly to this paragraph
196 if (int(tmpbuf->params().depth()) + depth_delta < 0)
199 // Set the right depth so that we are not too deep or shallow.
200 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
201 if (tmpbuf->params().depth() > max_depth)
202 tmpbuf->params().depth(max_depth);
204 // Only set this from the 2nd on as the 2nd depends
205 // for maxDepth still on pit.
206 if (tmpbuf != insertion.begin())
207 max_depth = tmpbuf->getMaxDepthAfter();
209 // Set the inset owner of this paragraph.
210 tmpbuf->setInsetOwner(pars[pit].inInset());
211 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
212 if (tmpbuf->getChar(i) == Paragraph::META_INSET &&
213 !pars[pit].insetAllowed(tmpbuf->getInset(i)->lyxCode()))
217 // reset change tracking status
218 if (buffer.params().tracking_changes)
219 tmpbuf->cleanChanges(Paragraph::trackingOn);
221 tmpbuf->cleanChanges(Paragraph::trackingOff);
224 bool const empty = pars[pit].empty();
226 // Make the buf exactly the same layout as the cursor
228 insertion.begin()->makeSameLayout(pars[pit]);
231 // Prepare the paragraphs and insets for insertion.
232 // A couple of insets store buffer references so need updating.
233 insertion.swap(in.paragraphs());
235 ParIterator fpit = par_iterator_begin(in);
236 ParIterator fend = par_iterator_end(in);
238 for (; fpit != fend; ++fpit) {
239 InsetList::iterator lit = fpit->insetlist.begin();
240 InsetList::iterator eit = fpit->insetlist.end();
242 for (; lit != eit; ++lit) {
243 switch (lit->inset->lyxCode()) {
244 case InsetBase::TABULAR_CODE: {
245 InsetTabular * it = static_cast<InsetTabular*>(lit->inset);
255 insertion.swap(in.paragraphs());
257 // Split the paragraph for inserting the buf if necessary.
259 breakParagraphConservative(buffer.params(), pars, pit, pos);
263 pars.insert(boost::next(pars.begin(), pit),
267 // merge the empty par with the last par of the insertion
268 mergeParagraph(buffer.params(), pars,
269 pit + insertion.size() - 1);
271 pars.insert(boost::next(pars.begin(), pit + 1),
275 // merge the first par of the insertion with the current par
276 mergeParagraph(buffer.params(), pars, pit);
279 pit_type last_paste = pit + insertion.size() - 1;
281 // Store the new cursor position.
283 pos = pars[last_paste].size();
285 // Join (conditionally) last pasted paragraph with next one, i.e.,
286 // the tail of the spliced document paragraph
287 if (!empty && last_paste + 1 != pit_type(pars.size())) {
288 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
289 mergeParagraph(buffer.params(), pars, last_paste);
290 } else if (pars[last_paste + 1].empty()) {
291 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
292 mergeParagraph(buffer.params(), pars, last_paste);
293 } else if (pars[last_paste].empty()) {
294 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
295 mergeParagraph(buffer.params(), pars, last_paste);
297 pars[last_paste + 1].stripLeadingSpaces();
302 return make_pair(PitPosPair(pit, pos), last_paste + 1);
306 PitPosPair eraseSelectionHelper(BufferParams const & params,
307 ParagraphList & pars,
308 pit_type startpit, pit_type endpit,
309 int startpos, int endpos, bool doclear)
311 // Start of selection is really invalid.
312 if (startpit == pit_type(pars.size()) ||
313 (startpos > pars[startpit].size()))
314 return PitPosPair(endpit, endpos);
316 // Start and end is inside same paragraph
317 if (endpit == pit_type(pars.size()) ||
318 startpit == endpit) {
319 endpos -= pars[startpit].erase(startpos, endpos);
320 return PitPosPair(endpit, endpos);
323 // A paragraph break has to be physically removed by merging, but
324 // only if either (1) change tracking is off, or (2) the para break
326 for (pit_type pit = startpit; pit != endpit + 1;) {
327 bool const merge = !params.tracking_changes ||
328 pars[pit].lookupChange(pars[pit].size()) ==
330 pos_type const left = ( pit == startpit ? startpos : 0 );
331 pos_type const right = ( pit == endpit ? endpos :
332 pars[pit].size() + 1 );
333 // Logical erase only:
334 pars[pit].erase(left, right);
335 // Separate handling of para break:
336 if (merge && pit != endpit &&
337 (pit + 1 != endpit || pars[pit].hasSameLayout(pars[pit + 1]))) {
338 pos_type const thissize = pars[pit].size();
340 pars[pit + 1].stripLeadingSpaces();
341 mergeParagraph(params, pars, pit);
349 // Ensure legal cursor pos:
352 return PitPosPair(endpit, endpos);
356 void copySelectionHelper(Buffer const & buf, ParagraphList & pars,
357 pit_type startpit, pit_type endpit,
358 int start, int end, textclass_type tc)
360 BOOST_ASSERT(0 <= start && start <= pars[startpit].size());
361 BOOST_ASSERT(0 <= end && end <= pars[endpit].size());
362 BOOST_ASSERT(startpit != endpit || start <= end);
364 // Clone the paragraphs within the selection.
365 ParagraphList paragraphs(boost::next(pars.begin(), startpit),
366 boost::next(pars.begin(), endpit + 1));
368 for_each(paragraphs.begin(), paragraphs.end(), resetParagraph(buf));
370 // Cut out the end of the last paragraph.
371 Paragraph & back = paragraphs.back();
372 back.erase(end, back.size());
374 // Cut out the begin of the first paragraph
375 Paragraph & front = paragraphs.front();
376 front.erase(0, start);
378 theCuts.push(make_pair(paragraphs, tc));
389 string grabAndEraseSelection(LCursor & cur)
391 if (!cur.selection())
393 string 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 lyx::from_utf8(name), lyx::from_utf8(it->layout()->name()),
425 lyx::from_utf8(tclass1.name()), lyx::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 lyx::from_utf8(name), lyx::from_utf8(tclass1.name()),
450 lyx::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<string> const availableSelections(Buffer const & buffer)
467 vector<string> 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, string::npos, "...");
486 selList.push_back(asciiSel);
493 lyx::size_type numberOfSelections()
495 return theCuts.size();
499 void cutSelection(LCursor & cur, bool doclear, bool realcut)
501 // This doesn't make sense, if there is no selection
502 if (!cur.selection())
505 // OK, we have a selection. This is always between cur.selBegin()
508 if (cur.inTexted()) {
509 LyXText * text = cur.text();
511 // Stuff what we got on the clipboard. Even if there is no selection.
513 // There is a problem with having the stuffing here in that the
514 // larger the selection the slower LyX will get. This can be
515 // solved by running the line below only when the selection has
516 // finished. The solution used currently just works, to make it
517 // faster we need to be more clever and probably also have more
518 // calls to cur.bv().owner()->gui().selection().put. (Lgb)
519 // cur.bv().owner()->gui().selection().put(cur.selectionAsString(true));
522 // make sure that the depth behind the selection are restored, too
523 recordUndoSelection(cur);
524 pit_type begpit = cur.selBegin().pit();
525 pit_type endpit = cur.selEnd().pit();
527 int endpos = cur.selEnd().pos();
529 BufferParams const & bp = cur.buffer().params();
531 copySelectionHelper(cur.buffer(),
534 cur.selBegin().pos(), endpos,
538 boost::tie(endpit, endpos) =
539 eraseSelectionHelper(bp,
542 cur.selBegin().pos(), endpos,
545 // sometimes necessary
547 text->paragraphs()[begpit].stripLeadingSpaces();
549 // cutSelection can invalidate the cursor so we need to set
551 // we prefer the end for when tracking changes
555 // need a valid cursor. (Lgb)
556 cur.clearSelection();
557 updateLabels(cur.buffer());
559 // tell tabular that a recent copy happened
560 dirtyTabularStack(false);
563 if (cur.inMathed()) {
564 if (cur.selBegin().idx() != cur.selEnd().idx()) {
565 // The current selection spans more than one cell.
567 recordUndoInset(cur);
569 // Record only the current cell to avoid a jumping
580 void copySelection(LCursor & cur)
582 // stuff the selection onto the X clipboard, from an explicit copy request
583 cur.bv().owner()->gui().clipboard().put(cur.selectionAsString(true));
585 // this doesn't make sense, if there is no selection
586 if (!cur.selection())
589 if (cur.inTexted()) {
590 LyXText * text = cur.text();
592 // ok we have a selection. This is always between cur.selBegin()
593 // and sel_end cursor
595 // copy behind a space if there is one
596 ParagraphList & pars = text->paragraphs();
597 pos_type pos = cur.selBegin().pos();
598 pit_type par = cur.selBegin().pit();
599 while (pos < pars[par].size()
600 && pars[par].isLineSeparator(pos)
601 && (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
604 copySelectionHelper(cur.buffer(), pars, par, cur.selEnd().pit(),
605 pos, cur.selEnd().pos(), cur.buffer().params().textclass);
608 if (cur.inMathed()) {
609 //lyxerr << "copySelection in mathed" << endl;
611 pars.push_back(Paragraph());
612 BufferParams const & bp = cur.buffer().params();
613 pars.back().layout(bp.getLyXTextClass().defaultLayout());
614 for_each(pars.begin(), pars.end(), resetParagraph(cur.buffer()));
615 pars.back().insert(0, grabSelection(cur), LyXFont());
616 theCuts.push(make_pair(pars, bp.textclass));
618 // tell tabular that a recent copy happened
619 dirtyTabularStack(false);
623 std::string getSelection(Buffer const & buf, size_t sel_index)
625 return sel_index < theCuts.size()
626 ? theCuts[sel_index].first.back().asString(buf, false)
631 void pasteParagraphList(LCursor & cur, ParagraphList const & parlist,
632 textclass_type textclass, ErrorList & errorList)
634 if (cur.inTexted()) {
635 LyXText * text = cur.text();
643 boost::tie(ppp, endpit) =
644 pasteSelectionHelper(cur, parlist,
645 textclass, errorList);
646 updateLabels(cur.buffer());
647 cur.clearSelection();
648 text->setCursor(cur, ppp.first, ppp.second);
651 // mathed is handled in InsetMathNest/InsetMathGrid
652 BOOST_ASSERT(!cur.inMathed());
656 void pasteSelection(LCursor & cur, ErrorList & errorList, size_t sel_index)
658 // this does not make sense, if there is nothing to paste
659 if (!checkPastePossible(sel_index))
662 pasteParagraphList(cur, theCuts[sel_index].first,
663 theCuts[sel_index].second, errorList);
668 // simple replacing. The font of the first selected character is used
669 void replaceSelectionWithString(LCursor & cur, string const & str, bool backwards)
672 DocIterator selbeg = cur.selectionBegin();
674 // Get font setting before we cut
676 selbeg.paragraph().getFontSettings(cur.buffer().params(), selbeg.pos());
678 // Insert the new string
679 pos_type pos = cur.selEnd().pos();
680 Paragraph & par = cur.selEnd().paragraph();
681 string::const_iterator cit = str.begin();
682 string::const_iterator end = str.end();
683 for (; cit != end; ++cit, ++pos)
684 par.insertChar(pos, (*cit), font);
687 cutSelection(cur, true, false);
689 // select the replacement
691 selbeg.pos() += str.length();
692 cur.setSelection(selbeg, -str.length());
694 cur.setSelection(selbeg, str.length());
698 void replaceSelection(LCursor & cur)
701 cutSelection(cur, true, false);
705 void eraseSelection(LCursor & cur)
707 //lyxerr << "LCursor::eraseSelection begin: " << cur << endl;
708 CursorSlice const & i1 = cur.selBegin();
709 CursorSlice const & i2 = cur.selEnd();
710 if (i1.inset().asInsetMath()) {
712 if (i1.idx() == i2.idx()) {
713 i1.cell().erase(i1.pos(), i2.pos());
714 // We may have deleted i1.cell(cur.pos()).
715 // Make sure that pos is valid.
716 if (cur.pos() > cur.lastpos())
717 cur.pos() = cur.lastpos();
719 InsetMath * p = i1.asInsetMath();
720 InsetBase::row_type r1, r2;
721 InsetBase::col_type c1, c2;
722 region(i1, i2, r1, r2, c1, c2);
723 for (InsetBase::row_type row = r1; row <= r2; ++row)
724 for (InsetBase::col_type col = c1; col <= c2; ++col)
725 p->cell(p->index(row, col)).clear();
726 // We've deleted the whole cell. Only pos 0 is valid.
729 // need a valid cursor. (Lgb)
730 cur.clearSelection();
732 lyxerr << "can't erase this selection 1" << endl;
734 //lyxerr << "LCursor::eraseSelection end: " << cur << endl;
738 void selDel(LCursor & cur)
740 //lyxerr << "LCursor::selDel" << endl;
746 void selClearOrDel(LCursor & cur)
748 //lyxerr << "LCursor::selClearOrDel" << endl;
749 if (lyxrc.auto_region_delete)
752 cur.selection() = false;
756 string grabSelection(LCursor const & cur)
758 if (!cur.selection())
761 // FIXME: What is wrong with the following?
763 std::ostringstream os;
764 for (DocIterator dit = cur.selectionBegin();
765 dit != cur.selectionEnd(); dit.forwardPos())
766 os << asString(dit.cell());
770 CursorSlice i1 = cur.selBegin();
771 CursorSlice i2 = cur.selEnd();
773 if (i1.idx() == i2.idx()) {
774 if (i1.inset().asInsetMath()) {
775 MathArray::const_iterator it = i1.cell().begin();
776 return asString(MathArray(it + i1.pos(), it + i2.pos()));
778 return "unknown selection 1";
782 InsetBase::row_type r1, r2;
783 InsetBase::col_type c1, c2;
784 region(i1, i2, r1, r2, c1, c2);
787 if (i1.inset().asInsetMath()) {
788 for (InsetBase::row_type row = r1; row <= r2; ++row) {
791 for (InsetBase::col_type col = c1; col <= c2; ++col) {
794 data += asString(i1.asInsetMath()->
795 cell(i1.asInsetMath()->index(row, col)));
799 data = "unknown selection 2";
805 void dirtyTabularStack(bool b)
807 dirty_tabular_stack_ = b;
811 bool tabularStackDirty()
813 return dirty_tabular_stack_;