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"
30 #include "lyxtextclasslist.h"
31 #include "paragraph.h"
32 #include "paragraph_funcs.h"
33 #include "ParagraphParameters.h"
34 #include "ParagraphList_fwd.h"
35 #include "pariterator.h"
38 #include "insets/insetcharstyle.h"
39 #include "insets/insettabular.h"
41 #include "mathed/math_data.h"
42 #include "mathed/math_inset.h"
43 #include "mathed/math_support.h"
45 #include "support/lstrings.h"
47 #include <boost/tuple/tuple.hpp>
51 using lyx::textclass_type;
53 using lyx::support::bformat;
65 typedef std::pair<lyx::pit_type, int> PitPosPair;
67 typedef limited_stack<pair<ParagraphList, textclass_type> > CutStack;
71 // store whether the tabular stack is newer than the normal copy stack
72 // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
73 // when we (hopefully) have a one-for-all paste mechanism.
74 bool dirty_tabular_stack_;
76 class resetOwnerAndChanges : public std::unary_function<Paragraph, void> {
78 void operator()(Paragraph & p) const {
85 void region(CursorSlice const & i1, CursorSlice const & i2,
86 InsetBase::row_type & r1, InsetBase::row_type & r2,
87 InsetBase::col_type & c1, InsetBase::col_type & c2)
89 InsetBase & p = i1.inset();
101 bool checkPastePossible(int index)
103 return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
107 pair<PitPosPair, pit_type>
108 pasteSelectionHelper(Buffer const & buffer,
109 ParagraphList & pars, pit_type pit, int pos,
110 ParagraphList const & parlist, textclass_type textclass,
111 ErrorList & errorlist)
114 return make_pair(PitPosPair(pit, pos), pit);
116 BOOST_ASSERT (pos <= pars[pit].size());
118 // Make a copy of the CaP paragraphs.
119 ParagraphList insertion = parlist;
120 textclass_type const tc = buffer.params().textclass;
122 // Now remove all out of the pars which is NOT allowed in the
123 // new environment and set also another font if that is required.
125 // Convert newline to paragraph break in ERT inset.
126 // This should not be here!
127 if (pars[pit].inInset() &&
128 pars[pit].inInset()->lyxCode() == InsetBase::ERT_CODE) {
129 for (ParagraphList::size_type i = 0; i < insertion.size(); ++i) {
130 for (pos_type j = 0; j < insertion[i].size(); ++j) {
131 if (insertion[i].isNewline(j)) {
132 insertion[i].erase(j);
133 breakParagraphConservative(
141 // Make sure there is no class difference.
142 lyx::cap::switchBetweenClasses(textclass, tc, insertion, errorlist);
144 ParagraphList::iterator tmpbuf = insertion.begin();
145 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
147 Paragraph::depth_type max_depth = pars[pit].getMaxDepthAfter();
149 for (; tmpbuf != insertion.end(); ++tmpbuf) {
150 // If we have a negative jump so that the depth would
151 // go below 0 depth then we have to redo the delta to
152 // this new max depth level so that subsequent
153 // paragraphs are aligned correctly to this paragraph
155 if (int(tmpbuf->params().depth()) + depth_delta < 0)
158 // Set the right depth so that we are not too deep or shallow.
159 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
160 if (tmpbuf->params().depth() > max_depth)
161 tmpbuf->params().depth(max_depth);
163 // Only set this from the 2nd on as the 2nd depends
164 // for maxDepth still on pit.
165 if (tmpbuf != insertion.begin())
166 max_depth = tmpbuf->getMaxDepthAfter();
168 // Set the inset owner of this paragraph.
169 tmpbuf->setInsetOwner(pars[pit].inInset());
170 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
171 if (tmpbuf->getChar(i) == Paragraph::META_INSET &&
172 !pars[pit].insetAllowed(tmpbuf->getInset(i)->lyxCode()))
176 // reset change tracking status
177 if (buffer.params().tracking_changes)
178 tmpbuf->cleanChanges(Paragraph::trackingOn);
180 tmpbuf->cleanChanges(Paragraph::trackingOff);
183 bool const empty = pars[pit].empty();
185 // Make the buf exactly the same layout as the cursor
187 insertion.begin()->makeSameLayout(pars[pit]);
190 // Prepare the paragraphs and insets for insertion.
191 // A couple of insets store buffer references so need updating.
193 std::swap(in.paragraphs(), insertion);
195 ParIterator fpit = par_iterator_begin(in);
196 ParIterator fend = par_iterator_end(in);
198 for (; fpit != fend; ++fpit) {
199 InsetList::iterator lit = fpit->insetlist.begin();
200 InsetList::iterator eit = fpit->insetlist.end();
202 for (; lit != eit; ++lit) {
203 switch (lit->inset->lyxCode()) {
204 case InsetBase::TABULAR_CODE: {
205 InsetTabular * it = static_cast<InsetTabular*>(lit->inset);
215 std::swap(in.paragraphs(), insertion);
217 // Split the paragraph for inserting the buf if necessary.
219 breakParagraphConservative(buffer.params(), pars, pit, pos);
223 pars.insert(boost::next(pars.begin(), pit),
227 // merge the empty par with the last par of the insertion
228 mergeParagraph(buffer.params(), pars,
229 pit + insertion.size() - 1);
231 pars.insert(boost::next(pars.begin(), pit + 1),
235 // merge the first par of the insertion with the current par
236 mergeParagraph(buffer.params(), pars, pit);
239 pit_type last_paste = pit + insertion.size() - 1;
241 // Store the new cursor position.
243 pos = pars[last_paste].size();
245 // Join (conditionally) last pasted paragraph with next one, i.e.,
246 // the tail of the spliced document paragraph
247 if (!empty && last_paste + 1 != pit_type(pars.size())) {
248 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
249 mergeParagraph(buffer.params(), pars, last_paste);
250 } else if (pars[last_paste + 1].empty()) {
251 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
252 mergeParagraph(buffer.params(), pars, last_paste);
253 } else if (pars[last_paste].empty()) {
254 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
255 mergeParagraph(buffer.params(), pars, last_paste);
257 pars[last_paste + 1].stripLeadingSpaces();
262 return make_pair(PitPosPair(pit, pos), last_paste + 1);
266 PitPosPair eraseSelectionHelper(BufferParams const & params,
267 ParagraphList & pars,
268 pit_type startpit, pit_type endpit,
269 int startpos, int endpos, bool doclear)
271 // Start of selection is really invalid.
272 if (startpit == pit_type(pars.size()) ||
273 (startpos > pars[startpit].size()))
274 return PitPosPair(endpit, endpos);
276 // Start and end is inside same paragraph
277 if (endpit == pit_type(pars.size()) ||
278 startpit == endpit) {
279 endpos -= pars[startpit].erase(startpos, endpos);
280 return PitPosPair(endpit, endpos);
283 // A paragraph break has to be physically removed by merging, but
284 // only if either (1) change tracking is off, or (2) the para break
286 for (pit_type pit = startpit; pit != endpit + 1;) {
287 bool const merge = !params.tracking_changes ||
288 pars[pit].lookupChange(pars[pit].size()) ==
290 pos_type const left = ( pit == startpit ? startpos : 0 );
291 pos_type const right = ( pit == endpit ? endpos :
292 pars[pit].size() + 1 );
293 // Logical erase only:
294 pars[pit].erase(left, right);
295 // Separate handling of para break:
296 if (merge && pit != endpit &&
297 pars[pit].hasSameLayout(pars[pit + 1])) {
298 pos_type const thissize = pars[pit].size();
300 pars[pit + 1].stripLeadingSpaces();
301 mergeParagraph(params, pars, pit);
309 // Ensure legal cursor pos:
312 return PitPosPair(endpit, endpos);
316 void copySelectionHelper(ParagraphList & pars,
317 pit_type startpit, pit_type endpit,
318 int start, int end, textclass_type tc)
320 BOOST_ASSERT(0 <= start && start <= pars[startpit].size());
321 BOOST_ASSERT(0 <= end && end <= pars[endpit].size());
322 BOOST_ASSERT(startpit != endpit || start <= end);
324 // Clone the paragraphs within the selection.
325 ParagraphList paragraphs(boost::next(pars.begin(), startpit),
326 boost::next(pars.begin(), endpit + 1));
328 for_each(paragraphs.begin(), paragraphs.end(), resetOwnerAndChanges());
330 // Cut out the end of the last paragraph.
331 Paragraph & back = paragraphs.back();
332 back.erase(end, back.size());
334 // Cut out the begin of the first paragraph
335 Paragraph & front = paragraphs.front();
336 front.erase(0, start);
338 theCuts.push(make_pair(paragraphs, tc));
349 string grabAndEraseSelection(LCursor & cur)
351 if (!cur.selection())
353 string res = grabSelection(cur);
359 void switchBetweenClasses(textclass_type c1, textclass_type c2,
360 ParagraphList & pars, ErrorList & errorlist)
362 BOOST_ASSERT(!pars.empty());
366 LyXTextClass const & tclass1 = textclasslist[c1];
367 LyXTextClass const & tclass2 = textclasslist[c2];
370 std::swap(in.paragraphs(), pars);
373 ParIterator end = par_iterator_end(in);
374 for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
375 string const name = it->layout()->name();
376 bool hasLayout = tclass2.hasLayout(name);
379 it->layout(tclass2[name]);
381 it->layout(tclass2.defaultLayout());
383 if (!hasLayout && name != tclass1.defaultLayoutName()) {
384 string const s = bformat(
385 _("Layout had to be changed from\n%1$s to %2$s\n"
386 "because of class conversion from\n%3$s to %4$s"),
387 name, it->layout()->name(), tclass1.name(), tclass2.name());
388 // To warn the user that something had to be done.
389 errorlist.push_back(ErrorItem(_("Changed Layout"), s,
396 InsetIterator const i_end = inset_iterator_end(in);
397 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
398 if (it->lyxCode() == InsetBase::CHARSTYLE_CODE) {
399 InsetCharStyle & inset =
400 static_cast<InsetCharStyle &>(*it);
401 string const name = inset.params().type;
402 CharStyles::iterator const found_cs =
403 tclass2.charstyle(name);
404 if (found_cs == tclass2.charstyles().end()) {
405 // The character style is undefined in tclass2
406 inset.setUndefined();
407 string const s = bformat(_(
408 "Character style %1$s is "
409 "undefined because of class "
410 "conversion from\n%2$s to %3$s"),
411 name, tclass1.name(), tclass2.name());
412 // To warn the user that something had to be done.
413 errorlist.push_back(ErrorItem(
414 _("Undefined character style"),
415 s, it.paragraph().id(),
416 it.pos(), it.pos() + 1));
417 } else if (inset.undefined()) {
418 // The character style is undefined in
419 // tclass1 and is defined in tclass2
420 inset.setDefined(found_cs);
425 std::swap(in.paragraphs(), pars);
429 std::vector<string> const availableSelections(Buffer const & buffer)
431 vector<string> selList;
433 CutStack::const_iterator cit = theCuts.begin();
434 CutStack::const_iterator end = theCuts.end();
435 for (; cit != end; ++cit) {
436 // we do not use cit-> here because gcc 2.9x does not
438 ParagraphList const & pars = (*cit).first;
440 ParagraphList::const_iterator pit = pars.begin();
441 ParagraphList::const_iterator pend = pars.end();
442 for (; pit != pend; ++pit) {
443 asciiSel += pit->asString(buffer, false);
444 if (asciiSel.size() > 25) {
445 asciiSel.replace(22, string::npos, "...");
450 selList.push_back(asciiSel);
457 lyx::size_type numberOfSelections()
459 return theCuts.size();
463 void cutSelection(LCursor & cur, bool doclear, bool realcut)
465 // This doesn't make sense, if there is no selection
466 if (!cur.selection())
469 // OK, we have a selection. This is always between cur.selBegin()
472 if (cur.inTexted()) {
473 LyXText * text = cur.text();
475 // Stuff what we got on the clipboard. Even if there is no selection.
477 // There is a problem with having the stuffing here in that the
478 // larger the selection the slower LyX will get. This can be
479 // solved by running the line below only when the selection has
480 // finished. The solution used currently just works, to make it
481 // faster we need to be more clever and probably also have more
482 // calls to stuffClipboard. (Lgb)
483 // cur.bv().stuffClipboard(cur.selectionAsString(true));
485 // make sure that the depth behind the selection are restored, too
486 recordUndoSelection(cur);
487 pit_type begpit = cur.selBegin().pit();
488 pit_type endpit = cur.selEnd().pit();
490 int endpos = cur.selEnd().pos();
492 BufferParams const & bp = cur.buffer().params();
494 copySelectionHelper(text->paragraphs(),
496 cur.selBegin().pos(), endpos,
500 boost::tie(endpit, endpos) =
501 eraseSelectionHelper(bp,
504 cur.selBegin().pos(), endpos,
507 // sometimes necessary
509 text->paragraphs()[begpit].stripLeadingSpaces();
511 // cutSelection can invalidate the cursor so we need to set
513 // we prefer the end for when tracking changes
517 // need a valid cursor. (Lgb)
518 cur.clearSelection();
519 updateLabels(cur.buffer());
521 // tell tabular that a recent copy happened
522 dirtyTabularStack(false);
525 if (cur.inMathed()) {
526 if (cur.selBegin().idx() != cur.selEnd().idx()) {
527 // The current selection spans more than one cell.
529 recordUndoInset(cur);
531 // Record only the current cell to avoid a jumping
542 void copySelection(LCursor & cur)
544 // stuff the selection onto the X clipboard, from an explicit copy request
545 cur.bv().stuffClipboard(cur.selectionAsString(true));
547 // this doesn't make sense, if there is no selection
548 if (!cur.selection())
551 if (cur.inTexted()) {
552 LyXText * text = cur.text();
554 // ok we have a selection. This is always between cur.selBegin()
555 // and sel_end cursor
557 // copy behind a space if there is one
558 ParagraphList & pars = text->paragraphs();
559 pos_type pos = cur.selBegin().pos();
560 pit_type par = cur.selBegin().pit();
561 while (pos < pars[par].size()
562 && pars[par].isLineSeparator(pos)
563 && (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
566 copySelectionHelper(pars, par, cur.selEnd().pit(),
567 pos, cur.selEnd().pos(), cur.buffer().params().textclass);
570 if (cur.inMathed()) {
571 lyxerr << "copySelection in mathed" << endl;
573 pars.push_back(Paragraph());
574 BufferParams const & bp = cur.buffer().params();
575 pars.back().layout(bp.getLyXTextClass().defaultLayout());
576 for_each(pars.begin(), pars.end(), resetOwnerAndChanges());
577 pars.back().insert(0, grabSelection(cur), LyXFont());
578 theCuts.push(make_pair(pars, bp.textclass));
580 // tell tabular that a recent copy happened
581 dirtyTabularStack(false);
585 std::string getSelection(Buffer const & buf, size_t sel_index)
587 return sel_index < theCuts.size()
588 ? theCuts[sel_index].first.back().asString(buf, false)
593 void pasteParagraphList(LCursor & cur, ParagraphList const & parlist,
594 textclass_type textclass)
596 if (cur.inTexted()) {
597 LyXText * text = cur.text();
606 boost::tie(ppp, endpit) =
607 pasteSelectionHelper(cur.buffer(),
609 cur.pit(), cur.pos(),
612 bufferErrors(cur.buffer(), el);
613 updateLabels(cur.buffer());
614 cur.clearSelection();
615 text->setCursor(cur, ppp.first, ppp.second);
618 // mathed is handled in MathNestInset/MathGridInset
619 BOOST_ASSERT(!cur.inMathed());
623 void pasteSelection(LCursor & cur, size_t sel_index)
625 // this does not make sense, if there is nothing to paste
626 if (!checkPastePossible(sel_index))
629 pasteParagraphList(cur, theCuts[sel_index].first,
630 theCuts[sel_index].second);
631 cur.bv().showErrorList(_("Paste"));
636 void setSelectionRange(LCursor & cur, pos_type length)
638 LyXText * text = cur.text();
644 text->cursorRight(cur);
649 // simple replacing. The font of the first selected character is used
650 void replaceSelectionWithString(LCursor & cur, string const & str)
652 LyXText * text = cur.text();
656 // Get font setting before we cut
657 pos_type pos = cur.selEnd().pos();
658 Paragraph & par = text->getPar(cur.selEnd().pit());
660 par.getFontSettings(cur.buffer().params(), cur.selBegin().pos());
662 // Insert the new string
663 string::const_iterator cit = str.begin();
664 string::const_iterator end = str.end();
665 for (; cit != end; ++cit, ++pos)
666 par.insertChar(pos, (*cit), font);
669 cutSelection(cur, true, false);
673 void replaceSelection(LCursor & cur)
676 cutSelection(cur, true, false);
680 // only used by the spellchecker
681 void replaceWord(LCursor & cur, string const & replacestring)
683 LyXText * text = cur.text();
686 replaceSelectionWithString(cur, replacestring);
687 setSelectionRange(cur, replacestring.length());
689 // Go back so that replacement string is also spellchecked
690 for (string::size_type i = 0; i < replacestring.length() + 1; ++i)
691 text->cursorLeft(cur);
695 void eraseSelection(LCursor & cur)
697 //lyxerr << "LCursor::eraseSelection begin: " << cur << endl;
698 CursorSlice const & i1 = cur.selBegin();
699 CursorSlice const & i2 = cur.selEnd();
700 if (i1.inset().asMathInset()) {
702 if (i1.idx() == i2.idx()) {
703 i1.cell().erase(i1.pos(), i2.pos());
704 // We may have deleted i1.cell(cur.pos()).
705 // Make sure that pos is valid.
706 if (cur.pos() > cur.lastpos())
707 cur.pos() = cur.lastpos();
709 MathInset * p = i1.asMathInset();
710 InsetBase::row_type r1, r2;
711 InsetBase::col_type c1, c2;
712 region(i1, i2, r1, r2, c1, c2);
713 for (InsetBase::row_type row = r1; row <= r2; ++row)
714 for (InsetBase::col_type col = c1; col <= c2; ++col)
715 p->cell(p->index(row, col)).clear();
716 // We've deleted the whole cell. Only pos 0 is valid.
719 // need a valid cursor. (Lgb)
720 cur.clearSelection();
722 lyxerr << "can't erase this selection 1" << endl;
724 //lyxerr << "LCursor::eraseSelection end: " << cur << endl;
728 void selDel(LCursor & cur)
730 //lyxerr << "LCursor::selDel" << endl;
736 void selClearOrDel(LCursor & cur)
738 //lyxerr << "LCursor::selClearOrDel" << endl;
739 if (lyxrc.auto_region_delete)
742 cur.selection() = false;
746 string grabSelection(LCursor const & cur)
748 if (!cur.selection())
751 // FIXME: What is wrong with the following?
753 std::ostringstream os;
754 for (DocIterator dit = cur.selectionBegin();
755 dit != cur.selectionEnd(); dit.forwardPos())
756 os << asString(dit.cell());
760 CursorSlice i1 = cur.selBegin();
761 CursorSlice i2 = cur.selEnd();
763 if (i1.idx() == i2.idx()) {
764 if (i1.inset().asMathInset()) {
765 MathArray::const_iterator it = i1.cell().begin();
766 return asString(MathArray(it + i1.pos(), it + i2.pos()));
768 return "unknown selection 1";
772 InsetBase::row_type r1, r2;
773 InsetBase::col_type c1, c2;
774 region(i1, i2, r1, r2, c1, c2);
777 if (i1.inset().asMathInset()) {
778 for (InsetBase::row_type row = r1; row <= r2; ++row) {
781 for (InsetBase::col_type col = c1; col <= c2; ++col) {
784 data += asString(i1.asMathInset()->
785 cell(i1.asMathInset()->index(row, col)));
789 data = "unknown selection 2";
795 void dirtyTabularStack(bool b)
797 dirty_tabular_stack_ = b;
801 bool tabularStackDirty()
803 return dirty_tabular_stack_;