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()))
177 bool const empty = pars[pit].empty();
179 // Make the buf exactly the same layout as the cursor
181 insertion.begin()->makeSameLayout(pars[pit]);
184 // Prepare the paragraphs and insets for insertion.
185 // A couple of insets store buffer references so need updating.
187 std::swap(in.paragraphs(), insertion);
189 ParIterator fpit = par_iterator_begin(in);
190 ParIterator fend = par_iterator_end(in);
192 for (; fpit != fend; ++fpit) {
193 InsetList::iterator lit = fpit->insetlist.begin();
194 InsetList::iterator eit = fpit->insetlist.end();
196 for (; lit != eit; ++lit) {
197 switch (lit->inset->lyxCode()) {
198 case InsetBase::TABULAR_CODE: {
199 InsetTabular * it = static_cast<InsetTabular*>(lit->inset);
209 std::swap(in.paragraphs(), insertion);
211 // Split the paragraph for inserting the buf if necessary.
213 breakParagraphConservative(buffer.params(), pars, pit, pos);
217 pars.insert(pars.begin() + pit, insertion.begin(),
220 // merge the empty par with the last par of the insertion
221 mergeParagraph(buffer.params(), pars,
222 pit + insertion.size() - 1);
224 pars.insert(pars.begin() + pit + 1, insertion.begin(),
227 // merge the first par of the insertion with the current par
228 mergeParagraph(buffer.params(), pars, pit);
231 pit_type last_paste = pit + insertion.size() - 1;
233 // Store the new cursor position.
235 pos = pars[last_paste].size();
237 // Join (conditionally) last pasted paragraph with next one, i.e.,
238 // the tail of the spliced document paragraph
239 if (!empty && last_paste + 1 != pit_type(pars.size())) {
240 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
241 mergeParagraph(buffer.params(), pars, last_paste);
242 } else if (pars[last_paste + 1].empty()) {
243 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
244 mergeParagraph(buffer.params(), pars, last_paste);
245 } else if (pars[last_paste].empty()) {
246 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
247 mergeParagraph(buffer.params(), pars, last_paste);
249 pars[last_paste + 1].stripLeadingSpaces();
254 return make_pair(PitPosPair(pit, pos), last_paste + 1);
258 PitPosPair eraseSelectionHelper(BufferParams const & params,
259 ParagraphList & pars,
260 pit_type startpit, pit_type endpit,
261 int startpos, int endpos, bool doclear)
263 // Start of selection is really invalid.
264 if (startpit == pit_type(pars.size()) ||
265 (startpos > pars[startpit].size()))
266 return PitPosPair(endpit, endpos);
268 // Start and end is inside same paragraph
269 if (endpit == pit_type(pars.size()) ||
270 startpit == endpit) {
271 endpos -= pars[startpit].erase(startpos, endpos);
272 return PitPosPair(endpit, endpos);
275 // A paragraph break has to be physically removed by merging, but
276 // only if either (1) change tracking is off, or (2) the para break
278 for (pit_type pit = startpit; pit != endpit + 1;) {
279 bool const merge = !params.tracking_changes ||
280 pars[pit].lookupChange(pars[pit].size()) ==
282 pos_type const left = ( pit == startpit ? startpos : 0 );
283 pos_type const right = ( pit == endpit ? endpos :
284 pars[pit].size() + 1 );
285 // Logical erase only:
286 pars[pit].erase(left, right);
287 // Separate handling of para break:
288 if (merge && pit != endpit &&
289 pars[pit].hasSameLayout(pars[pit + 1])) {
290 pos_type const thissize = pars[pit].size();
292 pars[pit + 1].stripLeadingSpaces();
293 mergeParagraph(params, pars, pit);
301 // Ensure legal cursor pos:
304 return PitPosPair(endpit, endpos);
308 void copySelectionHelper(ParagraphList & pars,
309 pit_type startpit, pit_type endpit,
310 int start, int end, textclass_type tc)
312 BOOST_ASSERT(0 <= start && start <= pars[startpit].size());
313 BOOST_ASSERT(0 <= end && end <= pars[endpit].size());
314 BOOST_ASSERT(startpit != endpit || start <= end);
316 // Clone the paragraphs within the selection.
317 ParagraphList paragraphs(pars.begin() + startpit, pars.begin() + endpit + 1);
319 for_each(paragraphs.begin(), paragraphs.end(), resetOwnerAndChanges());
321 // Cut out the end of the last paragraph.
322 Paragraph & back = paragraphs.back();
323 back.erase(end, back.size());
325 // Cut out the begin of the first paragraph
326 Paragraph & front = paragraphs.front();
327 front.erase(0, start);
329 theCuts.push(make_pair(paragraphs, tc));
340 string grabAndEraseSelection(LCursor & cur)
342 if (!cur.selection())
344 string res = grabSelection(cur);
350 void SwitchBetweenClasses(textclass_type c1, textclass_type c2,
351 ParagraphList & pars, ErrorList & errorlist)
353 BOOST_ASSERT(!pars.empty());
357 LyXTextClass const & tclass1 = textclasslist[c1];
358 LyXTextClass const & tclass2 = textclasslist[c2];
361 std::swap(in.paragraphs(), pars);
364 ParIterator end = par_iterator_end(in);
365 for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
366 string const name = it->layout()->name();
367 bool hasLayout = tclass2.hasLayout(name);
370 it->layout(tclass2[name]);
372 it->layout(tclass2.defaultLayout());
374 if (!hasLayout && name != tclass1.defaultLayoutName()) {
375 string const s = bformat(
376 _("Layout had to be changed from\n%1$s to %2$s\n"
377 "because of class conversion from\n%3$s to %4$s"),
378 name, it->layout()->name(), tclass1.name(), tclass2.name());
379 // To warn the user that something had to be done.
380 errorlist.push_back(ErrorItem(_("Changed Layout"), s,
387 InsetIterator const i_end = inset_iterator_end(in);
388 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
389 if (it->lyxCode() == InsetBase::CHARSTYLE_CODE) {
390 InsetCharStyle & inset =
391 static_cast<InsetCharStyle &>(*it);
392 string const name = inset.params().type;
393 CharStyles::iterator const found_cs =
394 tclass2.charstyle(name);
395 if (found_cs == tclass2.charstyles().end()) {
396 // The character style is undefined in tclass2
397 inset.setUndefined();
398 string const s = bformat(_(
399 "Character style %1$s is "
400 "undefined because of class "
401 "conversion from\n%2$s to %3$s"),
402 name, tclass1.name(), tclass2.name());
403 // To warn the user that something had to be done.
404 errorlist.push_back(ErrorItem(
405 _("Undefined character style"),
406 s, it.paragraph().id(),
407 it.pos(), it.pos() + 1));
408 } else if (inset.undefined()) {
409 // The character style is undefined in
410 // tclass1 and is defined in tclass2
411 inset.setDefined(found_cs);
416 std::swap(in.paragraphs(), pars);
420 std::vector<string> const availableSelections(Buffer const & buffer)
422 vector<string> selList;
424 CutStack::const_iterator cit = theCuts.begin();
425 CutStack::const_iterator end = theCuts.end();
426 for (; cit != end; ++cit) {
427 // we do not use cit-> here because gcc 2.9x does not
429 ParagraphList const & pars = (*cit).first;
431 ParagraphList::const_iterator pit = pars.begin();
432 ParagraphList::const_iterator pend = pars.end();
433 for (; pit != pend; ++pit) {
434 asciiSel += pit->asString(buffer, false);
435 if (asciiSel.size() > 25) {
436 asciiSel.replace(22, string::npos, "...");
441 selList.push_back(asciiSel);
448 lyx::size_type numberOfSelections()
450 return theCuts.size();
454 void cutSelection(LCursor & cur, bool doclear, bool realcut)
456 // This doesn't make sense, if there is no selection
457 if (!cur.selection())
460 // OK, we have a selection. This is always between cur.selBegin()
463 if (cur.inTexted()) {
464 LyXText * text = cur.text();
466 // Stuff what we got on the clipboard. Even if there is no selection.
468 // There is a problem with having the stuffing here in that the
469 // larger the selection the slower LyX will get. This can be
470 // solved by running the line below only when the selection has
471 // finished. The solution used currently just works, to make it
472 // faster we need to be more clever and probably also have more
473 // calls to stuffClipboard. (Lgb)
474 // cur.bv().stuffClipboard(cur.selectionAsString(true));
476 // make sure that the depth behind the selection are restored, too
477 recordUndoSelection(cur);
478 pit_type begpit = cur.selBegin().pit();
479 pit_type endpit = cur.selEnd().pit();
481 int endpos = cur.selEnd().pos();
483 BufferParams const & bp = cur.buffer().params();
485 copySelectionHelper(text->paragraphs(),
487 cur.selBegin().pos(), endpos,
491 boost::tie(endpit, endpos) =
492 eraseSelectionHelper(bp,
495 cur.selBegin().pos(), endpos,
498 // sometimes necessary
500 text->paragraphs()[begpit].stripLeadingSpaces();
502 // cutSelection can invalidate the cursor so we need to set
504 // we prefer the end for when tracking changes
508 // need a valid cursor. (Lgb)
509 cur.clearSelection();
510 updateCounters(cur.buffer());
512 // tell tabular that a recent copy happened
513 dirtyTabularStack(false);
516 if (cur.inMathed()) {
517 if (cur.selBegin().idx() != cur.selEnd().idx()) {
518 // The current selection spans more than one cell.
520 recordUndoInset(cur);
522 // Record only the current cell to avoid a jumping
533 void copySelection(LCursor & cur)
535 // stuff the selection onto the X clipboard, from an explicit copy request
536 cur.bv().stuffClipboard(cur.selectionAsString(true));
538 // this doesn't make sense, if there is no selection
539 if (!cur.selection())
542 if (cur.inTexted()) {
543 LyXText * text = cur.text();
545 // ok we have a selection. This is always between cur.selBegin()
546 // and sel_end cursor
548 // copy behind a space if there is one
549 ParagraphList & pars = text->paragraphs();
550 pos_type pos = cur.selBegin().pos();
551 pit_type par = cur.selBegin().pit();
552 while (pos < pars[par].size()
553 && pars[par].isLineSeparator(pos)
554 && (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
557 copySelectionHelper(pars, par, cur.selEnd().pit(),
558 pos, cur.selEnd().pos(), cur.buffer().params().textclass);
561 if (cur.inMathed()) {
562 lyxerr << "copySelection in mathed" << endl;
564 pars.push_back(Paragraph());
565 BufferParams const & bp = cur.buffer().params();
566 pars.back().layout(bp.getLyXTextClass().defaultLayout());
567 for_each(pars.begin(), pars.end(), resetOwnerAndChanges());
568 pars.back().insert(0, grabSelection(cur), LyXFont());
569 theCuts.push(make_pair(pars, bp.textclass));
571 // tell tabular that a recent copy happened
572 dirtyTabularStack(false);
576 std::string getSelection(Buffer const & buf, size_t sel_index)
578 return sel_index < theCuts.size()
579 ? theCuts[sel_index].first.back().asString(buf, false)
584 void pasteParagraphList(LCursor & cur, ParagraphList const & parlist,
585 textclass_type textclass)
587 if (cur.inTexted()) {
588 LyXText * text = cur.text();
597 boost::tie(ppp, endpit) =
598 pasteSelectionHelper(cur.buffer(),
600 cur.pit(), cur.pos(),
603 bufferErrors(cur.buffer(), el);
604 updateCounters(cur.buffer());
605 cur.clearSelection();
606 text->setCursor(cur, ppp.first, ppp.second);
609 // mathed is handled in MathNestInset/MathGridInset
610 BOOST_ASSERT(!cur.inMathed());
614 void pasteSelection(LCursor & cur, size_t sel_index)
616 // this does not make sense, if there is nothing to paste
617 if (!checkPastePossible(sel_index))
620 pasteParagraphList(cur, theCuts[sel_index].first,
621 theCuts[sel_index].second);
622 cur.bv().showErrorList(_("Paste"));
627 void setSelectionRange(LCursor & cur, pos_type length)
629 LyXText * text = cur.text();
635 text->cursorRight(cur);
640 // simple replacing. The font of the first selected character is used
641 void replaceSelectionWithString(LCursor & cur, string const & str)
643 LyXText * text = cur.text();
647 // Get font setting before we cut
648 pos_type pos = cur.selEnd().pos();
649 Paragraph & par = text->getPar(cur.selEnd().pit());
651 par.getFontSettings(cur.buffer().params(), cur.selBegin().pos());
653 // Insert the new string
654 string::const_iterator cit = str.begin();
655 string::const_iterator end = str.end();
656 for (; cit != end; ++cit, ++pos)
657 par.insertChar(pos, (*cit), font);
660 cutSelection(cur, true, false);
664 void replaceSelection(LCursor & cur)
667 cutSelection(cur, true, false);
671 // only used by the spellchecker
672 void replaceWord(LCursor & cur, string const & replacestring)
674 LyXText * text = cur.text();
677 replaceSelectionWithString(cur, replacestring);
678 setSelectionRange(cur, replacestring.length());
680 // Go back so that replacement string is also spellchecked
681 for (string::size_type i = 0; i < replacestring.length() + 1; ++i)
682 text->cursorLeft(cur);
686 void eraseSelection(LCursor & cur)
688 //lyxerr << "LCursor::eraseSelection begin: " << cur << endl;
689 CursorSlice const & i1 = cur.selBegin();
690 CursorSlice const & i2 = cur.selEnd();
691 if (i1.inset().asMathInset()) {
693 if (i1.idx() == i2.idx()) {
694 i1.cell().erase(i1.pos(), i2.pos());
695 // We may have deleted i1.cell(cur.pos()).
696 // Make sure that pos is valid.
697 if (cur.pos() > cur.lastpos())
698 cur.pos() = cur.lastpos();
700 MathInset * p = i1.asMathInset();
701 InsetBase::row_type r1, r2;
702 InsetBase::col_type c1, c2;
703 region(i1, i2, r1, r2, c1, c2);
704 for (InsetBase::row_type row = r1; row <= r2; ++row)
705 for (InsetBase::col_type col = c1; col <= c2; ++col)
706 p->cell(p->index(row, col)).clear();
707 // We've deleted the whole cell. Only pos 0 is valid.
710 // need a valid cursor. (Lgb)
711 cur.clearSelection();
713 lyxerr << "can't erase this selection 1" << endl;
715 //lyxerr << "LCursor::eraseSelection end: " << cur << endl;
719 void selDel(LCursor & cur)
721 //lyxerr << "LCursor::selDel" << endl;
727 void selClearOrDel(LCursor & cur)
729 //lyxerr << "LCursor::selClearOrDel" << endl;
730 if (lyxrc.auto_region_delete)
733 cur.selection() = false;
737 string grabSelection(LCursor const & cur)
739 if (!cur.selection())
742 // FIXME: What is wrong with the following?
744 std::ostringstream os;
745 for (DocIterator dit = cur.selectionBegin();
746 dit != cur.selectionEnd(); dit.forwardPos())
747 os << asString(dit.cell());
751 CursorSlice i1 = cur.selBegin();
752 CursorSlice i2 = cur.selEnd();
754 if (i1.idx() == i2.idx()) {
755 if (i1.inset().asMathInset()) {
756 MathArray::const_iterator it = i1.cell().begin();
757 return asString(MathArray(it + i1.pos(), it + i2.pos()));
759 return "unknown selection 1";
763 InsetBase::row_type r1, r2;
764 InsetBase::col_type c1, c2;
765 region(i1, i2, r1, r2, c1, c2);
768 if (i1.inset().asMathInset()) {
769 for (InsetBase::row_type row = r1; row <= r2; ++row) {
772 for (InsetBase::col_type col = c1; col <= c2; ++col) {
775 data += asString(i1.asMathInset()->
776 cell(i1.asMathInset()->index(row, col)));
780 data = "unknown selection 2";
786 void dirtyTabularStack(bool b)
788 dirty_tabular_stack_ = b;
792 bool tabularStackDirty()
794 return dirty_tabular_stack_;