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"
29 #include "lyxtextclasslist.h"
30 #include "paragraph.h"
31 #include "paragraph_funcs.h"
32 #include "ParagraphParameters.h"
33 #include "ParagraphList_fwd.h"
34 #include "pariterator.h"
37 #include "insets/insettabular.h"
39 #include "mathed/math_data.h"
40 #include "mathed/math_inset.h"
41 #include "mathed/math_support.h"
43 #include "support/lstrings.h"
45 #include <boost/tuple/tuple.hpp>
49 using lyx::textclass_type;
51 using lyx::support::bformat;
63 typedef std::pair<lyx::pit_type, int> PitPosPair;
65 typedef limited_stack<pair<ParagraphList, textclass_type> > CutStack;
69 struct resetOwnerAndChanges : public std::unary_function<Paragraph, void> {
70 void operator()(Paragraph & p) const {
77 void region(CursorSlice const & i1, CursorSlice const & i2,
78 InsetBase::row_type & r1, InsetBase::row_type & r2,
79 InsetBase::col_type & c1, InsetBase::col_type & c2)
81 InsetBase & p = i1.inset();
93 bool checkPastePossible(int index)
95 return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
99 pair<PitPosPair, pit_type>
100 pasteSelectionHelper(Buffer const & buffer, ParagraphList & pars,
101 pit_type pit, int pos,
102 textclass_type tc, size_t cut_index, ErrorList & errorlist)
104 if (!checkPastePossible(cut_index))
105 return make_pair(PitPosPair(pit, pos), pit);
107 BOOST_ASSERT (pos <= pars[pit].size());
109 // Make a copy of the CaP paragraphs.
110 ParagraphList insertion = theCuts[cut_index].first;
111 textclass_type const textclass = theCuts[cut_index].second;
113 // Now remove all out of the pars which is NOT allowed in the
114 // new environment and set also another font if that is required.
116 // Make sure there is no class difference.
117 lyx::cap::SwitchLayoutsBetweenClasses(textclass, tc, insertion,
120 ParagraphList::iterator tmpbuf = insertion.begin();
121 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
123 Paragraph::depth_type max_depth = pars[pit].getMaxDepthAfter();
125 for (; tmpbuf != insertion.end(); ++tmpbuf) {
126 // If we have a negative jump so that the depth would
127 // go below 0 depth then we have to redo the delta to
128 // this new max depth level so that subsequent
129 // paragraphs are aligned correctly to this paragraph
131 if (int(tmpbuf->params().depth()) + depth_delta < 0)
134 // Set the right depth so that we are not too deep or shallow.
135 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
136 if (tmpbuf->params().depth() > max_depth)
137 tmpbuf->params().depth(max_depth);
139 // Only set this from the 2nd on as the 2nd depends
140 // for maxDepth still on pit.
141 if (tmpbuf != insertion.begin())
142 max_depth = tmpbuf->getMaxDepthAfter();
144 // Set the inset owner of this paragraph.
145 tmpbuf->setInsetOwner(pars[pit].inInset());
146 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
147 if (tmpbuf->getChar(i) == Paragraph::META_INSET) {
148 if (!pars[pit].insetAllowed(tmpbuf->getInset(i)->lyxCode()))
154 bool const empty = pars[pit].empty();
156 // Make the buf exactly the same layout as the cursor
158 insertion.begin()->makeSameLayout(pars[pit]);
161 // Prepare the paragraphs and insets for insertion.
162 // A couple of insets store buffer references so need updating.
164 std::swap(in.paragraphs(), insertion);
166 ParIterator fpit = par_iterator_begin(in);
167 ParIterator fend = par_iterator_end(in);
169 for (; fpit != fend; ++fpit) {
170 InsetList::iterator lit = fpit->insetlist.begin();
171 InsetList::iterator eit = fpit->insetlist.end();
173 for (; lit != eit; ++lit) {
174 switch (lit->inset->lyxCode()) {
175 case InsetBase::TABULAR_CODE: {
176 InsetTabular * it = static_cast<InsetTabular*>(lit->inset);
186 std::swap(in.paragraphs(), insertion);
188 // Split the paragraph for inserting the buf if necessary.
190 breakParagraphConservative(buffer.params(), pars, pit, pos);
194 pars.insert(pars.begin() + pit, insertion.begin(),
197 // merge the empty par with the last par of the insertion
198 mergeParagraph(buffer.params(), pars,
199 pit + insertion.size() - 1);
201 pars.insert(pars.begin() + pit + 1, insertion.begin(),
204 // merge the first par of the insertion with the current par
205 mergeParagraph(buffer.params(), pars, pit);
208 pit_type last_paste = pit + insertion.size() - 1;
210 // Store the new cursor position.
212 pos = pars[last_paste].size();
214 // Maybe some pasting.
215 if (!empty && last_paste + 1 != pit_type(pars.size())) {
216 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
217 mergeParagraph(buffer.params(), pars, last_paste);
218 } else if (pars[last_paste + 1].empty()) {
219 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
220 mergeParagraph(buffer.params(), pars, last_paste);
221 } else if (pars[last_paste].empty()) {
222 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
223 mergeParagraph(buffer.params(), pars, last_paste);
225 pars[last_paste + 1].stripLeadingSpaces();
230 return make_pair(PitPosPair(pit, pos), last_paste + 1);
234 PitPosPair eraseSelectionHelper(BufferParams const & params,
235 ParagraphList & pars,
236 pit_type startpit, pit_type endpit,
237 int startpos, int endpos, bool doclear)
239 if (startpit == pit_type(pars.size()) ||
240 (startpos > pars[startpit].size()))
241 return PitPosPair(endpit, endpos);
243 if (endpit == pit_type(pars.size()) ||
244 startpit == endpit) {
245 endpos -= pars[startpit].erase(startpos, endpos);
246 return PitPosPair(endpit, endpos);
249 // clear end/begin fragments of the first/last par in selection
250 bool all_erased = true;
252 pars[startpit].erase(startpos, pars[startpit].size());
253 if (pars[startpit].size() != startpos)
256 endpos -= pars[endpit].erase(0, endpos);
260 // Loop through the deleted pars if any, erasing as needed
261 for (pit_type pit = startpit + 1; pit != endpit;) {
262 // "erase" the contents of the par
263 pars[pit].erase(0, pars[pit].size());
264 if (!pars[pit].size()) {
265 // remove the par if it's now empty
266 pars.erase(pars.begin() + pit);
274 #if 0 // FIXME: why for cut but not copy ?
275 // the cut selection should begin with standard layout
277 buf->params().clear();
279 buf->layout(textclasslist[buffer->params.textclass].defaultLayoutName());
283 if (startpit + 1 == pit_type(pars.size()))
284 return PitPosPair(endpit, endpos);
287 pars[startpit + 1].stripLeadingSpaces();
290 // paste the paragraphs again, if possible
292 (pars[startpit].hasSameLayout(pars[startpit + 1]) ||
293 pars[startpit + 1].empty())) {
294 mergeParagraph(params, pars, startpit);
295 // this because endpar gets deleted here!
300 return PitPosPair(endpit, endpos);
305 void copySelectionHelper(ParagraphList & pars,
306 pit_type startpit, pit_type endpit,
307 int start, int end, textclass_type tc)
309 BOOST_ASSERT(0 <= start && start <= pars[startpit].size());
310 BOOST_ASSERT(0 <= end && end <= pars[endpit].size());
311 BOOST_ASSERT(startpit != endpit || start <= end);
313 // Clone the paragraphs within the selection.
314 ParagraphList paragraphs(pars.begin() + startpit, pars.begin() + endpit + 1);
315 for_each(paragraphs.begin(), paragraphs.end(), resetOwnerAndChanges());
317 // Cut out the end of the last paragraph.
318 Paragraph & back = paragraphs.back();
319 back.erase(end, back.size());
321 // Cut out the begin of the first paragraph
322 Paragraph & front = paragraphs.front();
323 front.erase(0, start);
325 theCuts.push(make_pair(paragraphs, tc));
330 PitPosPair cutSelectionHelper(BufferParams const & params,
331 ParagraphList & pars, pit_type startpit, pit_type endpit,
332 int startpos, int endpos, textclass_type tc, bool doclear)
334 copySelectionHelper(pars, startpit, endpit, startpos, endpos, tc);
335 return eraseSelectionHelper(params, pars, startpit, endpit,
336 startpos, endpos, doclear);
348 string grabAndEraseSelection(LCursor & cur)
350 if (!cur.selection())
352 string res = grabSelection(cur);
354 cur.selection() = false;
359 int SwitchLayoutsBetweenClasses(textclass_type c1, textclass_type c2,
360 ParagraphList & pars, ErrorList & errorlist)
362 BOOST_ASSERT(!pars.empty());
367 LyXTextClass const & tclass1 = textclasslist[c1];
368 LyXTextClass const & tclass2 = textclasslist[c2];
371 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()) {
385 string const s = bformat(
386 _("Layout had to be changed from\n%1$s to %2$s\n"
387 "because of class conversion from\n%3$s to %4$s"),
388 name, it->layout()->name(), tclass1.name(), tclass2.name());
389 // To warn the user that something had to be done.
390 errorlist.push_back(ErrorItem("Changed Layout", s,
395 std::swap(in.paragraphs(), pars);
400 std::vector<string> const availableSelections(Buffer const & buffer)
402 vector<string> selList;
404 CutStack::const_iterator cit = theCuts.begin();
405 CutStack::const_iterator end = theCuts.end();
406 for (; cit != end; ++cit) {
407 // we do not use cit-> here because gcc 2.9x does not
409 ParagraphList const & pars = (*cit).first;
411 ParagraphList::const_iterator pit = pars.begin();
412 ParagraphList::const_iterator pend = pars.end();
413 for (; pit != pend; ++pit) {
414 asciiSel += pit->asString(buffer, false);
415 if (asciiSel.size() > 25) {
416 asciiSel.replace(22, string::npos, "...");
421 selList.push_back(asciiSel);
430 return theCuts.empty() ? 0 : theCuts[0].first.size();
434 void cutSelection(LCursor & cur, bool doclear, bool realcut)
436 if (cur.inTexted()) {
437 LyXText * text = cur.text();
439 // Stuff what we got on the clipboard. Even if there is no selection.
441 // There is a problem with having the stuffing here in that the
442 // larger the selection the slower LyX will get. This can be
443 // solved by running the line below only when the selection has
444 // finished. The solution used currently just works, to make it
445 // faster we need to be more clever and probably also have more
446 // calls to stuffClipboard. (Lgb)
447 cur.bv().stuffClipboard(cur.selectionAsString(true));
449 // This doesn't make sense, if there is no selection
450 if (!cur.selection())
453 // OK, we have a selection. This is always between cur.selBegin()
456 // make sure that the depth behind the selection are restored, too
457 recordUndoSelection(cur);
458 pit_type begpit = cur.selBegin().pit();
459 pit_type endpit = cur.selEnd().pit();
461 int endpos = cur.selEnd().pos();
463 BufferParams const & bp = cur.buffer().params();
465 copySelectionHelper(text->paragraphs(),
467 cur.selBegin().pos(), endpos,
471 boost::tie(endpit, endpos) =
472 eraseSelectionHelper(bp,
475 cur.selBegin().pos(), endpos,
478 // sometimes necessary
480 text->paragraphs()[begpit].stripLeadingSpaces();
482 // cutSelection can invalidate the cursor so we need to set
484 // we prefer the end for when tracking changes
488 // need a valid cursor. (Lgb)
489 cur.clearSelection();
490 text->updateCounters();
493 if (cur.inMathed()) {
494 lyxerr << "cutSelection in mathed" << endl;
497 cur.selection() = false;
503 void copySelection(LCursor & cur)
505 // stuff the selection onto the X clipboard, from an explicit copy request
506 cur.bv().stuffClipboard(cur.selectionAsString(true));
508 // this doesn't make sense, if there is no selection
509 if (!cur.selection())
512 if (cur.inTexted()) {
513 LyXText * text = cur.text();
515 // ok we have a selection. This is always between cur.selBegin()
516 // and sel_end cursor
518 // copy behind a space if there is one
519 ParagraphList & pars = text->paragraphs();
520 pos_type pos = cur.selBegin().pos();
521 pit_type par = cur.selBegin().pit();
522 while (pos < pars[par].size()
523 && pars[par].isLineSeparator(pos)
524 && (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
527 copySelectionHelper(pars, par, cur.selEnd().pit(),
528 pos, cur.selEnd().pos(), cur.buffer().params().textclass);
531 if (cur.inMathed()) {
532 lyxerr << "copySelection in mathed" << endl;
534 pars.push_back(Paragraph());
535 BufferParams const & bp = cur.buffer().params();
536 pars.back().layout(bp.getLyXTextClass().defaultLayout());
537 for_each(pars.begin(), pars.end(), resetOwnerAndChanges());
538 pars.back().insert(0, grabSelection(cur), LyXFont());
539 theCuts.push(make_pair(pars, bp.textclass));
544 std::string getSelection(Buffer const & buf, size_t sel_index)
546 return sel_index < theCuts.size()
547 ? theCuts[sel_index].first.back().asString(buf, false)
552 void pasteSelection(LCursor & cur, size_t sel_index)
554 // this does not make sense, if there is nothing to paste
555 lyxerr << "#### pasteSelection " << sel_index << endl;
556 if (!checkPastePossible(sel_index))
559 if (cur.inTexted()) {
560 LyXText * text = cur.text();
570 boost::tie(ppp, endpit) =
571 pasteSelectionHelper(cur.buffer(),
573 cur.pit(), cur.pos(),
574 cur.buffer().params().textclass,
576 bufferErrors(cur.buffer(), el);
577 cur.bv().showErrorList(_("Paste"));
579 cur.clearSelection();
581 text->setCursor(cur, ppp.first, ppp.second);
583 text->updateCounters();
586 if (cur.inMathed()) {
587 lyxerr << "### should be handled in MathNest/GridInset" << endl;
592 void setSelectionRange(LCursor & cur, pos_type length)
594 LyXText * text = cur.text();
600 text->cursorRight(cur);
605 // simple replacing. The font of the first selected character is used
606 void replaceSelectionWithString(LCursor & cur, string const & str)
608 LyXText * text = cur.text();
612 // Get font setting before we cut
613 pos_type pos = cur.selEnd().pos();
614 Paragraph & par = text->getPar(cur.selEnd().pit());
616 par.getFontSettings(cur.buffer().params(), cur.selBegin().pos());
618 // Insert the new string
619 string::const_iterator cit = str.begin();
620 string::const_iterator end = str.end();
621 for (; cit != end; ++cit, ++pos)
622 par.insertChar(pos, (*cit), font);
625 cutSelection(cur, true, false);
629 void replaceSelection(LCursor & cur)
632 cutSelection(cur, true, false);
636 // only used by the spellchecker
637 void replaceWord(LCursor & cur, string const & replacestring)
639 LyXText * text = cur.text();
642 replaceSelectionWithString(cur, replacestring);
643 setSelectionRange(cur, replacestring.length());
645 // Go back so that replacement string is also spellchecked
646 for (string::size_type i = 0; i < replacestring.length() + 1; ++i)
647 text->cursorLeft(cur);
651 void eraseSelection(LCursor & cur)
653 //lyxerr << "LCursor::eraseSelection begin: " << cur << endl;
654 CursorSlice const & i1 = cur.selBegin();
655 CursorSlice const & i2 = cur.selEnd();
656 if (i1.inset().asMathInset()) {
657 if (i1.idx() == i2.idx()) {
658 i1.cell().erase(i1.pos(), i2.pos());
660 MathInset * p = i1.asMathInset();
661 InsetBase::row_type r1, r2;
662 InsetBase::col_type c1, c2;
663 region(i1, i2, r1, r2, c1, c2);
664 for (InsetBase::row_type row = r1; row <= r2; ++row)
665 for (InsetBase::col_type col = c1; col <= c2; ++col)
666 p->cell(p->index(row, col)).clear();
669 cur.pos() = 0; // We've deleted the whole cell. Only pos 0 is valid.
672 lyxerr << "can't erase this selection 1" << endl;
674 //lyxerr << "LCursor::eraseSelection end: " << cur << endl;
678 void selDel(LCursor & cur)
680 //lyxerr << "LCursor::selDel" << endl;
681 if (cur.selection()) {
683 cur.selection() = false;
688 void selClearOrDel(LCursor & cur)
690 //lyxerr << "LCursor::selClearOrDel" << endl;
691 if (lyxrc.auto_region_delete)
694 cur.selection() = false;
698 string grabSelection(LCursor & cur)
700 if (!cur.selection())
703 CursorSlice i1 = cur.selBegin();
704 CursorSlice i2 = cur.selEnd();
706 if (i1.idx() == i2.idx()) {
707 if (i1.inset().asMathInset()) {
708 MathArray::const_iterator it = i1.cell().begin();
709 return asString(MathArray(it + i1.pos(), it + i2.pos()));
711 return "unknown selection 1";
715 InsetBase::row_type r1, r2;
716 InsetBase::col_type c1, c2;
717 region(i1, i2, r1, r2, c1, c2);
720 if (i1.inset().asMathInset()) {
721 for (InsetBase::row_type row = r1; row <= r2; ++row) {
724 for (InsetBase::col_type col = c1; col <= c2; ++col) {
727 data += asString(i1.asMathInset()->
728 cell(i1.asMathInset()->index(row, col)));
732 data = "unknown selection 2";