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.
153 lyx::cap::switchBetweenClasses(textclass, tc, insertion, errorlist);
155 ParagraphList::iterator tmpbuf = insertion.begin();
156 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
158 Paragraph::depth_type max_depth = pars[pit].getMaxDepthAfter();
160 for (; tmpbuf != insertion.end(); ++tmpbuf) {
161 // If we have a negative jump so that the depth would
162 // go below 0 depth then we have to redo the delta to
163 // this new max depth level so that subsequent
164 // paragraphs are aligned correctly to this paragraph
166 if (int(tmpbuf->params().depth()) + depth_delta < 0)
169 // Set the right depth so that we are not too deep or shallow.
170 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
171 if (tmpbuf->params().depth() > max_depth)
172 tmpbuf->params().depth(max_depth);
174 // Only set this from the 2nd on as the 2nd depends
175 // for maxDepth still on pit.
176 if (tmpbuf != insertion.begin())
177 max_depth = tmpbuf->getMaxDepthAfter();
179 // Set the inset owner of this paragraph.
180 tmpbuf->setInsetOwner(pars[pit].inInset());
181 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
182 if (tmpbuf->getChar(i) == Paragraph::META_INSET &&
183 !pars[pit].insetAllowed(tmpbuf->getInset(i)->lyxCode()))
187 // reset change tracking status
188 if (buffer.params().tracking_changes)
189 tmpbuf->cleanChanges(Paragraph::trackingOn);
191 tmpbuf->cleanChanges(Paragraph::trackingOff);
194 bool const empty = pars[pit].empty();
196 // Make the buf exactly the same layout as the cursor
198 insertion.begin()->makeSameLayout(pars[pit]);
201 // Prepare the paragraphs and insets for insertion.
202 // A couple of insets store buffer references so need updating.
204 std::swap(in.paragraphs(), insertion);
206 ParIterator fpit = par_iterator_begin(in);
207 ParIterator fend = par_iterator_end(in);
209 for (; fpit != fend; ++fpit) {
210 InsetList::iterator lit = fpit->insetlist.begin();
211 InsetList::iterator eit = fpit->insetlist.end();
213 for (; lit != eit; ++lit) {
214 switch (lit->inset->lyxCode()) {
215 case InsetBase::TABULAR_CODE: {
216 InsetTabular * it = static_cast<InsetTabular*>(lit->inset);
226 std::swap(in.paragraphs(), insertion);
228 // Split the paragraph for inserting the buf if necessary.
230 breakParagraphConservative(buffer.params(), pars, pit, pos);
234 pars.insert(boost::next(pars.begin(), pit),
238 // merge the empty par with the last par of the insertion
239 mergeParagraph(buffer.params(), pars,
240 pit + insertion.size() - 1);
242 pars.insert(boost::next(pars.begin(), pit + 1),
246 // merge the first par of the insertion with the current par
247 mergeParagraph(buffer.params(), pars, pit);
250 pit_type last_paste = pit + insertion.size() - 1;
252 // Store the new cursor position.
254 pos = pars[last_paste].size();
256 // Join (conditionally) last pasted paragraph with next one, i.e.,
257 // the tail of the spliced document paragraph
258 if (!empty && last_paste + 1 != pit_type(pars.size())) {
259 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
260 mergeParagraph(buffer.params(), pars, last_paste);
261 } else if (pars[last_paste + 1].empty()) {
262 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
263 mergeParagraph(buffer.params(), pars, last_paste);
264 } else if (pars[last_paste].empty()) {
265 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
266 mergeParagraph(buffer.params(), pars, last_paste);
268 pars[last_paste + 1].stripLeadingSpaces();
273 return make_pair(PitPosPair(pit, pos), last_paste + 1);
277 PitPosPair eraseSelectionHelper(BufferParams const & params,
278 ParagraphList & pars,
279 pit_type startpit, pit_type endpit,
280 int startpos, int endpos, bool doclear)
282 // Start of selection is really invalid.
283 if (startpit == pit_type(pars.size()) ||
284 (startpos > pars[startpit].size()))
285 return PitPosPair(endpit, endpos);
287 // Start and end is inside same paragraph
288 if (endpit == pit_type(pars.size()) ||
289 startpit == endpit) {
290 endpos -= pars[startpit].erase(startpos, endpos);
291 return PitPosPair(endpit, endpos);
294 // A paragraph break has to be physically removed by merging, but
295 // only if either (1) change tracking is off, or (2) the para break
297 for (pit_type pit = startpit; pit != endpit + 1;) {
298 bool const merge = !params.tracking_changes ||
299 pars[pit].lookupChange(pars[pit].size()) ==
301 pos_type const left = ( pit == startpit ? startpos : 0 );
302 pos_type const right = ( pit == endpit ? endpos :
303 pars[pit].size() + 1 );
304 // Logical erase only:
305 pars[pit].erase(left, right);
306 // Separate handling of para break:
307 if (merge && pit != endpit &&
308 pars[pit].hasSameLayout(pars[pit + 1])) {
309 pos_type const thissize = pars[pit].size();
311 pars[pit + 1].stripLeadingSpaces();
312 mergeParagraph(params, pars, pit);
320 // Ensure legal cursor pos:
323 return PitPosPair(endpit, endpos);
327 void copySelectionHelper(Buffer const & buf, ParagraphList & pars,
328 pit_type startpit, pit_type endpit,
329 int start, int end, textclass_type tc)
331 BOOST_ASSERT(0 <= start && start <= pars[startpit].size());
332 BOOST_ASSERT(0 <= end && end <= pars[endpit].size());
333 BOOST_ASSERT(startpit != endpit || start <= end);
335 // Clone the paragraphs within the selection.
336 ParagraphList paragraphs(boost::next(pars.begin(), startpit),
337 boost::next(pars.begin(), endpit + 1));
339 for_each(paragraphs.begin(), paragraphs.end(), resetParagraph(buf));
341 // Cut out the end of the last paragraph.
342 Paragraph & back = paragraphs.back();
343 back.erase(end, back.size());
345 // Cut out the begin of the first paragraph
346 Paragraph & front = paragraphs.front();
347 front.erase(0, start);
349 theCuts.push(make_pair(paragraphs, tc));
360 string grabAndEraseSelection(LCursor & cur)
362 if (!cur.selection())
364 string res = grabSelection(cur);
370 void switchBetweenClasses(textclass_type c1, textclass_type c2,
371 ParagraphList & pars, ErrorList & errorlist)
373 BOOST_ASSERT(!pars.empty());
377 LyXTextClass const & tclass1 = textclasslist[c1];
378 LyXTextClass const & tclass2 = textclasslist[c2];
381 std::swap(in.paragraphs(), pars);
384 ParIterator end = par_iterator_end(in);
385 for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
386 string const name = it->layout()->name();
387 bool hasLayout = tclass2.hasLayout(name);
390 it->layout(tclass2[name]);
392 it->layout(tclass2.defaultLayout());
394 if (!hasLayout && name != tclass1.defaultLayoutName()) {
395 string const s = bformat(
396 _("Layout had to be changed from\n%1$s to %2$s\n"
397 "because of class conversion from\n%3$s to %4$s"),
398 name, it->layout()->name(), tclass1.name(), tclass2.name());
399 // To warn the user that something had to be done.
400 errorlist.push_back(ErrorItem(_("Changed Layout"), s,
407 InsetIterator const i_end = inset_iterator_end(in);
408 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
409 if (it->lyxCode() == InsetBase::CHARSTYLE_CODE) {
410 InsetCharStyle & inset =
411 static_cast<InsetCharStyle &>(*it);
412 string const name = inset.params().type;
413 CharStyles::iterator const found_cs =
414 tclass2.charstyle(name);
415 if (found_cs == tclass2.charstyles().end()) {
416 // The character style is undefined in tclass2
417 inset.setUndefined();
418 string const s = bformat(_(
419 "Character style %1$s is "
420 "undefined because of class "
421 "conversion from\n%2$s to %3$s"),
422 name, tclass1.name(), tclass2.name());
423 // To warn the user that something had to be done.
424 errorlist.push_back(ErrorItem(
425 _("Undefined character style"),
426 s, it.paragraph().id(),
427 it.pos(), it.pos() + 1));
428 } else if (inset.undefined()) {
429 // The character style is undefined in
430 // tclass1 and is defined in tclass2
431 inset.setDefined(found_cs);
436 std::swap(in.paragraphs(), pars);
440 std::vector<string> const availableSelections(Buffer const & buffer)
442 vector<string> selList;
444 CutStack::const_iterator cit = theCuts.begin();
445 CutStack::const_iterator end = theCuts.end();
446 for (; cit != end; ++cit) {
447 // we do not use cit-> here because gcc 2.9x does not
449 ParagraphList const & pars = (*cit).first;
451 ParagraphList::const_iterator pit = pars.begin();
452 ParagraphList::const_iterator pend = pars.end();
453 for (; pit != pend; ++pit) {
454 asciiSel += pit->asString(buffer, false);
455 if (asciiSel.size() > 25) {
456 asciiSel.replace(22, string::npos, "...");
461 selList.push_back(asciiSel);
468 lyx::size_type numberOfSelections()
470 return theCuts.size();
474 void cutSelection(LCursor & cur, bool doclear, bool realcut)
476 // This doesn't make sense, if there is no selection
477 if (!cur.selection())
480 // OK, we have a selection. This is always between cur.selBegin()
483 if (cur.inTexted()) {
484 LyXText * text = cur.text();
486 // Stuff what we got on the clipboard. Even if there is no selection.
488 // There is a problem with having the stuffing here in that the
489 // larger the selection the slower LyX will get. This can be
490 // solved by running the line below only when the selection has
491 // finished. The solution used currently just works, to make it
492 // faster we need to be more clever and probably also have more
493 // calls to stuffClipboard. (Lgb)
494 // cur.bv().stuffClipboard(cur.selectionAsString(true));
496 // make sure that the depth behind the selection are restored, too
497 recordUndoSelection(cur);
498 pit_type begpit = cur.selBegin().pit();
499 pit_type endpit = cur.selEnd().pit();
501 int endpos = cur.selEnd().pos();
503 BufferParams const & bp = cur.buffer().params();
505 copySelectionHelper(cur.buffer(),
508 cur.selBegin().pos(), endpos,
512 boost::tie(endpit, endpos) =
513 eraseSelectionHelper(bp,
516 cur.selBegin().pos(), endpos,
519 // sometimes necessary
521 text->paragraphs()[begpit].stripLeadingSpaces();
523 // cutSelection can invalidate the cursor so we need to set
525 // we prefer the end for when tracking changes
529 // need a valid cursor. (Lgb)
530 cur.clearSelection();
531 updateLabels(cur.buffer());
533 // tell tabular that a recent copy happened
534 dirtyTabularStack(false);
537 if (cur.inMathed()) {
538 if (cur.selBegin().idx() != cur.selEnd().idx()) {
539 // The current selection spans more than one cell.
541 recordUndoInset(cur);
543 // Record only the current cell to avoid a jumping
554 void copySelection(LCursor & cur)
556 // stuff the selection onto the X clipboard, from an explicit copy request
557 cur.bv().stuffClipboard(cur.selectionAsString(true));
559 // this doesn't make sense, if there is no selection
560 if (!cur.selection())
563 if (cur.inTexted()) {
564 LyXText * text = cur.text();
566 // ok we have a selection. This is always between cur.selBegin()
567 // and sel_end cursor
569 // copy behind a space if there is one
570 ParagraphList & pars = text->paragraphs();
571 pos_type pos = cur.selBegin().pos();
572 pit_type par = cur.selBegin().pit();
573 while (pos < pars[par].size()
574 && pars[par].isLineSeparator(pos)
575 && (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
578 copySelectionHelper(cur.buffer(), pars, par, cur.selEnd().pit(),
579 pos, cur.selEnd().pos(), cur.buffer().params().textclass);
582 if (cur.inMathed()) {
583 lyxerr << "copySelection in mathed" << endl;
585 pars.push_back(Paragraph());
586 BufferParams const & bp = cur.buffer().params();
587 pars.back().layout(bp.getLyXTextClass().defaultLayout());
588 for_each(pars.begin(), pars.end(), resetParagraph(cur.buffer()));
589 pars.back().insert(0, grabSelection(cur), LyXFont());
590 theCuts.push(make_pair(pars, bp.textclass));
592 // tell tabular that a recent copy happened
593 dirtyTabularStack(false);
597 std::string getSelection(Buffer const & buf, size_t sel_index)
599 return sel_index < theCuts.size()
600 ? theCuts[sel_index].first.back().asString(buf, false)
605 void pasteParagraphList(LCursor & cur, ParagraphList const & parlist,
606 textclass_type textclass)
608 if (cur.inTexted()) {
609 LyXText * text = cur.text();
618 boost::tie(ppp, endpit) =
619 pasteSelectionHelper(cur.buffer(),
621 cur.pit(), cur.pos(),
624 bufferErrors(cur.buffer(), el);
625 updateLabels(cur.buffer());
626 cur.clearSelection();
627 text->setCursor(cur, ppp.first, ppp.second);
630 // mathed is handled in MathNestInset/MathGridInset
631 BOOST_ASSERT(!cur.inMathed());
635 void pasteSelection(LCursor & cur, size_t sel_index)
637 // this does not make sense, if there is nothing to paste
638 if (!checkPastePossible(sel_index))
641 pasteParagraphList(cur, theCuts[sel_index].first,
642 theCuts[sel_index].second);
643 cur.bv().showErrorList(_("Paste"));
648 void setSelectionRange(LCursor & cur, pos_type length)
650 LyXText * text = cur.text();
656 text->cursorRight(cur);
661 // simple replacing. The font of the first selected character is used
662 void replaceSelectionWithString(LCursor & cur, string const & str)
664 LyXText * text = cur.text();
668 // Get font setting before we cut
669 pos_type pos = cur.selEnd().pos();
670 Paragraph & par = text->getPar(cur.selEnd().pit());
672 par.getFontSettings(cur.buffer().params(), cur.selBegin().pos());
674 // Insert the new string
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);
685 void replaceSelection(LCursor & cur)
688 cutSelection(cur, true, false);
692 // only used by the spellchecker
693 void replaceWord(LCursor & cur, string const & replacestring)
695 LyXText * text = cur.text();
698 replaceSelectionWithString(cur, replacestring);
699 setSelectionRange(cur, replacestring.length());
701 // Go back so that replacement string is also spellchecked
702 for (string::size_type i = 0; i < replacestring.length() + 1; ++i)
703 text->cursorLeft(cur);
707 void eraseSelection(LCursor & cur)
709 //lyxerr << "LCursor::eraseSelection begin: " << cur << endl;
710 CursorSlice const & i1 = cur.selBegin();
711 CursorSlice const & i2 = cur.selEnd();
712 if (i1.inset().asMathInset()) {
714 if (i1.idx() == i2.idx()) {
715 i1.cell().erase(i1.pos(), i2.pos());
716 // We may have deleted i1.cell(cur.pos()).
717 // Make sure that pos is valid.
718 if (cur.pos() > cur.lastpos())
719 cur.pos() = cur.lastpos();
721 MathInset * p = i1.asMathInset();
722 InsetBase::row_type r1, r2;
723 InsetBase::col_type c1, c2;
724 region(i1, i2, r1, r2, c1, c2);
725 for (InsetBase::row_type row = r1; row <= r2; ++row)
726 for (InsetBase::col_type col = c1; col <= c2; ++col)
727 p->cell(p->index(row, col)).clear();
728 // We've deleted the whole cell. Only pos 0 is valid.
731 // need a valid cursor. (Lgb)
732 cur.clearSelection();
734 lyxerr << "can't erase this selection 1" << endl;
736 //lyxerr << "LCursor::eraseSelection end: " << cur << endl;
740 void selDel(LCursor & cur)
742 //lyxerr << "LCursor::selDel" << endl;
748 void selClearOrDel(LCursor & cur)
750 //lyxerr << "LCursor::selClearOrDel" << endl;
751 if (lyxrc.auto_region_delete)
754 cur.selection() = false;
758 string grabSelection(LCursor const & cur)
760 if (!cur.selection())
763 // FIXME: What is wrong with the following?
765 std::ostringstream os;
766 for (DocIterator dit = cur.selectionBegin();
767 dit != cur.selectionEnd(); dit.forwardPos())
768 os << asString(dit.cell());
772 CursorSlice i1 = cur.selBegin();
773 CursorSlice i2 = cur.selEnd();
775 if (i1.idx() == i2.idx()) {
776 if (i1.inset().asMathInset()) {
777 MathArray::const_iterator it = i1.cell().begin();
778 return asString(MathArray(it + i1.pos(), it + i2.pos()));
780 return "unknown selection 1";
784 InsetBase::row_type r1, r2;
785 InsetBase::col_type c1, c2;
786 region(i1, i2, r1, r2, c1, c2);
789 if (i1.inset().asMathInset()) {
790 for (InsetBase::row_type row = r1; row <= r2; ++row) {
793 for (InsetBase::col_type col = c1; col <= c2; ++col) {
796 data += asString(i1.asMathInset()->
797 cell(i1.asMathInset()->index(row, col)));
801 data = "unknown selection 2";
807 void dirtyTabularStack(bool b)
809 dirty_tabular_stack_ = b;
813 bool tabularStackDirty()
815 return dirty_tabular_stack_;