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 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()))
215 // reset change tracking status
216 if (buffer.params().tracking_changes)
217 tmpbuf->cleanChanges(Paragraph::trackingOn);
219 tmpbuf->cleanChanges(Paragraph::trackingOff);
222 bool const empty = pars[pit].empty();
224 // Make the buf exactly the same layout as the cursor
226 insertion.begin()->makeSameLayout(pars[pit]);
229 // Prepare the paragraphs and insets for insertion.
230 // A couple of insets store buffer references so need updating.
231 insertion.swap(in.paragraphs());
233 ParIterator fpit = par_iterator_begin(in);
234 ParIterator fend = par_iterator_end(in);
236 for (; fpit != fend; ++fpit) {
237 InsetList::iterator lit = fpit->insetlist.begin();
238 InsetList::iterator eit = fpit->insetlist.end();
240 for (; lit != eit; ++lit) {
241 switch (lit->inset->lyxCode()) {
242 case InsetBase::TABULAR_CODE: {
243 InsetTabular * it = static_cast<InsetTabular*>(lit->inset);
253 insertion.swap(in.paragraphs());
255 // Split the paragraph for inserting the buf if necessary.
257 breakParagraphConservative(buffer.params(), pars, pit, pos);
261 pars.insert(boost::next(pars.begin(), pit),
265 // merge the empty par with the last par of the insertion
266 mergeParagraph(buffer.params(), pars,
267 pit + insertion.size() - 1);
269 pars.insert(boost::next(pars.begin(), pit + 1),
273 // merge the first par of the insertion with the current par
274 mergeParagraph(buffer.params(), pars, pit);
277 pit_type last_paste = pit + insertion.size() - 1;
279 // Store the new cursor position.
281 pos = pars[last_paste].size();
283 // Join (conditionally) last pasted paragraph with next one, i.e.,
284 // the tail of the spliced document paragraph
285 if (!empty && last_paste + 1 != pit_type(pars.size())) {
286 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
287 mergeParagraph(buffer.params(), pars, last_paste);
288 } else if (pars[last_paste + 1].empty()) {
289 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
290 mergeParagraph(buffer.params(), pars, last_paste);
291 } else if (pars[last_paste].empty()) {
292 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
293 mergeParagraph(buffer.params(), pars, last_paste);
295 pars[last_paste + 1].stripLeadingSpaces();
300 return make_pair(PitPosPair(pit, pos), last_paste + 1);
304 PitPosPair eraseSelectionHelper(BufferParams const & params,
305 ParagraphList & pars,
306 pit_type startpit, pit_type endpit,
307 int startpos, int endpos, bool doclear)
309 // Start of selection is really invalid.
310 if (startpit == pit_type(pars.size()) ||
311 (startpos > pars[startpit].size()))
312 return PitPosPair(endpit, endpos);
314 // Start and end is inside same paragraph
315 if (endpit == pit_type(pars.size()) ||
316 startpit == endpit) {
317 endpos -= pars[startpit].erase(startpos, endpos);
318 return PitPosPair(endpit, endpos);
321 // A paragraph break has to be physically removed by merging, but
322 // only if either (1) change tracking is off, or (2) the para break
324 for (pit_type pit = startpit; pit != endpit + 1;) {
325 bool const merge = !params.tracking_changes ||
326 pars[pit].lookupChange(pars[pit].size()) ==
328 pos_type const left = ( pit == startpit ? startpos : 0 );
329 pos_type const right = ( pit == endpit ? endpos :
330 pars[pit].size() + 1 );
331 // Logical erase only:
332 pars[pit].erase(left, right);
333 // Separate handling of para break:
334 if (merge && pit != endpit &&
335 (pit + 1 != endpit || pars[pit].hasSameLayout(pars[pit + 1]))) {
336 pos_type const thissize = pars[pit].size();
338 pars[pit + 1].stripLeadingSpaces();
339 mergeParagraph(params, pars, pit);
347 // Ensure legal cursor pos:
350 return PitPosPair(endpit, endpos);
354 void copySelectionHelper(Buffer const & buf, ParagraphList & pars,
355 pit_type startpit, pit_type endpit,
356 int start, int end, textclass_type tc)
358 BOOST_ASSERT(0 <= start && start <= pars[startpit].size());
359 BOOST_ASSERT(0 <= end && end <= pars[endpit].size());
360 BOOST_ASSERT(startpit != endpit || start <= end);
362 // Clone the paragraphs within the selection.
363 ParagraphList paragraphs(boost::next(pars.begin(), startpit),
364 boost::next(pars.begin(), endpit + 1));
366 for_each(paragraphs.begin(), paragraphs.end(), resetParagraph(buf));
368 // Cut out the end of the last paragraph.
369 Paragraph & back = paragraphs.back();
370 back.erase(end, back.size());
372 // Cut out the begin of the first paragraph
373 Paragraph & front = paragraphs.front();
374 front.erase(0, start);
376 theCuts.push(make_pair(paragraphs, tc));
387 string grabAndEraseSelection(LCursor & cur)
389 if (!cur.selection())
391 string res = grabSelection(cur);
397 void switchBetweenClasses(textclass_type c1, textclass_type c2,
398 InsetText & in, ErrorList & errorlist)
400 BOOST_ASSERT(!in.paragraphs().empty());
404 LyXTextClass const & tclass1 = textclasslist[c1];
405 LyXTextClass const & tclass2 = textclasslist[c2];
408 ParIterator end = par_iterator_end(in);
409 for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
410 string const name = it->layout()->name();
411 bool hasLayout = tclass2.hasLayout(name);
414 it->layout(tclass2[name]);
416 it->layout(tclass2.defaultLayout());
418 if (!hasLayout && name != tclass1.defaultLayoutName()) {
419 docstring const s = bformat(
420 _("Layout had to be changed from\n%1$s to %2$s\n"
421 "because of class conversion from\n%3$s to %4$s"),
422 lyx::from_utf8(name), lyx::from_utf8(it->layout()->name()),
423 lyx::from_utf8(tclass1.name()), lyx::from_utf8(tclass2.name()));
424 // To warn the user that something had to be done.
425 errorlist.push_back(ErrorItem(_("Changed Layout"), s,
432 InsetIterator const i_end = inset_iterator_end(in);
433 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
434 if (it->lyxCode() == InsetBase::CHARSTYLE_CODE) {
435 InsetCharStyle & inset =
436 static_cast<InsetCharStyle &>(*it);
437 string const name = inset.params().type;
438 CharStyles::iterator const found_cs =
439 tclass2.charstyle(name);
440 if (found_cs == tclass2.charstyles().end()) {
441 // The character style is undefined in tclass2
442 inset.setUndefined();
443 docstring const s = bformat(_(
444 "Character style %1$s is "
445 "undefined because of class "
446 "conversion from\n%2$s to %3$s"),
447 lyx::from_utf8(name), lyx::from_utf8(tclass1.name()),
448 lyx::from_utf8(tclass2.name()));
449 // To warn the user that something had to be done.
450 errorlist.push_back(ErrorItem(
451 _("Undefined character style"),
452 s, it.paragraph().id(), it.pos(), it.pos() + 1));
453 } else if (inset.undefined()) {
454 // The character style is undefined in
455 // tclass1 and is defined in tclass2
456 inset.setDefined(found_cs);
463 std::vector<string> const availableSelections(Buffer const & buffer)
465 vector<string> selList;
467 CutStack::const_iterator cit = theCuts.begin();
468 CutStack::const_iterator end = theCuts.end();
469 for (; cit != end; ++cit) {
470 // we do not use cit-> here because gcc 2.9x does not
472 ParagraphList const & pars = (*cit).first;
474 ParagraphList::const_iterator pit = pars.begin();
475 ParagraphList::const_iterator pend = pars.end();
476 for (; pit != pend; ++pit) {
477 asciiSel += pit->asString(buffer, false);
478 if (asciiSel.size() > 25) {
479 asciiSel.replace(22, string::npos, "...");
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 cur.bv().owner()->gui().selection().put. (Lgb)
517 // cur.bv().owner()->gui().selection().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 cur.bv().owner()->gui().clipboard().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 std::string 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 par.insertChar(pos, (*cit), font);
685 cutSelection(cur, true, false);
687 // select the replacement
689 selbeg.pos() += str.length();
690 cur.setSelection(selbeg, -str.length());
692 cur.setSelection(selbeg, str.length());
696 void replaceSelection(LCursor & cur)
699 cutSelection(cur, true, false);
703 void eraseSelection(LCursor & cur)
705 //lyxerr << "LCursor::eraseSelection begin: " << cur << endl;
706 CursorSlice const & i1 = cur.selBegin();
707 CursorSlice const & i2 = cur.selEnd();
708 if (i1.inset().asInsetMath()) {
710 if (i1.idx() == i2.idx()) {
711 i1.cell().erase(i1.pos(), i2.pos());
712 // We may have deleted i1.cell(cur.pos()).
713 // Make sure that pos is valid.
714 if (cur.pos() > cur.lastpos())
715 cur.pos() = cur.lastpos();
717 InsetMath * p = i1.asInsetMath();
718 InsetBase::row_type r1, r2;
719 InsetBase::col_type c1, c2;
720 region(i1, i2, r1, r2, c1, c2);
721 for (InsetBase::row_type row = r1; row <= r2; ++row)
722 for (InsetBase::col_type col = c1; col <= c2; ++col)
723 p->cell(p->index(row, col)).clear();
724 // We've deleted the whole cell. Only pos 0 is valid.
727 // need a valid cursor. (Lgb)
728 cur.clearSelection();
730 lyxerr << "can't erase this selection 1" << endl;
732 //lyxerr << "LCursor::eraseSelection end: " << cur << endl;
736 void selDel(LCursor & cur)
738 //lyxerr << "LCursor::selDel" << endl;
744 void selClearOrDel(LCursor & cur)
746 //lyxerr << "LCursor::selClearOrDel" << endl;
747 if (lyxrc.auto_region_delete)
750 cur.selection() = false;
754 string grabSelection(LCursor const & cur)
756 if (!cur.selection())
759 // FIXME: What is wrong with the following?
761 std::ostringstream os;
762 for (DocIterator dit = cur.selectionBegin();
763 dit != cur.selectionEnd(); dit.forwardPos())
764 os << asString(dit.cell());
768 CursorSlice i1 = cur.selBegin();
769 CursorSlice i2 = cur.selEnd();
771 if (i1.idx() == i2.idx()) {
772 if (i1.inset().asInsetMath()) {
773 MathArray::const_iterator it = i1.cell().begin();
774 return asString(MathArray(it + i1.pos(), it + i2.pos()));
776 return "unknown selection 1";
780 InsetBase::row_type r1, r2;
781 InsetBase::col_type c1, c2;
782 region(i1, i2, r1, r2, c1, c2);
785 if (i1.inset().asInsetMath()) {
786 for (InsetBase::row_type row = r1; row <= r2; ++row) {
789 for (InsetBase::col_type col = c1; col <= c2; ++col) {
792 data += asString(i1.asInsetMath()->
793 cell(i1.asInsetMath()->index(row, col)));
797 data = "unknown selection 2";
803 void dirtyTabularStack(bool b)
805 dirty_tabular_stack_ = b;
809 bool tabularStackDirty()
811 return dirty_tabular_stack_;