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::par_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, par_type>
100 pasteSelectionHelper(Buffer const & buffer, ParagraphList & pars,
101 par_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 // Make the buf exactly the same layout as the cursor paragraph.
155 insertion.begin()->makeSameLayout(pars[pit]);
157 // Prepare the paragraphs and insets for insertion.
158 // A couple of insets store buffer references so need updating.
160 std::swap(in.paragraphs(), insertion);
162 ParIterator fpit = par_iterator_begin(in);
163 ParIterator fend = par_iterator_end(in);
165 for (; fpit != fend; ++fpit) {
166 InsetList::iterator lit = fpit->insetlist.begin();
167 InsetList::iterator eit = fpit->insetlist.end();
169 for (; lit != eit; ++lit) {
170 switch (lit->inset->lyxCode()) {
171 case InsetOld::TABULAR_CODE: {
172 InsetTabular * it = static_cast<InsetTabular*>(lit->inset);
182 std::swap(in.paragraphs(), insertion);
184 // Split the paragraph for inserting the buf if necessary.
185 bool did_split = false;
186 if (pars[pit].size() || pit + 1 == par_type(pars.size())) {
187 breakParagraphConservative(buffer.params(), pars, pit, pos);
192 pars.insert(pars.begin() + pit + 1, insertion.begin(), insertion.end());
193 mergeParagraph(buffer.params(), pars, pit);
195 par_type last_paste = pit + insertion.size() - 1;
197 // Store the new cursor position.
199 pos = pars[last_paste].size();
201 // Maybe some pasting.
202 if (did_split && last_paste + 1 != par_type(pars.size())) {
203 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
204 mergeParagraph(buffer.params(), pars, last_paste);
205 } else if (pars[last_paste + 1].empty()) {
206 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
207 mergeParagraph(buffer.params(), pars, last_paste);
208 } else if (pars[last_paste].empty()) {
209 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
210 mergeParagraph(buffer.params(), pars, last_paste);
212 pars[last_paste + 1].stripLeadingSpaces();
217 return make_pair(PitPosPair(pit, pos), last_paste + 1);
221 PitPosPair eraseSelectionHelper(BufferParams const & params,
222 ParagraphList & pars,
223 par_type startpit, par_type endpit,
224 int startpos, int endpos, bool doclear)
226 if (startpit == par_type(pars.size()) ||
227 (startpos > pars[startpit].size()))
228 return PitPosPair(endpit, endpos);
230 if (endpit == par_type(pars.size()) ||
231 startpit == endpit) {
232 endpos -= pars[startpit].erase(startpos, endpos);
233 return PitPosPair(endpit, endpos);
236 // clear end/begin fragments of the first/last par in selection
237 bool all_erased = true;
239 pars[startpit].erase(startpos, pars[startpit].size());
240 if (pars[startpit].size() != startpos)
243 endpos -= pars[endpit].erase(0, endpos);
247 // Loop through the deleted pars if any, erasing as needed
248 for (par_type pit = startpit + 1; pit != endpit;) {
249 // "erase" the contents of the par
250 pars[pit].erase(0, pars[pit].size());
251 if (!pars[pit].size()) {
252 // remove the par if it's now empty
253 pars.erase(pars.begin() + pit);
261 #if 0 // FIXME: why for cut but not copy ?
262 // the cut selection should begin with standard layout
264 buf->params().clear();
266 buf->layout(textclasslist[buffer->params.textclass].defaultLayoutName());
270 if (startpit + 1 == par_type(pars.size()))
271 return PitPosPair(endpit, endpos);
274 pars[startpit + 1].stripLeadingSpaces();
277 // paste the paragraphs again, if possible
279 (pars[startpit].hasSameLayout(pars[startpit + 1]) ||
280 pars[startpit + 1].empty())) {
281 mergeParagraph(params, pars, startpit);
282 // this because endpar gets deleted here!
287 return PitPosPair(endpit, endpos);
292 void copySelectionHelper(ParagraphList & pars,
293 par_type startpit, par_type endpit,
294 int start, int end, textclass_type tc)
296 BOOST_ASSERT(0 <= start && start <= pars[startpit].size());
297 BOOST_ASSERT(0 <= end && end <= pars[endpit].size());
298 BOOST_ASSERT(startpit != endpit || start <= end);
300 // Clone the paragraphs within the selection.
301 ParagraphList paragraphs(pars.begin() + startpit, pars.begin() + endpit + 1);
302 for_each(paragraphs.begin(), paragraphs.end(), resetOwnerAndChanges());
304 // Cut out the end of the last paragraph.
305 Paragraph & back = paragraphs.back();
306 back.erase(end, back.size());
308 // Cut out the begin of the first paragraph
309 Paragraph & front = paragraphs.front();
310 front.erase(0, start);
312 theCuts.push(make_pair(paragraphs, tc));
317 PitPosPair cutSelectionHelper(BufferParams const & params,
318 ParagraphList & pars, par_type startpit, par_type endpit,
319 int startpos, int endpos, textclass_type tc, bool doclear)
321 copySelectionHelper(pars, startpit, endpit, startpos, endpos, tc);
322 return eraseSelectionHelper(params, pars, startpit, endpit,
323 startpos, endpos, doclear);
335 string grabAndEraseSelection(LCursor & cur)
337 if (!cur.selection())
339 string res = grabSelection(cur);
341 cur.selection() = false;
346 int SwitchLayoutsBetweenClasses(textclass_type c1, textclass_type c2,
347 ParagraphList & pars, ErrorList & errorlist)
349 BOOST_ASSERT(!pars.empty());
354 LyXTextClass const & tclass1 = textclasslist[c1];
355 LyXTextClass const & tclass2 = textclasslist[c2];
358 std::swap(in.paragraphs(), pars);
360 ParIterator end = par_iterator_end(in);
361 for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
362 string const name = it->layout()->name();
363 bool hasLayout = tclass2.hasLayout(name);
366 it->layout(tclass2[name]);
368 it->layout(tclass2.defaultLayout());
370 if (!hasLayout && name != tclass1.defaultLayoutName()) {
372 string const s = bformat(
373 _("Layout had to be changed from\n%1$s to %2$s\n"
374 "because of class conversion from\n%3$s to %4$s"),
375 name, it->layout()->name(), tclass1.name(), tclass2.name());
376 // To warn the user that something had to be done.
377 errorlist.push_back(ErrorItem("Changed Layout", s,
382 std::swap(in.paragraphs(), pars);
387 std::vector<string> const availableSelections(Buffer const & buffer)
389 vector<string> selList;
391 CutStack::const_iterator cit = theCuts.begin();
392 CutStack::const_iterator end = theCuts.end();
393 for (; cit != end; ++cit) {
394 // we do not use cit-> here because gcc 2.9x does not
396 ParagraphList const & pars = (*cit).first;
398 ParagraphList::const_iterator pit = pars.begin();
399 ParagraphList::const_iterator pend = pars.end();
400 for (; pit != pend; ++pit) {
401 asciiSel += pit->asString(buffer, false);
402 if (asciiSel.size() > 25) {
403 asciiSel.replace(22, string::npos, "...");
408 selList.push_back(asciiSel);
417 return theCuts.empty() ? 0 : theCuts[0].first.size();
421 void cutSelection(LCursor & cur, bool doclear, bool realcut)
423 if (cur.inTexted()) {
424 LyXText * text = cur.text();
426 // Stuff what we got on the clipboard. Even if there is no selection.
428 // There is a problem with having the stuffing here in that the
429 // larger the selection the slower LyX will get. This can be
430 // solved by running the line below only when the selection has
431 // finished. The solution used currently just works, to make it
432 // faster we need to be more clever and probably also have more
433 // calls to stuffClipboard. (Lgb)
434 cur.bv().stuffClipboard(cur.selectionAsString(true));
436 // This doesn't make sense, if there is no selection
437 if (!cur.selection())
440 // OK, we have a selection. This is always between cur.selBegin()
443 // make sure that the depth behind the selection are restored, too
444 recordUndoSelection(cur);
445 par_type begpit = cur.selBegin().par();
446 par_type endpit = cur.selEnd().par();
448 int endpos = cur.selEnd().pos();
450 BufferParams const & bp = cur.buffer().params();
452 copySelectionHelper(text->paragraphs(),
454 cur.selBegin().pos(), endpos,
458 boost::tie(endpit, endpos) =
459 eraseSelectionHelper(bp,
462 cur.selBegin().pos(), endpos,
465 // sometimes necessary
467 text->paragraphs()[begpit].stripLeadingSpaces();
469 text->redoParagraphs(begpit, begpit + 1);
470 // cutSelection can invalidate the cursor so we need to set
472 // we prefer the end for when tracking changes
476 // need a valid cursor. (Lgb)
477 cur.clearSelection();
478 text->updateCounters();
481 if (cur.inMathed()) {
482 lyxerr << "cutSelection in mathed" << endl;
485 cur.selection() = false;
491 void copySelection(LCursor & cur)
493 // stuff the selection onto the X clipboard, from an explicit copy request
494 cur.bv().stuffClipboard(cur.selectionAsString(true));
496 // this doesn't make sense, if there is no selection
497 if (!cur.selection())
500 if (cur.inTexted()) {
501 LyXText * text = cur.text();
503 // ok we have a selection. This is always between cur.selBegin()
504 // and sel_end cursor
506 // copy behind a space if there is one
507 ParagraphList & pars = text->paragraphs();
508 pos_type pos = cur.selBegin().pos();
509 par_type par = cur.selBegin().par();
510 while (pos < pars[par].size()
511 && pars[par].isLineSeparator(pos)
512 && (par != cur.selEnd().par() || pos < cur.selEnd().pos()))
515 copySelectionHelper(pars, par, cur.selEnd().par(),
516 pos, cur.selEnd().pos(), cur.buffer().params().textclass);
519 if (cur.inMathed()) {
520 lyxerr << "copySelection in mathed" << endl;
522 pars.push_back(Paragraph());
523 BufferParams const & bp = cur.buffer().params();
524 pars.back().layout(bp.getLyXTextClass().defaultLayout());
525 for_each(pars.begin(), pars.end(), resetOwnerAndChanges());
526 pars.back().insert(0, grabSelection(cur), LyXFont());
527 theCuts.push(make_pair(pars, bp.textclass));
532 std::string getSelection(Buffer const & buf, size_t sel_index)
534 return sel_index < theCuts.size()
535 ? theCuts[sel_index].first.back().asString(buf, false)
540 void pasteSelection(LCursor & cur, size_t sel_index)
542 // this does not make sense, if there is nothing to paste
543 lyxerr << "#### pasteSelection " << sel_index << endl;
544 if (!checkPastePossible(sel_index))
547 if (cur.inTexted()) {
548 LyXText * text = cur.text();
558 boost::tie(ppp, endpit) =
559 pasteSelectionHelper(cur.buffer(),
561 cur.par(), cur.pos(),
562 cur.buffer().params().textclass,
564 bufferErrors(cur.buffer(), el);
565 cur.bv().showErrorList(_("Paste"));
567 text->redoParagraphs(cur.par(), endpit);
569 cur.clearSelection();
571 text->setCursor(cur, ppp.first, ppp.second);
573 text->updateCounters();
576 if (cur.inMathed()) {
577 lyxerr << "### should be handled in MathNest/GridInset" << endl;
582 void setSelectionRange(LCursor & cur, pos_type length)
584 LyXText * text = cur.text();
590 text->cursorRight(cur);
595 // simple replacing. The font of the first selected character is used
596 void replaceSelectionWithString(LCursor & cur, string const & str)
598 LyXText * text = cur.text();
602 // Get font setting before we cut
603 pos_type pos = cur.selEnd().pos();
604 Paragraph & par = text->getPar(cur.selEnd().par());
606 par.getFontSettings(cur.buffer().params(), cur.selBegin().pos());
608 // Insert the new string
609 string::const_iterator cit = str.begin();
610 string::const_iterator end = str.end();
611 for (; cit != end; ++cit, ++pos)
612 par.insertChar(pos, (*cit), font);
615 cutSelection(cur, true, false);
619 void replaceSelection(LCursor & cur)
622 cutSelection(cur, true, false);
626 // only used by the spellchecker
627 void replaceWord(LCursor & cur, string const & replacestring)
629 LyXText * text = cur.text();
632 replaceSelectionWithString(cur, replacestring);
633 setSelectionRange(cur, replacestring.length());
635 // Go back so that replacement string is also spellchecked
636 for (string::size_type i = 0; i < replacestring.length() + 1; ++i)
637 text->cursorLeft(cur);
641 void eraseSelection(LCursor & cur)
643 //lyxerr << "LCursor::eraseSelection begin: " << cur << endl;
644 CursorSlice const & i1 = cur.selBegin();
645 CursorSlice const & i2 = cur.selEnd();
646 if (i1.inset().asMathInset()) {
647 if (i1.idx() == i2.idx()) {
648 i1.cell().erase(i1.pos(), i2.pos());
650 MathInset * p = i1.asMathInset();
651 InsetBase::row_type r1, r2;
652 InsetBase::col_type c1, c2;
653 region(i1, i2, r1, r2, c1, c2);
654 for (InsetBase::row_type row = r1; row <= r2; ++row)
655 for (InsetBase::col_type col = c1; col <= c2; ++col)
656 p->cell(p->index(row, col)).clear();
659 cur.pos() = 0; // We've deleted the whole cell. Only pos 0 is valid.
662 lyxerr << "can't erase this selection 1" << endl;
664 //lyxerr << "LCursor::eraseSelection end: " << cur << endl;
668 void selDel(LCursor & cur)
670 //lyxerr << "LCursor::selDel" << endl;
671 if (cur.selection()) {
673 cur.selection() = false;
678 void selClearOrDel(LCursor & cur)
680 //lyxerr << "LCursor::selClearOrDel" << endl;
681 if (lyxrc.auto_region_delete)
684 cur.selection() = false;
688 string grabSelection(LCursor & cur)
690 if (!cur.selection())
693 CursorSlice i1 = cur.selBegin();
694 CursorSlice i2 = cur.selEnd();
696 if (i1.idx() == i2.idx()) {
697 if (i1.inset().asMathInset()) {
698 MathArray::const_iterator it = i1.cell().begin();
699 return asString(MathArray(it + i1.pos(), it + i2.pos()));
701 return "unknown selection 1";
705 InsetBase::row_type r1, r2;
706 InsetBase::col_type c1, c2;
707 region(i1, i2, r1, r2, c1, c2);
710 if (i1.inset().asMathInset()) {
711 for (InsetBase::row_type row = r1; row <= r2; ++row) {
714 for (InsetBase::col_type col = c1; col <= c2; ++col) {
717 data += asString(i1.asMathInset()->
718 cell(i1.asMathInset()->index(row, col)));
722 data = "unknown selection 2";