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()->lyxCode() == InsetBase::ERT_CODE) {
120 for (ParagraphList::size_type i = 0; i < insertion.size(); ++i) {
121 for (pos_type j = 0; j < insertion[i].size(); ++j) {
122 if (insertion[i].isNewline(j)) {
123 insertion[i].erase(j);
124 breakParagraphConservative(
132 // Make sure there is no class difference.
133 lyx::cap::SwitchLayoutsBetweenClasses(textclass, tc, insertion,
136 ParagraphList::iterator tmpbuf = insertion.begin();
137 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
139 Paragraph::depth_type max_depth = pars[pit].getMaxDepthAfter();
141 for (; tmpbuf != insertion.end(); ++tmpbuf) {
142 // If we have a negative jump so that the depth would
143 // go below 0 depth then we have to redo the delta to
144 // this new max depth level so that subsequent
145 // paragraphs are aligned correctly to this paragraph
147 if (int(tmpbuf->params().depth()) + depth_delta < 0)
150 // Set the right depth so that we are not too deep or shallow.
151 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
152 if (tmpbuf->params().depth() > max_depth)
153 tmpbuf->params().depth(max_depth);
155 // Only set this from the 2nd on as the 2nd depends
156 // for maxDepth still on pit.
157 if (tmpbuf != insertion.begin())
158 max_depth = tmpbuf->getMaxDepthAfter();
160 // Set the inset owner of this paragraph.
161 tmpbuf->setInsetOwner(pars[pit].inInset());
162 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
163 if (tmpbuf->getChar(i) == Paragraph::META_INSET &&
164 !pars[pit].insetAllowed(tmpbuf->getInset(i)->lyxCode()))
169 bool const empty = pars[pit].empty();
171 // Make the buf exactly the same layout as the cursor
173 insertion.begin()->makeSameLayout(pars[pit]);
176 // Prepare the paragraphs and insets for insertion.
177 // A couple of insets store buffer references so need updating.
179 std::swap(in.paragraphs(), insertion);
181 ParIterator fpit = par_iterator_begin(in);
182 ParIterator fend = par_iterator_end(in);
184 for (; fpit != fend; ++fpit) {
185 InsetList::iterator lit = fpit->insetlist.begin();
186 InsetList::iterator eit = fpit->insetlist.end();
188 for (; lit != eit; ++lit) {
189 switch (lit->inset->lyxCode()) {
190 case InsetBase::TABULAR_CODE: {
191 InsetTabular * it = static_cast<InsetTabular*>(lit->inset);
201 std::swap(in.paragraphs(), insertion);
203 // Split the paragraph for inserting the buf if necessary.
205 breakParagraphConservative(buffer.params(), pars, pit, pos);
209 pars.insert(pars.begin() + pit, insertion.begin(),
212 // merge the empty par with the last par of the insertion
213 mergeParagraph(buffer.params(), pars,
214 pit + insertion.size() - 1);
216 pars.insert(pars.begin() + pit + 1, insertion.begin(),
219 // merge the first par of the insertion with the current par
220 mergeParagraph(buffer.params(), pars, pit);
223 pit_type last_paste = pit + insertion.size() - 1;
225 // Store the new cursor position.
227 pos = pars[last_paste].size();
229 // Maybe some pasting.
230 if (!empty && last_paste + 1 != pit_type(pars.size())) {
231 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
232 mergeParagraph(buffer.params(), pars, last_paste);
233 } else if (pars[last_paste + 1].empty()) {
234 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
235 mergeParagraph(buffer.params(), pars, last_paste);
236 } else if (pars[last_paste].empty()) {
237 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
238 mergeParagraph(buffer.params(), pars, last_paste);
240 pars[last_paste + 1].stripLeadingSpaces();
245 return make_pair(PitPosPair(pit, pos), last_paste + 1);
249 PitPosPair eraseSelectionHelper(BufferParams const & params,
250 ParagraphList & pars,
251 pit_type startpit, pit_type endpit,
252 int startpos, int endpos, bool doclear)
254 if (startpit == pit_type(pars.size()) ||
255 (startpos > pars[startpit].size()))
256 return PitPosPair(endpit, endpos);
258 if (endpit == pit_type(pars.size()) ||
259 startpit == endpit) {
260 endpos -= pars[startpit].erase(startpos, endpos);
261 return PitPosPair(endpit, endpos);
264 // clear end/begin fragments of the first/last par in selection
265 bool all_erased = true;
267 pars[startpit].erase(startpos, pars[startpit].size());
268 if (pars[startpit].size() != startpos)
271 endpos -= pars[endpit].erase(0, endpos);
275 // Loop through the deleted pars if any, erasing as needed
276 for (pit_type pit = startpit + 1; pit != endpit;) {
277 // "erase" the contents of the par
278 pars[pit].erase(0, pars[pit].size());
279 if (!pars[pit].size()) {
280 // remove the par if it's now empty
281 pars.erase(pars.begin() + pit);
289 #if 0 // FIXME: why for cut but not copy ?
290 // the cut selection should begin with standard layout
292 buf->params().clear();
294 buf->layout(textclasslist[buffer->params.textclass].defaultLayoutName());
298 if (startpit + 1 == pit_type(pars.size()))
299 return PitPosPair(endpit, endpos);
302 pars[startpit + 1].stripLeadingSpaces();
305 // paste the paragraphs again, if possible
307 (pars[startpit].hasSameLayout(pars[startpit + 1]) ||
308 pars[startpit + 1].empty())) {
309 mergeParagraph(params, pars, startpit);
310 // this because endpar gets deleted here!
315 return PitPosPair(endpit, endpos);
320 void copySelectionHelper(ParagraphList & pars,
321 pit_type startpit, pit_type endpit,
322 int start, int end, textclass_type tc)
324 BOOST_ASSERT(0 <= start && start <= pars[startpit].size());
325 BOOST_ASSERT(0 <= end && end <= pars[endpit].size());
326 BOOST_ASSERT(startpit != endpit || start <= end);
328 // Clone the paragraphs within the selection.
329 ParagraphList paragraphs(pars.begin() + startpit, pars.begin() + endpit + 1);
330 for_each(paragraphs.begin(), paragraphs.end(), resetOwnerAndChanges());
332 // Cut out the end of the last paragraph.
333 Paragraph & back = paragraphs.back();
334 back.erase(end, back.size());
336 // Cut out the begin of the first paragraph
337 Paragraph & front = paragraphs.front();
338 front.erase(0, start);
340 theCuts.push(make_pair(paragraphs, tc));
345 PitPosPair cutSelectionHelper(BufferParams const & params,
346 ParagraphList & pars, pit_type startpit, pit_type endpit,
347 int startpos, int endpos, textclass_type tc, bool doclear)
349 copySelectionHelper(pars, startpit, endpit, startpos, endpos, tc);
350 return eraseSelectionHelper(params, pars, startpit, endpit,
351 startpos, endpos, doclear);
363 string grabAndEraseSelection(LCursor & cur)
365 if (!cur.selection())
367 string res = grabSelection(cur);
369 cur.selection() = false;
374 int SwitchLayoutsBetweenClasses(textclass_type c1, textclass_type c2,
375 ParagraphList & pars, ErrorList & errorlist)
377 BOOST_ASSERT(!pars.empty());
382 LyXTextClass const & tclass1 = textclasslist[c1];
383 LyXTextClass const & tclass2 = textclasslist[c2];
386 std::swap(in.paragraphs(), pars);
388 ParIterator end = par_iterator_end(in);
389 for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
390 string const name = it->layout()->name();
391 bool hasLayout = tclass2.hasLayout(name);
394 it->layout(tclass2[name]);
396 it->layout(tclass2.defaultLayout());
398 if (!hasLayout && name != tclass1.defaultLayoutName()) {
400 string const s = bformat(
401 _("Layout had to be changed from\n%1$s to %2$s\n"
402 "because of class conversion from\n%3$s to %4$s"),
403 name, it->layout()->name(), tclass1.name(), tclass2.name());
404 // To warn the user that something had to be done.
405 errorlist.push_back(ErrorItem("Changed Layout", s,
410 std::swap(in.paragraphs(), pars);
415 std::vector<string> const availableSelections(Buffer const & buffer)
417 vector<string> selList;
419 CutStack::const_iterator cit = theCuts.begin();
420 CutStack::const_iterator end = theCuts.end();
421 for (; cit != end; ++cit) {
422 // we do not use cit-> here because gcc 2.9x does not
424 ParagraphList const & pars = (*cit).first;
426 ParagraphList::const_iterator pit = pars.begin();
427 ParagraphList::const_iterator pend = pars.end();
428 for (; pit != pend; ++pit) {
429 asciiSel += pit->asString(buffer, false);
430 if (asciiSel.size() > 25) {
431 asciiSel.replace(22, string::npos, "...");
436 selList.push_back(asciiSel);
445 return theCuts.empty() ? 0 : theCuts[0].first.size();
449 void cutSelection(LCursor & cur, bool doclear, bool realcut)
451 if (cur.inTexted()) {
452 LyXText * text = cur.text();
454 // Stuff what we got on the clipboard. Even if there is no selection.
456 // There is a problem with having the stuffing here in that the
457 // larger the selection the slower LyX will get. This can be
458 // solved by running the line below only when the selection has
459 // finished. The solution used currently just works, to make it
460 // faster we need to be more clever and probably also have more
461 // calls to stuffClipboard. (Lgb)
462 cur.bv().stuffClipboard(cur.selectionAsString(true));
464 // This doesn't make sense, if there is no selection
465 if (!cur.selection())
468 // OK, we have a selection. This is always between cur.selBegin()
471 // make sure that the depth behind the selection are restored, too
472 recordUndoSelection(cur);
473 pit_type begpit = cur.selBegin().pit();
474 pit_type endpit = cur.selEnd().pit();
476 int endpos = cur.selEnd().pos();
478 BufferParams const & bp = cur.buffer().params();
480 copySelectionHelper(text->paragraphs(),
482 cur.selBegin().pos(), endpos,
486 boost::tie(endpit, endpos) =
487 eraseSelectionHelper(bp,
490 cur.selBegin().pos(), endpos,
493 // sometimes necessary
495 text->paragraphs()[begpit].stripLeadingSpaces();
497 // cutSelection can invalidate the cursor so we need to set
499 // we prefer the end for when tracking changes
503 // need a valid cursor. (Lgb)
504 cur.clearSelection();
505 text->updateCounters();
508 if (cur.inMathed()) {
509 lyxerr << "cutSelection in mathed" << endl;
512 cur.selection() = false;
518 void copySelection(LCursor & cur)
520 // stuff the selection onto the X clipboard, from an explicit copy request
521 cur.bv().stuffClipboard(cur.selectionAsString(true));
523 // this doesn't make sense, if there is no selection
524 if (!cur.selection())
527 if (cur.inTexted()) {
528 LyXText * text = cur.text();
530 // ok we have a selection. This is always between cur.selBegin()
531 // and sel_end cursor
533 // copy behind a space if there is one
534 ParagraphList & pars = text->paragraphs();
535 pos_type pos = cur.selBegin().pos();
536 pit_type par = cur.selBegin().pit();
537 while (pos < pars[par].size()
538 && pars[par].isLineSeparator(pos)
539 && (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
542 copySelectionHelper(pars, par, cur.selEnd().pit(),
543 pos, cur.selEnd().pos(), cur.buffer().params().textclass);
546 if (cur.inMathed()) {
547 lyxerr << "copySelection in mathed" << endl;
549 pars.push_back(Paragraph());
550 BufferParams const & bp = cur.buffer().params();
551 pars.back().layout(bp.getLyXTextClass().defaultLayout());
552 for_each(pars.begin(), pars.end(), resetOwnerAndChanges());
553 pars.back().insert(0, grabSelection(cur), LyXFont());
554 theCuts.push(make_pair(pars, bp.textclass));
559 std::string getSelection(Buffer const & buf, size_t sel_index)
561 return sel_index < theCuts.size()
562 ? theCuts[sel_index].first.back().asString(buf, false)
567 void pasteSelection(LCursor & cur, size_t sel_index)
569 // this does not make sense, if there is nothing to paste
570 lyxerr << "#### pasteSelection " << sel_index << endl;
571 if (!checkPastePossible(sel_index))
574 if (cur.inTexted()) {
575 LyXText * text = cur.text();
585 boost::tie(ppp, endpit) =
586 pasteSelectionHelper(cur.buffer(),
588 cur.pit(), cur.pos(),
589 cur.buffer().params().textclass,
591 bufferErrors(cur.buffer(), el);
592 cur.bv().showErrorList(_("Paste"));
594 cur.clearSelection();
596 text->setCursor(cur, ppp.first, ppp.second);
598 text->updateCounters();
601 if (cur.inMathed()) {
602 lyxerr << "### should be handled in MathNest/GridInset" << endl;
607 void setSelectionRange(LCursor & cur, pos_type length)
609 LyXText * text = cur.text();
615 text->cursorRight(cur);
620 // simple replacing. The font of the first selected character is used
621 void replaceSelectionWithString(LCursor & cur, string const & str)
623 LyXText * text = cur.text();
627 // Get font setting before we cut
628 pos_type pos = cur.selEnd().pos();
629 Paragraph & par = text->getPar(cur.selEnd().pit());
631 par.getFontSettings(cur.buffer().params(), cur.selBegin().pos());
633 // Insert the new string
634 string::const_iterator cit = str.begin();
635 string::const_iterator end = str.end();
636 for (; cit != end; ++cit, ++pos)
637 par.insertChar(pos, (*cit), font);
640 cutSelection(cur, true, false);
644 void replaceSelection(LCursor & cur)
647 cutSelection(cur, true, false);
651 // only used by the spellchecker
652 void replaceWord(LCursor & cur, string const & replacestring)
654 LyXText * text = cur.text();
657 replaceSelectionWithString(cur, replacestring);
658 setSelectionRange(cur, replacestring.length());
660 // Go back so that replacement string is also spellchecked
661 for (string::size_type i = 0; i < replacestring.length() + 1; ++i)
662 text->cursorLeft(cur);
666 void eraseSelection(LCursor & cur)
668 //lyxerr << "LCursor::eraseSelection begin: " << cur << endl;
669 CursorSlice const & i1 = cur.selBegin();
670 CursorSlice const & i2 = cur.selEnd();
671 if (i1.inset().asMathInset()) {
672 if (i1.idx() == i2.idx()) {
673 i1.cell().erase(i1.pos(), i2.pos());
675 MathInset * p = i1.asMathInset();
676 InsetBase::row_type r1, r2;
677 InsetBase::col_type c1, c2;
678 region(i1, i2, r1, r2, c1, c2);
679 for (InsetBase::row_type row = r1; row <= r2; ++row)
680 for (InsetBase::col_type col = c1; col <= c2; ++col)
681 p->cell(p->index(row, col)).clear();
684 cur.pos() = 0; // We've deleted the whole cell. Only pos 0 is valid.
687 lyxerr << "can't erase this selection 1" << endl;
689 //lyxerr << "LCursor::eraseSelection end: " << cur << endl;
693 void selDel(LCursor & cur)
695 //lyxerr << "LCursor::selDel" << endl;
696 if (cur.selection()) {
698 cur.selection() = false;
703 void selClearOrDel(LCursor & cur)
705 //lyxerr << "LCursor::selClearOrDel" << endl;
706 if (lyxrc.auto_region_delete)
709 cur.selection() = false;
713 string grabSelection(LCursor & cur)
715 if (!cur.selection())
718 CursorSlice i1 = cur.selBegin();
719 CursorSlice i2 = cur.selEnd();
721 if (i1.idx() == i2.idx()) {
722 if (i1.inset().asMathInset()) {
723 MathArray::const_iterator it = i1.cell().begin();
724 return asString(MathArray(it + i1.pos(), it + i2.pos()));
726 return "unknown selection 1";
730 InsetBase::row_type r1, r2;
731 InsetBase::col_type c1, c2;
732 region(i1, i2, r1, r2, c1, c2);
735 if (i1.inset().asMathInset()) {
736 for (InsetBase::row_type row = r1; row <= r2; ++row) {
739 for (InsetBase::col_type col = c1; col <= c2; ++col) {
742 data += asString(i1.asMathInset()->
743 cell(i1.asMathInset()->index(row, col)));
747 data = "unknown selection 2";