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/math_data.h"
43 #include "mathed/math_inset.h"
44 #include "mathed/math_support.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(Buffer const & buffer,
127 ParagraphList & pars, pit_type pit, int pos,
128 ParagraphList const & parlist, textclass_type textclass,
129 ErrorList & errorlist)
132 return make_pair(PitPosPair(pit, pos), pit);
134 BOOST_ASSERT (pos <= pars[pit].size());
136 // Make a copy of the CaP paragraphs.
137 ParagraphList insertion = parlist;
138 textclass_type const tc = buffer.params().textclass;
140 // Now remove all out of the pars which is NOT allowed in the
141 // new environment and set also another font if that is required.
143 // Convert newline to paragraph break in ERT inset.
144 // This should not be here!
145 if (pars[pit].inInset() &&
146 pars[pit].inInset()->lyxCode() == InsetBase::ERT_CODE) {
147 for (ParagraphList::size_type i = 0; i < insertion.size(); ++i) {
148 for (pos_type j = 0; j < insertion[i].size(); ++j) {
149 if (insertion[i].isNewline(j)) {
150 insertion[i].erase(j);
151 breakParagraphConservative(
159 // Make sure there is no class difference.
161 // This works without copying any paragraph data because we have
162 // a specialized swap method for ParagraphList. This is important
163 // since we store pointers to insets at some places and we don't
164 // want to invalidate them.
165 insertion.swap(in.paragraphs());
166 lyx::cap::switchBetweenClasses(textclass, tc, in, errorlist);
167 insertion.swap(in.paragraphs());
169 ParagraphList::iterator tmpbuf = insertion.begin();
170 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
172 Paragraph::depth_type max_depth = pars[pit].getMaxDepthAfter();
174 for (; tmpbuf != insertion.end(); ++tmpbuf) {
175 // If we have a negative jump so that the depth would
176 // go below 0 depth then we have to redo the delta to
177 // this new max depth level so that subsequent
178 // paragraphs are aligned correctly to this paragraph
180 if (int(tmpbuf->params().depth()) + depth_delta < 0)
183 // Set the right depth so that we are not too deep or shallow.
184 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
185 if (tmpbuf->params().depth() > max_depth)
186 tmpbuf->params().depth(max_depth);
188 // Only set this from the 2nd on as the 2nd depends
189 // for maxDepth still on pit.
190 if (tmpbuf != insertion.begin())
191 max_depth = tmpbuf->getMaxDepthAfter();
193 // Set the inset owner of this paragraph.
194 tmpbuf->setInsetOwner(pars[pit].inInset());
195 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
196 if (tmpbuf->getChar(i) == Paragraph::META_INSET &&
197 !pars[pit].insetAllowed(tmpbuf->getInset(i)->lyxCode()))
201 // reset change tracking status
202 if (buffer.params().tracking_changes)
203 tmpbuf->cleanChanges(Paragraph::trackingOn);
205 tmpbuf->cleanChanges(Paragraph::trackingOff);
208 bool const empty = pars[pit].empty();
210 // Make the buf exactly the same layout as the cursor
212 insertion.begin()->makeSameLayout(pars[pit]);
215 // Prepare the paragraphs and insets for insertion.
216 // A couple of insets store buffer references so need updating.
217 insertion.swap(in.paragraphs());
219 ParIterator fpit = par_iterator_begin(in);
220 ParIterator fend = par_iterator_end(in);
222 for (; fpit != fend; ++fpit) {
223 InsetList::iterator lit = fpit->insetlist.begin();
224 InsetList::iterator eit = fpit->insetlist.end();
226 for (; lit != eit; ++lit) {
227 switch (lit->inset->lyxCode()) {
228 case InsetBase::TABULAR_CODE: {
229 InsetTabular * it = static_cast<InsetTabular*>(lit->inset);
239 insertion.swap(in.paragraphs());
241 // Split the paragraph for inserting the buf if necessary.
243 breakParagraphConservative(buffer.params(), pars, pit, pos);
247 pars.insert(boost::next(pars.begin(), pit),
251 // merge the empty par with the last par of the insertion
252 mergeParagraph(buffer.params(), pars,
253 pit + insertion.size() - 1);
255 pars.insert(boost::next(pars.begin(), pit + 1),
259 // merge the first par of the insertion with the current par
260 mergeParagraph(buffer.params(), pars, pit);
263 pit_type last_paste = pit + insertion.size() - 1;
265 // Store the new cursor position.
267 pos = pars[last_paste].size();
269 // Join (conditionally) last pasted paragraph with next one, i.e.,
270 // the tail of the spliced document paragraph
271 if (!empty && last_paste + 1 != pit_type(pars.size())) {
272 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
273 mergeParagraph(buffer.params(), pars, last_paste);
274 } else if (pars[last_paste + 1].empty()) {
275 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
276 mergeParagraph(buffer.params(), pars, last_paste);
277 } else if (pars[last_paste].empty()) {
278 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
279 mergeParagraph(buffer.params(), pars, last_paste);
281 pars[last_paste + 1].stripLeadingSpaces();
286 return make_pair(PitPosPair(pit, pos), last_paste + 1);
290 PitPosPair eraseSelectionHelper(BufferParams const & params,
291 ParagraphList & pars,
292 pit_type startpit, pit_type endpit,
293 int startpos, int endpos, bool doclear)
295 // Start of selection is really invalid.
296 if (startpit == pit_type(pars.size()) ||
297 (startpos > pars[startpit].size()))
298 return PitPosPair(endpit, endpos);
300 // Start and end is inside same paragraph
301 if (endpit == pit_type(pars.size()) ||
302 startpit == endpit) {
303 endpos -= pars[startpit].erase(startpos, endpos);
304 return PitPosPair(endpit, endpos);
307 // A paragraph break has to be physically removed by merging, but
308 // only if either (1) change tracking is off, or (2) the para break
310 for (pit_type pit = startpit; pit != endpit + 1;) {
311 bool const merge = !params.tracking_changes ||
312 pars[pit].lookupChange(pars[pit].size()) ==
314 pos_type const left = ( pit == startpit ? startpos : 0 );
315 pos_type const right = ( pit == endpit ? endpos :
316 pars[pit].size() + 1 );
317 // Logical erase only:
318 pars[pit].erase(left, right);
319 // Separate handling of para break:
320 if (merge && pit != endpit &&
321 (pit + 1 != endpit || pars[pit].hasSameLayout(pars[pit + 1]))) {
322 pos_type const thissize = pars[pit].size();
324 pars[pit + 1].stripLeadingSpaces();
325 mergeParagraph(params, pars, pit);
333 // Ensure legal cursor pos:
336 return PitPosPair(endpit, endpos);
340 void copySelectionHelper(Buffer const & buf, ParagraphList & pars,
341 pit_type startpit, pit_type endpit,
342 int start, int end, textclass_type tc)
344 BOOST_ASSERT(0 <= start && start <= pars[startpit].size());
345 BOOST_ASSERT(0 <= end && end <= pars[endpit].size());
346 BOOST_ASSERT(startpit != endpit || start <= end);
348 // Clone the paragraphs within the selection.
349 ParagraphList paragraphs(boost::next(pars.begin(), startpit),
350 boost::next(pars.begin(), endpit + 1));
352 for_each(paragraphs.begin(), paragraphs.end(), resetParagraph(buf));
354 // Cut out the end of the last paragraph.
355 Paragraph & back = paragraphs.back();
356 back.erase(end, back.size());
358 // Cut out the begin of the first paragraph
359 Paragraph & front = paragraphs.front();
360 front.erase(0, start);
362 theCuts.push(make_pair(paragraphs, tc));
373 string grabAndEraseSelection(LCursor & cur)
375 if (!cur.selection())
377 string res = grabSelection(cur);
383 void switchBetweenClasses(textclass_type c1, textclass_type c2,
384 InsetText & in, ErrorList & errorlist)
386 BOOST_ASSERT(!in.paragraphs().empty());
390 LyXTextClass const & tclass1 = textclasslist[c1];
391 LyXTextClass const & tclass2 = textclasslist[c2];
394 ParIterator end = par_iterator_end(in);
395 for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
396 string const name = it->layout()->name();
397 bool hasLayout = tclass2.hasLayout(name);
400 it->layout(tclass2[name]);
402 it->layout(tclass2.defaultLayout());
404 if (!hasLayout && name != tclass1.defaultLayoutName()) {
405 string const s = bformat(
406 _("Layout had to be changed from\n%1$s to %2$s\n"
407 "because of class conversion from\n%3$s to %4$s"),
408 name, it->layout()->name(), tclass1.name(), tclass2.name());
409 // To warn the user that something had to be done.
410 errorlist.push_back(ErrorItem(_("Changed Layout"), s,
417 InsetIterator const i_end = inset_iterator_end(in);
418 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
419 if (it->lyxCode() == InsetBase::CHARSTYLE_CODE) {
420 InsetCharStyle & inset =
421 static_cast<InsetCharStyle &>(*it);
422 string const name = inset.params().type;
423 CharStyles::iterator const found_cs =
424 tclass2.charstyle(name);
425 if (found_cs == tclass2.charstyles().end()) {
426 // The character style is undefined in tclass2
427 inset.setUndefined();
428 string const s = bformat(_(
429 "Character style %1$s is "
430 "undefined because of class "
431 "conversion from\n%2$s to %3$s"),
432 name, tclass1.name(), tclass2.name());
433 // To warn the user that something had to be done.
434 errorlist.push_back(ErrorItem(
435 _("Undefined character style"),
436 s, it.paragraph().id(),
437 it.pos(), it.pos() + 1));
438 } else if (inset.undefined()) {
439 // The character style is undefined in
440 // tclass1 and is defined in tclass2
441 inset.setDefined(found_cs);
448 std::vector<string> const availableSelections(Buffer const & buffer)
450 vector<string> selList;
452 CutStack::const_iterator cit = theCuts.begin();
453 CutStack::const_iterator end = theCuts.end();
454 for (; cit != end; ++cit) {
455 // we do not use cit-> here because gcc 2.9x does not
457 ParagraphList const & pars = (*cit).first;
459 ParagraphList::const_iterator pit = pars.begin();
460 ParagraphList::const_iterator pend = pars.end();
461 for (; pit != pend; ++pit) {
462 asciiSel += pit->asString(buffer, false);
463 if (asciiSel.size() > 25) {
464 asciiSel.replace(22, string::npos, "...");
469 selList.push_back(asciiSel);
476 lyx::size_type numberOfSelections()
478 return theCuts.size();
482 void cutSelection(LCursor & cur, bool doclear, bool realcut)
484 // This doesn't make sense, if there is no selection
485 if (!cur.selection())
488 // OK, we have a selection. This is always between cur.selBegin()
491 if (cur.inTexted()) {
492 LyXText * text = cur.text();
494 // Stuff what we got on the clipboard. Even if there is no selection.
496 // There is a problem with having the stuffing here in that the
497 // larger the selection the slower LyX will get. This can be
498 // solved by running the line below only when the selection has
499 // finished. The solution used currently just works, to make it
500 // faster we need to be more clever and probably also have more
501 // calls to cur.bv().owner()->gui().selection().put. (Lgb)
502 // cur.bv().owner()->gui().selection().put(cur.selectionAsString(true));
505 // make sure that the depth behind the selection are restored, too
506 recordUndoSelection(cur);
507 pit_type begpit = cur.selBegin().pit();
508 pit_type endpit = cur.selEnd().pit();
510 int endpos = cur.selEnd().pos();
512 BufferParams const & bp = cur.buffer().params();
514 copySelectionHelper(cur.buffer(),
517 cur.selBegin().pos(), endpos,
521 boost::tie(endpit, endpos) =
522 eraseSelectionHelper(bp,
525 cur.selBegin().pos(), endpos,
528 // sometimes necessary
530 text->paragraphs()[begpit].stripLeadingSpaces();
532 // cutSelection can invalidate the cursor so we need to set
534 // we prefer the end for when tracking changes
538 // need a valid cursor. (Lgb)
539 cur.clearSelection();
540 updateLabels(cur.buffer());
542 // tell tabular that a recent copy happened
543 dirtyTabularStack(false);
546 if (cur.inMathed()) {
547 if (cur.selBegin().idx() != cur.selEnd().idx()) {
548 // The current selection spans more than one cell.
550 recordUndoInset(cur);
552 // Record only the current cell to avoid a jumping
563 void copySelection(LCursor & cur)
565 // stuff the selection onto the X clipboard, from an explicit copy request
566 cur.bv().owner()->gui().clipboard().put(cur.selectionAsString(true));
568 // this doesn't make sense, if there is no selection
569 if (!cur.selection())
572 if (cur.inTexted()) {
573 LyXText * text = cur.text();
575 // ok we have a selection. This is always between cur.selBegin()
576 // and sel_end cursor
578 // copy behind a space if there is one
579 ParagraphList & pars = text->paragraphs();
580 pos_type pos = cur.selBegin().pos();
581 pit_type par = cur.selBegin().pit();
582 while (pos < pars[par].size()
583 && pars[par].isLineSeparator(pos)
584 && (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
587 copySelectionHelper(cur.buffer(), pars, par, cur.selEnd().pit(),
588 pos, cur.selEnd().pos(), cur.buffer().params().textclass);
591 if (cur.inMathed()) {
592 //lyxerr << "copySelection in mathed" << endl;
594 pars.push_back(Paragraph());
595 BufferParams const & bp = cur.buffer().params();
596 pars.back().layout(bp.getLyXTextClass().defaultLayout());
597 for_each(pars.begin(), pars.end(), resetParagraph(cur.buffer()));
598 pars.back().insert(0, grabSelection(cur), LyXFont());
599 theCuts.push(make_pair(pars, bp.textclass));
601 // tell tabular that a recent copy happened
602 dirtyTabularStack(false);
606 std::string getSelection(Buffer const & buf, size_t sel_index)
608 return sel_index < theCuts.size()
609 ? theCuts[sel_index].first.back().asString(buf, false)
614 void pasteParagraphList(LCursor & cur, ParagraphList const & parlist,
615 textclass_type textclass)
617 if (cur.inTexted()) {
618 LyXText * text = cur.text();
627 boost::tie(ppp, endpit) =
628 pasteSelectionHelper(cur.buffer(),
630 cur.pit(), cur.pos(),
633 bufferErrors(cur.buffer(), el);
634 updateLabels(cur.buffer());
635 cur.clearSelection();
636 text->setCursor(cur, ppp.first, ppp.second);
639 // mathed is handled in MathNestInset/MathGridInset
640 BOOST_ASSERT(!cur.inMathed());
644 void pasteSelection(LCursor & cur, size_t sel_index)
646 // this does not make sense, if there is nothing to paste
647 if (!checkPastePossible(sel_index))
650 pasteParagraphList(cur, theCuts[sel_index].first,
651 theCuts[sel_index].second);
652 cur.bv().owner()->showErrorList(_("Paste"));
657 void setSelectionRange(LCursor & cur, pos_type length)
659 LyXText * text = cur.text();
665 text->cursorRight(cur);
670 // simple replacing. The font of the first selected character is used
671 void replaceSelectionWithString(LCursor & cur, string const & str)
673 LyXText * text = cur.text();
677 // Get font setting before we cut
678 pos_type pos = cur.selEnd().pos();
679 Paragraph & par = text->getPar(cur.selEnd().pit());
681 par.getFontSettings(cur.buffer().params(), cur.selBegin().pos());
683 // Insert the new string
684 string::const_iterator cit = str.begin();
685 string::const_iterator end = str.end();
686 for (; cit != end; ++cit, ++pos)
687 par.insertChar(pos, (*cit), font);
690 cutSelection(cur, true, false);
694 void replaceSelection(LCursor & cur)
697 cutSelection(cur, true, false);
701 // only used by the spellchecker
702 void replaceWord(LCursor & cur, string const & replacestring)
704 LyXText * text = cur.text();
707 replaceSelectionWithString(cur, replacestring);
708 setSelectionRange(cur, replacestring.length());
710 // Go back so that replacement string is also spellchecked
711 for (string::size_type i = 0; i < replacestring.length() + 1; ++i)
712 text->cursorLeft(cur);
716 void eraseSelection(LCursor & cur)
718 //lyxerr << "LCursor::eraseSelection begin: " << cur << endl;
719 CursorSlice const & i1 = cur.selBegin();
720 CursorSlice const & i2 = cur.selEnd();
721 if (i1.inset().asMathInset()) {
723 if (i1.idx() == i2.idx()) {
724 i1.cell().erase(i1.pos(), i2.pos());
725 // We may have deleted i1.cell(cur.pos()).
726 // Make sure that pos is valid.
727 if (cur.pos() > cur.lastpos())
728 cur.pos() = cur.lastpos();
730 MathInset * p = i1.asMathInset();
731 InsetBase::row_type r1, r2;
732 InsetBase::col_type c1, c2;
733 region(i1, i2, r1, r2, c1, c2);
734 for (InsetBase::row_type row = r1; row <= r2; ++row)
735 for (InsetBase::col_type col = c1; col <= c2; ++col)
736 p->cell(p->index(row, col)).clear();
737 // We've deleted the whole cell. Only pos 0 is valid.
740 // need a valid cursor. (Lgb)
741 cur.clearSelection();
743 lyxerr << "can't erase this selection 1" << endl;
745 //lyxerr << "LCursor::eraseSelection end: " << cur << endl;
749 void selDel(LCursor & cur)
751 //lyxerr << "LCursor::selDel" << endl;
757 void selClearOrDel(LCursor & cur)
759 //lyxerr << "LCursor::selClearOrDel" << endl;
760 if (lyxrc.auto_region_delete)
763 cur.selection() = false;
767 string grabSelection(LCursor const & cur)
769 if (!cur.selection())
772 // FIXME: What is wrong with the following?
774 std::ostringstream os;
775 for (DocIterator dit = cur.selectionBegin();
776 dit != cur.selectionEnd(); dit.forwardPos())
777 os << asString(dit.cell());
781 CursorSlice i1 = cur.selBegin();
782 CursorSlice i2 = cur.selEnd();
784 if (i1.idx() == i2.idx()) {
785 if (i1.inset().asMathInset()) {
786 MathArray::const_iterator it = i1.cell().begin();
787 return asString(MathArray(it + i1.pos(), it + i2.pos()));
789 return "unknown selection 1";
793 InsetBase::row_type r1, r2;
794 InsetBase::col_type c1, c2;
795 region(i1, i2, r1, r2, c1, c2);
798 if (i1.inset().asMathInset()) {
799 for (InsetBase::row_type row = r1; row <= r2; ++row) {
802 for (InsetBase::col_type col = c1; col <= c2; ++col) {
805 data += asString(i1.asMathInset()->
806 cell(i1.asMathInset()->index(row, col)));
810 data = "unknown selection 2";
816 void dirtyTabularStack(bool b)
818 dirty_tabular_stack_ = b;
822 bool tabularStackDirty()
824 return dirty_tabular_stack_;