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 class resetOwnerAndChanges : public std::unary_function<Paragraph, void> {
71 void operator()(Paragraph & p) const {
78 void region(CursorSlice const & i1, CursorSlice const & i2,
79 InsetBase::row_type & r1, InsetBase::row_type & r2,
80 InsetBase::col_type & c1, InsetBase::col_type & c2)
82 InsetBase & p = i1.inset();
94 bool checkPastePossible(int index)
96 return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
100 pair<PitPosPair, pit_type>
101 pasteSelectionHelper(Buffer const & buffer, ParagraphList & pars,
102 pit_type pit, int pos,
103 textclass_type tc, size_t cut_index, ErrorList & errorlist)
105 if (!checkPastePossible(cut_index))
106 return make_pair(PitPosPair(pit, pos), pit);
108 BOOST_ASSERT (pos <= pars[pit].size());
110 // Make a copy of the CaP paragraphs.
111 ParagraphList insertion = theCuts[cut_index].first;
112 textclass_type const textclass = theCuts[cut_index].second;
114 // Now remove all out of the pars which is NOT allowed in the
115 // new environment and set also another font if that is required.
117 // Convert newline to paragraph break in ERT inset.
118 // This should not be here!
119 if (pars[pit].inInset() &&
120 pars[pit].inInset()->lyxCode() == InsetBase::ERT_CODE) {
121 for (ParagraphList::size_type i = 0; i < insertion.size(); ++i) {
122 for (pos_type j = 0; j < insertion[i].size(); ++j) {
123 if (insertion[i].isNewline(j)) {
124 insertion[i].erase(j);
125 breakParagraphConservative(
133 // Make sure there is no class difference.
134 lyx::cap::SwitchLayoutsBetweenClasses(textclass, tc, insertion,
137 ParagraphList::iterator tmpbuf = insertion.begin();
138 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
140 Paragraph::depth_type max_depth = pars[pit].getMaxDepthAfter();
142 for (; tmpbuf != insertion.end(); ++tmpbuf) {
143 // If we have a negative jump so that the depth would
144 // go below 0 depth then we have to redo the delta to
145 // this new max depth level so that subsequent
146 // paragraphs are aligned correctly to this paragraph
148 if (int(tmpbuf->params().depth()) + depth_delta < 0)
151 // Set the right depth so that we are not too deep or shallow.
152 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
153 if (tmpbuf->params().depth() > max_depth)
154 tmpbuf->params().depth(max_depth);
156 // Only set this from the 2nd on as the 2nd depends
157 // for maxDepth still on pit.
158 if (tmpbuf != insertion.begin())
159 max_depth = tmpbuf->getMaxDepthAfter();
161 // Set the inset owner of this paragraph.
162 tmpbuf->setInsetOwner(pars[pit].inInset());
163 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
164 if (tmpbuf->getChar(i) == Paragraph::META_INSET &&
165 !pars[pit].insetAllowed(tmpbuf->getInset(i)->lyxCode()))
170 bool const empty = pars[pit].empty();
172 // Make the buf exactly the same layout as the cursor
174 insertion.begin()->makeSameLayout(pars[pit]);
177 // Prepare the paragraphs and insets for insertion.
178 // A couple of insets store buffer references so need updating.
180 std::swap(in.paragraphs(), insertion);
182 ParIterator fpit = par_iterator_begin(in);
183 ParIterator fend = par_iterator_end(in);
185 for (; fpit != fend; ++fpit) {
186 InsetList::iterator lit = fpit->insetlist.begin();
187 InsetList::iterator eit = fpit->insetlist.end();
189 for (; lit != eit; ++lit) {
190 switch (lit->inset->lyxCode()) {
191 case InsetBase::TABULAR_CODE: {
192 InsetTabular * it = static_cast<InsetTabular*>(lit->inset);
202 std::swap(in.paragraphs(), insertion);
204 // Split the paragraph for inserting the buf if necessary.
206 breakParagraphConservative(buffer.params(), pars, pit, pos);
210 pars.insert(pars.begin() + pit, insertion.begin(),
213 // merge the empty par with the last par of the insertion
214 mergeParagraph(buffer.params(), pars,
215 pit + insertion.size() - 1);
217 pars.insert(pars.begin() + pit + 1, insertion.begin(),
220 // merge the first par of the insertion with the current par
221 mergeParagraph(buffer.params(), pars, pit);
224 pit_type last_paste = pit + insertion.size() - 1;
226 // Store the new cursor position.
228 pos = pars[last_paste].size();
230 // Maybe some pasting.
231 if (!empty && last_paste + 1 != pit_type(pars.size())) {
232 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
233 mergeParagraph(buffer.params(), pars, last_paste);
234 } else if (pars[last_paste + 1].empty()) {
235 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
236 mergeParagraph(buffer.params(), pars, last_paste);
237 } else if (pars[last_paste].empty()) {
238 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
239 mergeParagraph(buffer.params(), pars, last_paste);
241 pars[last_paste + 1].stripLeadingSpaces();
246 return make_pair(PitPosPair(pit, pos), last_paste + 1);
250 PitPosPair eraseSelectionHelper(BufferParams const & params,
251 ParagraphList & pars,
252 pit_type startpit, pit_type endpit,
253 int startpos, int endpos, bool doclear)
255 if (startpit == pit_type(pars.size()) ||
256 (startpos > pars[startpit].size()))
257 return PitPosPair(endpit, endpos);
259 if (endpit == pit_type(pars.size()) ||
260 startpit == endpit) {
261 endpos -= pars[startpit].erase(startpos, endpos);
262 return PitPosPair(endpit, endpos);
265 // clear end/begin fragments of the first/last par in selection
266 bool all_erased = true;
268 pars[startpit].erase(startpos, pars[startpit].size());
269 if (pars[startpit].size() != startpos)
272 endpos -= pars[endpit].erase(0, endpos);
276 // Loop through the deleted pars if any, erasing as needed
277 for (pit_type pit = startpit + 1; pit != endpit;) {
278 // "erase" the contents of the par
279 pars[pit].erase(0, pars[pit].size());
280 if (!pars[pit].size()) {
281 // remove the par if it's now empty
282 pars.erase(pars.begin() + pit);
290 #if 0 // FIXME: why for cut but not copy ?
291 // the cut selection should begin with standard layout
293 buf->params().clear();
295 buf->layout(textclasslist[buffer->params.textclass].defaultLayoutName());
299 if (startpit + 1 == pit_type(pars.size()))
300 return PitPosPair(endpit, endpos);
303 pars[startpit + 1].stripLeadingSpaces();
306 // paste the paragraphs again, if possible
308 (pars[startpit].hasSameLayout(pars[startpit + 1]) ||
309 pars[startpit + 1].empty())) {
310 mergeParagraph(params, pars, startpit);
311 // this because endpar gets deleted here!
316 return PitPosPair(endpit, endpos);
321 void copySelectionHelper(ParagraphList & pars,
322 pit_type startpit, pit_type endpit,
323 int start, int end, textclass_type tc)
325 BOOST_ASSERT(0 <= start && start <= pars[startpit].size());
326 BOOST_ASSERT(0 <= end && end <= pars[endpit].size());
327 BOOST_ASSERT(startpit != endpit || start <= end);
329 // Clone the paragraphs within the selection.
330 ParagraphList paragraphs(pars.begin() + startpit, pars.begin() + endpit + 1);
331 for_each(paragraphs.begin(), paragraphs.end(), resetOwnerAndChanges());
333 // Cut out the end of the last paragraph.
334 Paragraph & back = paragraphs.back();
335 back.erase(end, back.size());
337 // Cut out the begin of the first paragraph
338 Paragraph & front = paragraphs.front();
339 front.erase(0, start);
341 theCuts.push(make_pair(paragraphs, tc));
346 PitPosPair cutSelectionHelper(BufferParams const & params,
347 ParagraphList & pars, pit_type startpit, pit_type endpit,
348 int startpos, int endpos, textclass_type tc, bool doclear)
350 copySelectionHelper(pars, startpit, endpit, startpos, endpos, tc);
351 return eraseSelectionHelper(params, pars, startpit, endpit,
352 startpos, endpos, doclear);
364 string grabAndEraseSelection(LCursor & cur)
366 if (!cur.selection())
368 string res = grabSelection(cur);
370 cur.selection() = false;
375 int SwitchLayoutsBetweenClasses(textclass_type c1, textclass_type c2,
376 ParagraphList & pars, ErrorList & errorlist)
378 BOOST_ASSERT(!pars.empty());
383 LyXTextClass const & tclass1 = textclasslist[c1];
384 LyXTextClass const & tclass2 = textclasslist[c2];
387 std::swap(in.paragraphs(), pars);
389 ParIterator end = par_iterator_end(in);
390 for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
391 string const name = it->layout()->name();
392 bool hasLayout = tclass2.hasLayout(name);
395 it->layout(tclass2[name]);
397 it->layout(tclass2.defaultLayout());
399 if (!hasLayout && name != tclass1.defaultLayoutName()) {
401 string const s = bformat(
402 _("Layout had to be changed from\n%1$s to %2$s\n"
403 "because of class conversion from\n%3$s to %4$s"),
404 name, it->layout()->name(), tclass1.name(), tclass2.name());
405 // To warn the user that something had to be done.
406 errorlist.push_back(ErrorItem("Changed Layout", s,
411 std::swap(in.paragraphs(), pars);
416 std::vector<string> const availableSelections(Buffer const & buffer)
418 vector<string> selList;
420 CutStack::const_iterator cit = theCuts.begin();
421 CutStack::const_iterator end = theCuts.end();
422 for (; cit != end; ++cit) {
423 // we do not use cit-> here because gcc 2.9x does not
425 ParagraphList const & pars = (*cit).first;
427 ParagraphList::const_iterator pit = pars.begin();
428 ParagraphList::const_iterator pend = pars.end();
429 for (; pit != pend; ++pit) {
430 asciiSel += pit->asString(buffer, false);
431 if (asciiSel.size() > 25) {
432 asciiSel.replace(22, string::npos, "...");
437 selList.push_back(asciiSel);
446 return theCuts.empty() ? 0 : theCuts[0].first.size();
450 void cutSelection(LCursor & cur, bool doclear, bool realcut)
452 if (cur.inTexted()) {
453 LyXText * text = cur.text();
455 // Stuff what we got on the clipboard. Even if there is no selection.
457 // There is a problem with having the stuffing here in that the
458 // larger the selection the slower LyX will get. This can be
459 // solved by running the line below only when the selection has
460 // finished. The solution used currently just works, to make it
461 // faster we need to be more clever and probably also have more
462 // calls to stuffClipboard. (Lgb)
463 cur.bv().stuffClipboard(cur.selectionAsString(true));
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 // make sure that the depth behind the selection are restored, too
473 recordUndoSelection(cur);
474 pit_type begpit = cur.selBegin().pit();
475 pit_type endpit = cur.selEnd().pit();
477 int endpos = cur.selEnd().pos();
479 BufferParams const & bp = cur.buffer().params();
481 copySelectionHelper(text->paragraphs(),
483 cur.selBegin().pos(), endpos,
487 boost::tie(endpit, endpos) =
488 eraseSelectionHelper(bp,
491 cur.selBegin().pos(), endpos,
494 // sometimes necessary
496 text->paragraphs()[begpit].stripLeadingSpaces();
498 // cutSelection can invalidate the cursor so we need to set
500 // we prefer the end for when tracking changes
504 // need a valid cursor. (Lgb)
505 cur.clearSelection();
506 updateCounters(cur.buffer());
509 if (cur.inMathed()) {
510 lyxerr << "cutSelection in mathed" << endl;
513 cur.selection() = false;
519 void copySelection(LCursor & cur)
521 // stuff the selection onto the X clipboard, from an explicit copy request
522 cur.bv().stuffClipboard(cur.selectionAsString(true));
524 // this doesn't make sense, if there is no selection
525 if (!cur.selection())
528 if (cur.inTexted()) {
529 LyXText * text = cur.text();
531 // ok we have a selection. This is always between cur.selBegin()
532 // and sel_end cursor
534 // copy behind a space if there is one
535 ParagraphList & pars = text->paragraphs();
536 pos_type pos = cur.selBegin().pos();
537 pit_type par = cur.selBegin().pit();
538 while (pos < pars[par].size()
539 && pars[par].isLineSeparator(pos)
540 && (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
543 copySelectionHelper(pars, par, cur.selEnd().pit(),
544 pos, cur.selEnd().pos(), cur.buffer().params().textclass);
547 if (cur.inMathed()) {
548 lyxerr << "copySelection in mathed" << endl;
550 pars.push_back(Paragraph());
551 BufferParams const & bp = cur.buffer().params();
552 pars.back().layout(bp.getLyXTextClass().defaultLayout());
553 for_each(pars.begin(), pars.end(), resetOwnerAndChanges());
554 pars.back().insert(0, grabSelection(cur), LyXFont());
555 theCuts.push(make_pair(pars, bp.textclass));
560 std::string getSelection(Buffer const & buf, size_t sel_index)
562 return sel_index < theCuts.size()
563 ? theCuts[sel_index].first.back().asString(buf, false)
568 void pasteSelection(LCursor & cur, size_t sel_index)
570 // this does not make sense, if there is nothing to paste
571 lyxerr << "#### pasteSelection " << sel_index << endl;
572 if (!checkPastePossible(sel_index))
575 if (cur.inTexted()) {
576 LyXText * text = cur.text();
586 boost::tie(ppp, endpit) =
587 pasteSelectionHelper(cur.buffer(),
589 cur.pit(), cur.pos(),
590 cur.buffer().params().textclass,
592 bufferErrors(cur.buffer(), el);
593 cur.bv().showErrorList(_("Paste"));
595 cur.clearSelection();
597 text->setCursor(cur, ppp.first, ppp.second);
599 updateCounters(cur.buffer());
602 if (cur.inMathed()) {
603 lyxerr << "### should be handled in MathNest/GridInset" << endl;
608 void setSelectionRange(LCursor & cur, pos_type length)
610 LyXText * text = cur.text();
616 text->cursorRight(cur);
621 // simple replacing. The font of the first selected character is used
622 void replaceSelectionWithString(LCursor & cur, string const & str)
624 LyXText * text = cur.text();
628 // Get font setting before we cut
629 pos_type pos = cur.selEnd().pos();
630 Paragraph & par = text->getPar(cur.selEnd().pit());
632 par.getFontSettings(cur.buffer().params(), cur.selBegin().pos());
634 // Insert the new string
635 string::const_iterator cit = str.begin();
636 string::const_iterator end = str.end();
637 for (; cit != end; ++cit, ++pos)
638 par.insertChar(pos, (*cit), font);
641 cutSelection(cur, true, false);
645 void replaceSelection(LCursor & cur)
648 cutSelection(cur, true, false);
652 // only used by the spellchecker
653 void replaceWord(LCursor & cur, string const & replacestring)
655 LyXText * text = cur.text();
658 replaceSelectionWithString(cur, replacestring);
659 setSelectionRange(cur, replacestring.length());
661 // Go back so that replacement string is also spellchecked
662 for (string::size_type i = 0; i < replacestring.length() + 1; ++i)
663 text->cursorLeft(cur);
667 void eraseSelection(LCursor & cur)
669 //lyxerr << "LCursor::eraseSelection begin: " << cur << endl;
670 CursorSlice const & i1 = cur.selBegin();
671 CursorSlice const & i2 = cur.selEnd();
672 if (i1.inset().asMathInset()) {
673 if (i1.idx() == i2.idx()) {
674 i1.cell().erase(i1.pos(), i2.pos());
676 MathInset * p = i1.asMathInset();
677 InsetBase::row_type r1, r2;
678 InsetBase::col_type c1, c2;
679 region(i1, i2, r1, r2, c1, c2);
680 for (InsetBase::row_type row = r1; row <= r2; ++row)
681 for (InsetBase::col_type col = c1; col <= c2; ++col)
682 p->cell(p->index(row, col)).clear();
685 cur.pos() = 0; // We've deleted the whole cell. Only pos 0 is valid.
688 lyxerr << "can't erase this selection 1" << endl;
690 //lyxerr << "LCursor::eraseSelection end: " << cur << endl;
694 void selDel(LCursor & cur)
696 //lyxerr << "LCursor::selDel" << endl;
697 if (cur.selection()) {
699 cur.selection() = false;
704 void selClearOrDel(LCursor & cur)
706 //lyxerr << "LCursor::selClearOrDel" << endl;
707 if (lyxrc.auto_region_delete)
710 cur.selection() = false;
714 string grabSelection(LCursor & cur)
716 if (!cur.selection())
719 CursorSlice i1 = cur.selBegin();
720 CursorSlice i2 = cur.selEnd();
722 if (i1.idx() == i2.idx()) {
723 if (i1.inset().asMathInset()) {
724 MathArray::const_iterator it = i1.cell().begin();
725 return asString(MathArray(it + i1.pos(), it + i2.pos()));
727 return "unknown selection 1";
731 InsetBase::row_type r1, r2;
732 InsetBase::col_type c1, c2;
733 region(i1, i2, r1, r2, c1, c2);
736 if (i1.inset().asMathInset()) {
737 for (InsetBase::row_type row = r1; row <= r2; ++row) {
740 for (InsetBase::col_type col = c1; col <= c2; ++col) {
743 data += asString(i1.asMathInset()->
744 cell(i1.asMathInset()->index(row, col)));
748 data = "unknown selection 2";