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 <boost/tuple/tuple.hpp>
52 using lyx::textclass_type;
54 using lyx::support::bformat;
66 typedef std::pair<lyx::pit_type, int> PitPosPair;
68 typedef limited_stack<pair<ParagraphList, textclass_type> > CutStack;
72 // store whether the tabular stack is newer than the normal copy stack
73 // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
74 // when we (hopefully) have a one-for-all paste mechanism.
75 bool dirty_tabular_stack_;
77 class resetParagraph : public std::unary_function<Paragraph, Buffer const &> {
79 resetParagraph(Buffer const & b) : buffer_(b) {}
80 void operator()(Paragraph & p) const {
82 // ERT paragraphs have the Language latex_language.
83 // This is invalid outside of ERT, so we need to change it
84 // to the buffer language.
85 if (p.ownerCode() == InsetBase::ERT_CODE) {
86 p.changeLanguage(buffer_.params(), latex_language,
87 buffer_.getLanguage());
92 Buffer const & buffer_;
96 void region(CursorSlice const & i1, CursorSlice const & i2,
97 InsetBase::row_type & r1, InsetBase::row_type & r2,
98 InsetBase::col_type & c1, InsetBase::col_type & c2)
100 InsetBase & p = i1.inset();
101 c1 = p.col(i1.idx());
102 c2 = p.col(i2.idx());
105 r1 = p.row(i1.idx());
106 r2 = p.row(i2.idx());
112 bool checkPastePossible(int index)
114 return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
118 pair<PitPosPair, pit_type>
119 pasteSelectionHelper(Buffer const & buffer,
120 ParagraphList & pars, pit_type pit, int pos,
121 ParagraphList const & parlist, textclass_type textclass,
122 ErrorList & errorlist)
125 return make_pair(PitPosPair(pit, pos), pit);
127 BOOST_ASSERT (pos <= pars[pit].size());
129 // Make a copy of the CaP paragraphs.
130 ParagraphList insertion = parlist;
131 textclass_type const tc = buffer.params().textclass;
133 // Now remove all out of the pars which is NOT allowed in the
134 // new environment and set also another font if that is required.
136 // Convert newline to paragraph break in ERT inset.
137 // This should not be here!
138 if (pars[pit].inInset() &&
139 pars[pit].inInset()->lyxCode() == InsetBase::ERT_CODE) {
140 for (ParagraphList::size_type i = 0; i < insertion.size(); ++i) {
141 for (pos_type j = 0; j < insertion[i].size(); ++j) {
142 if (insertion[i].isNewline(j)) {
143 insertion[i].erase(j);
144 breakParagraphConservative(
152 // Make sure there is no class difference.
154 // This works without copying any paragraph data because we have
155 // a specialized swap method for ParagraphList. This is important
156 // since we store pointers to insets at some places and we don't
157 // want to invalidate them.
158 insertion.swap(in.paragraphs());
159 lyx::cap::switchBetweenClasses(textclass, tc, in, errorlist);
160 insertion.swap(in.paragraphs());
162 ParagraphList::iterator tmpbuf = insertion.begin();
163 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
165 Paragraph::depth_type max_depth = pars[pit].getMaxDepthAfter();
167 for (; tmpbuf != insertion.end(); ++tmpbuf) {
168 // If we have a negative jump so that the depth would
169 // go below 0 depth then we have to redo the delta to
170 // this new max depth level so that subsequent
171 // paragraphs are aligned correctly to this paragraph
173 if (int(tmpbuf->params().depth()) + depth_delta < 0)
176 // Set the right depth so that we are not too deep or shallow.
177 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
178 if (tmpbuf->params().depth() > max_depth)
179 tmpbuf->params().depth(max_depth);
181 // Only set this from the 2nd on as the 2nd depends
182 // for maxDepth still on pit.
183 if (tmpbuf != insertion.begin())
184 max_depth = tmpbuf->getMaxDepthAfter();
186 // Set the inset owner of this paragraph.
187 tmpbuf->setInsetOwner(pars[pit].inInset());
188 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
189 if (tmpbuf->getChar(i) == Paragraph::META_INSET &&
190 !pars[pit].insetAllowed(tmpbuf->getInset(i)->lyxCode()))
194 // reset change tracking status
195 if (buffer.params().tracking_changes)
196 tmpbuf->cleanChanges(Paragraph::trackingOn);
198 tmpbuf->cleanChanges(Paragraph::trackingOff);
201 bool const empty = pars[pit].empty();
203 // Make the buf exactly the same layout as the cursor
205 insertion.begin()->makeSameLayout(pars[pit]);
208 // Prepare the paragraphs and insets for insertion.
209 // A couple of insets store buffer references so need updating.
210 insertion.swap(in.paragraphs());
212 ParIterator fpit = par_iterator_begin(in);
213 ParIterator fend = par_iterator_end(in);
215 for (; fpit != fend; ++fpit) {
216 InsetList::iterator lit = fpit->insetlist.begin();
217 InsetList::iterator eit = fpit->insetlist.end();
219 for (; lit != eit; ++lit) {
220 switch (lit->inset->lyxCode()) {
221 case InsetBase::TABULAR_CODE: {
222 InsetTabular * it = static_cast<InsetTabular*>(lit->inset);
232 insertion.swap(in.paragraphs());
234 // Split the paragraph for inserting the buf if necessary.
236 breakParagraphConservative(buffer.params(), pars, pit, pos);
240 pars.insert(boost::next(pars.begin(), pit),
244 // merge the empty par with the last par of the insertion
245 mergeParagraph(buffer.params(), pars,
246 pit + insertion.size() - 1);
248 pars.insert(boost::next(pars.begin(), pit + 1),
252 // merge the first par of the insertion with the current par
253 mergeParagraph(buffer.params(), pars, pit);
256 pit_type last_paste = pit + insertion.size() - 1;
258 // Store the new cursor position.
260 pos = pars[last_paste].size();
262 // Join (conditionally) last pasted paragraph with next one, i.e.,
263 // the tail of the spliced document paragraph
264 if (!empty && last_paste + 1 != pit_type(pars.size())) {
265 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
266 mergeParagraph(buffer.params(), pars, last_paste);
267 } else if (pars[last_paste + 1].empty()) {
268 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
269 mergeParagraph(buffer.params(), pars, last_paste);
270 } else if (pars[last_paste].empty()) {
271 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
272 mergeParagraph(buffer.params(), pars, last_paste);
274 pars[last_paste + 1].stripLeadingSpaces();
279 return make_pair(PitPosPair(pit, pos), last_paste + 1);
283 PitPosPair eraseSelectionHelper(BufferParams const & params,
284 ParagraphList & pars,
285 pit_type startpit, pit_type endpit,
286 int startpos, int endpos, bool doclear)
288 // Start of selection is really invalid.
289 if (startpit == pit_type(pars.size()) ||
290 (startpos > pars[startpit].size()))
291 return PitPosPair(endpit, endpos);
293 // Start and end is inside same paragraph
294 if (endpit == pit_type(pars.size()) ||
295 startpit == endpit) {
296 endpos -= pars[startpit].erase(startpos, endpos);
297 return PitPosPair(endpit, endpos);
300 // A paragraph break has to be physically removed by merging, but
301 // only if either (1) change tracking is off, or (2) the para break
303 for (pit_type pit = startpit; pit != endpit + 1;) {
304 bool const merge = !params.tracking_changes ||
305 pars[pit].lookupChange(pars[pit].size()) ==
307 pos_type const left = ( pit == startpit ? startpos : 0 );
308 pos_type const right = ( pit == endpit ? endpos :
309 pars[pit].size() + 1 );
310 // Logical erase only:
311 pars[pit].erase(left, right);
312 // Separate handling of para break:
313 if (merge && pit != endpit &&
314 (pit + 1 != endpit || pars[pit].hasSameLayout(pars[pit + 1]))) {
315 pos_type const thissize = pars[pit].size();
317 pars[pit + 1].stripLeadingSpaces();
318 mergeParagraph(params, pars, pit);
326 // Ensure legal cursor pos:
329 return PitPosPair(endpit, endpos);
333 void copySelectionHelper(Buffer const & buf, ParagraphList & pars,
334 pit_type startpit, pit_type endpit,
335 int start, int end, textclass_type tc)
337 BOOST_ASSERT(0 <= start && start <= pars[startpit].size());
338 BOOST_ASSERT(0 <= end && end <= pars[endpit].size());
339 BOOST_ASSERT(startpit != endpit || start <= end);
341 // Clone the paragraphs within the selection.
342 ParagraphList paragraphs(boost::next(pars.begin(), startpit),
343 boost::next(pars.begin(), endpit + 1));
345 for_each(paragraphs.begin(), paragraphs.end(), resetParagraph(buf));
347 // Cut out the end of the last paragraph.
348 Paragraph & back = paragraphs.back();
349 back.erase(end, back.size());
351 // Cut out the begin of the first paragraph
352 Paragraph & front = paragraphs.front();
353 front.erase(0, start);
355 theCuts.push(make_pair(paragraphs, tc));
366 string grabAndEraseSelection(LCursor & cur)
368 if (!cur.selection())
370 string res = grabSelection(cur);
376 void switchBetweenClasses(textclass_type c1, textclass_type c2,
377 InsetText & in, ErrorList & errorlist)
379 BOOST_ASSERT(!in.paragraphs().empty());
383 LyXTextClass const & tclass1 = textclasslist[c1];
384 LyXTextClass const & tclass2 = textclasslist[c2];
387 ParIterator end = par_iterator_end(in);
388 for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
389 string const name = it->layout()->name();
390 bool hasLayout = tclass2.hasLayout(name);
393 it->layout(tclass2[name]);
395 it->layout(tclass2.defaultLayout());
397 if (!hasLayout && name != tclass1.defaultLayoutName()) {
398 string const s = bformat(
399 _("Layout had to be changed from\n%1$s to %2$s\n"
400 "because of class conversion from\n%3$s to %4$s"),
401 name, it->layout()->name(), tclass1.name(), tclass2.name());
402 // To warn the user that something had to be done.
403 errorlist.push_back(ErrorItem(_("Changed Layout"), s,
410 InsetIterator const i_end = inset_iterator_end(in);
411 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
412 if (it->lyxCode() == InsetBase::CHARSTYLE_CODE) {
413 InsetCharStyle & inset =
414 static_cast<InsetCharStyle &>(*it);
415 string const name = inset.params().type;
416 CharStyles::iterator const found_cs =
417 tclass2.charstyle(name);
418 if (found_cs == tclass2.charstyles().end()) {
419 // The character style is undefined in tclass2
420 inset.setUndefined();
421 string const s = bformat(_(
422 "Character style %1$s is "
423 "undefined because of class "
424 "conversion from\n%2$s to %3$s"),
425 name, tclass1.name(), tclass2.name());
426 // To warn the user that something had to be done.
427 errorlist.push_back(ErrorItem(
428 _("Undefined character style"),
429 s, it.paragraph().id(),
430 it.pos(), it.pos() + 1));
431 } else if (inset.undefined()) {
432 // The character style is undefined in
433 // tclass1 and is defined in tclass2
434 inset.setDefined(found_cs);
441 std::vector<string> const availableSelections(Buffer const & buffer)
443 vector<string> selList;
445 CutStack::const_iterator cit = theCuts.begin();
446 CutStack::const_iterator end = theCuts.end();
447 for (; cit != end; ++cit) {
448 // we do not use cit-> here because gcc 2.9x does not
450 ParagraphList const & pars = (*cit).first;
452 ParagraphList::const_iterator pit = pars.begin();
453 ParagraphList::const_iterator pend = pars.end();
454 for (; pit != pend; ++pit) {
455 asciiSel += pit->asString(buffer, false);
456 if (asciiSel.size() > 25) {
457 asciiSel.replace(22, string::npos, "...");
462 selList.push_back(asciiSel);
469 lyx::size_type numberOfSelections()
471 return theCuts.size();
475 void cutSelection(LCursor & cur, bool doclear, bool realcut)
477 // This doesn't make sense, if there is no selection
478 if (!cur.selection())
481 // OK, we have a selection. This is always between cur.selBegin()
484 if (cur.inTexted()) {
485 LyXText * text = cur.text();
487 // Stuff what we got on the clipboard. Even if there is no selection.
489 // There is a problem with having the stuffing here in that the
490 // larger the selection the slower LyX will get. This can be
491 // solved by running the line below only when the selection has
492 // finished. The solution used currently just works, to make it
493 // faster we need to be more clever and probably also have more
494 // calls to stuffClipboard. (Lgb)
495 // cur.bv().stuffClipboard(cur.selectionAsString(true));
497 // make sure that the depth behind the selection are restored, too
498 recordUndoSelection(cur);
499 pit_type begpit = cur.selBegin().pit();
500 pit_type endpit = cur.selEnd().pit();
502 int endpos = cur.selEnd().pos();
504 BufferParams const & bp = cur.buffer().params();
506 copySelectionHelper(cur.buffer(),
509 cur.selBegin().pos(), endpos,
513 boost::tie(endpit, endpos) =
514 eraseSelectionHelper(bp,
517 cur.selBegin().pos(), endpos,
520 // sometimes necessary
522 text->paragraphs()[begpit].stripLeadingSpaces();
524 // cutSelection can invalidate the cursor so we need to set
526 // we prefer the end for when tracking changes
530 // need a valid cursor. (Lgb)
531 cur.clearSelection();
532 updateLabels(cur.buffer());
534 // tell tabular that a recent copy happened
535 dirtyTabularStack(false);
538 if (cur.inMathed()) {
539 if (cur.selBegin().idx() != cur.selEnd().idx()) {
540 // The current selection spans more than one cell.
542 recordUndoInset(cur);
544 // Record only the current cell to avoid a jumping
555 void copySelection(LCursor & cur)
557 // stuff the selection onto the X clipboard, from an explicit copy request
558 cur.bv().stuffClipboard(cur.selectionAsString(true));
560 // this doesn't make sense, if there is no selection
561 if (!cur.selection())
564 if (cur.inTexted()) {
565 LyXText * text = cur.text();
567 // ok we have a selection. This is always between cur.selBegin()
568 // and sel_end cursor
570 // copy behind a space if there is one
571 ParagraphList & pars = text->paragraphs();
572 pos_type pos = cur.selBegin().pos();
573 pit_type par = cur.selBegin().pit();
574 while (pos < pars[par].size()
575 && pars[par].isLineSeparator(pos)
576 && (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
579 copySelectionHelper(cur.buffer(), pars, par, cur.selEnd().pit(),
580 pos, cur.selEnd().pos(), cur.buffer().params().textclass);
583 if (cur.inMathed()) {
584 lyxerr << "copySelection in mathed" << endl;
586 pars.push_back(Paragraph());
587 BufferParams const & bp = cur.buffer().params();
588 pars.back().layout(bp.getLyXTextClass().defaultLayout());
589 for_each(pars.begin(), pars.end(), resetParagraph(cur.buffer()));
590 pars.back().insert(0, grabSelection(cur), LyXFont());
591 theCuts.push(make_pair(pars, bp.textclass));
593 // tell tabular that a recent copy happened
594 dirtyTabularStack(false);
598 std::string getSelection(Buffer const & buf, size_t sel_index)
600 return sel_index < theCuts.size()
601 ? theCuts[sel_index].first.back().asString(buf, false)
606 void pasteParagraphList(LCursor & cur, ParagraphList const & parlist,
607 textclass_type textclass)
609 if (cur.inTexted()) {
610 LyXText * text = cur.text();
619 boost::tie(ppp, endpit) =
620 pasteSelectionHelper(cur.buffer(),
622 cur.pit(), cur.pos(),
625 bufferErrors(cur.buffer(), el);
626 updateLabels(cur.buffer());
627 cur.clearSelection();
628 text->setCursor(cur, ppp.first, ppp.second);
631 // mathed is handled in MathNestInset/MathGridInset
632 BOOST_ASSERT(!cur.inMathed());
636 void pasteSelection(LCursor & cur, size_t sel_index)
638 // this does not make sense, if there is nothing to paste
639 if (!checkPastePossible(sel_index))
642 pasteParagraphList(cur, theCuts[sel_index].first,
643 theCuts[sel_index].second);
644 cur.bv().showErrorList(_("Paste"));
649 void setSelectionRange(LCursor & cur, pos_type length)
651 LyXText * text = cur.text();
657 text->cursorRight(cur);
662 // simple replacing. The font of the first selected character is used
663 void replaceSelectionWithString(LCursor & cur, string const & str)
665 LyXText * text = cur.text();
669 // Get font setting before we cut
670 pos_type pos = cur.selEnd().pos();
671 Paragraph & par = text->getPar(cur.selEnd().pit());
673 par.getFontSettings(cur.buffer().params(), cur.selBegin().pos());
675 // Insert the new string
676 string::const_iterator cit = str.begin();
677 string::const_iterator end = str.end();
678 for (; cit != end; ++cit, ++pos)
679 par.insertChar(pos, (*cit), font);
682 cutSelection(cur, true, false);
686 void replaceSelection(LCursor & cur)
689 cutSelection(cur, true, false);
693 // only used by the spellchecker
694 void replaceWord(LCursor & cur, string const & replacestring)
696 LyXText * text = cur.text();
699 replaceSelectionWithString(cur, replacestring);
700 setSelectionRange(cur, replacestring.length());
702 // Go back so that replacement string is also spellchecked
703 for (string::size_type i = 0; i < replacestring.length() + 1; ++i)
704 text->cursorLeft(cur);
708 void eraseSelection(LCursor & cur)
710 //lyxerr << "LCursor::eraseSelection begin: " << cur << endl;
711 CursorSlice const & i1 = cur.selBegin();
712 CursorSlice const & i2 = cur.selEnd();
713 if (i1.inset().asMathInset()) {
715 if (i1.idx() == i2.idx()) {
716 i1.cell().erase(i1.pos(), i2.pos());
717 // We may have deleted i1.cell(cur.pos()).
718 // Make sure that pos is valid.
719 if (cur.pos() > cur.lastpos())
720 cur.pos() = cur.lastpos();
722 MathInset * p = i1.asMathInset();
723 InsetBase::row_type r1, r2;
724 InsetBase::col_type c1, c2;
725 region(i1, i2, r1, r2, c1, c2);
726 for (InsetBase::row_type row = r1; row <= r2; ++row)
727 for (InsetBase::col_type col = c1; col <= c2; ++col)
728 p->cell(p->index(row, col)).clear();
729 // We've deleted the whole cell. Only pos 0 is valid.
732 // need a valid cursor. (Lgb)
733 cur.clearSelection();
735 lyxerr << "can't erase this selection 1" << endl;
737 //lyxerr << "LCursor::eraseSelection end: " << cur << endl;
741 void selDel(LCursor & cur)
743 //lyxerr << "LCursor::selDel" << endl;
749 void selClearOrDel(LCursor & cur)
751 //lyxerr << "LCursor::selClearOrDel" << endl;
752 if (lyxrc.auto_region_delete)
755 cur.selection() = false;
759 string grabSelection(LCursor const & cur)
761 if (!cur.selection())
764 // FIXME: What is wrong with the following?
766 std::ostringstream os;
767 for (DocIterator dit = cur.selectionBegin();
768 dit != cur.selectionEnd(); dit.forwardPos())
769 os << asString(dit.cell());
773 CursorSlice i1 = cur.selBegin();
774 CursorSlice i2 = cur.selEnd();
776 if (i1.idx() == i2.idx()) {
777 if (i1.inset().asMathInset()) {
778 MathArray::const_iterator it = i1.cell().begin();
779 return asString(MathArray(it + i1.pos(), it + i2.pos()));
781 return "unknown selection 1";
785 InsetBase::row_type r1, r2;
786 InsetBase::col_type c1, c2;
787 region(i1, i2, r1, r2, c1, c2);
790 if (i1.inset().asMathInset()) {
791 for (InsetBase::row_type row = r1; row <= r2; ++row) {
794 for (InsetBase::col_type col = c1; col <= c2; ++col) {
797 data += asString(i1.asMathInset()->
798 cell(i1.asMathInset()->index(row, col)));
802 data = "unknown selection 2";
808 void dirtyTabularStack(bool b)
810 dirty_tabular_stack_ = b;
814 bool tabularStackDirty()
816 return dirty_tabular_stack_;