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 // Make sure there is no class difference.
118 lyx::cap::SwitchLayoutsBetweenClasses(textclass, tc, insertion,
121 ParagraphList::iterator tmpbuf = insertion.begin();
122 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
124 Paragraph::depth_type max_depth = pars[pit].getMaxDepthAfter();
126 for (; tmpbuf != insertion.end(); ++tmpbuf) {
127 // If we have a negative jump so that the depth would
128 // go below 0 depth then we have to redo the delta to
129 // this new max depth level so that subsequent
130 // paragraphs are aligned correctly to this paragraph
132 if (int(tmpbuf->params().depth()) + depth_delta < 0)
135 // Set the right depth so that we are not too deep or shallow.
136 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
137 if (tmpbuf->params().depth() > max_depth)
138 tmpbuf->params().depth(max_depth);
140 // Only set this from the 2nd on as the 2nd depends
141 // for maxDepth still on pit.
142 if (tmpbuf != insertion.begin())
143 max_depth = tmpbuf->getMaxDepthAfter();
145 // Set the inset owner of this paragraph.
146 tmpbuf->setInsetOwner(pars[pit].inInset());
147 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
148 if (tmpbuf->getChar(i) == Paragraph::META_INSET) {
149 if (!pars[pit].insetAllowed(tmpbuf->getInset(i)->lyxCode()))
155 bool const empty = pars[pit].empty();
157 // Make the buf exactly the same layout as the cursor
159 insertion.begin()->makeSameLayout(pars[pit]);
162 // Prepare the paragraphs and insets for insertion.
163 // A couple of insets store buffer references so need updating.
165 std::swap(in.paragraphs(), insertion);
167 ParIterator fpit = par_iterator_begin(in);
168 ParIterator fend = par_iterator_end(in);
170 for (; fpit != fend; ++fpit) {
171 InsetList::iterator lit = fpit->insetlist.begin();
172 InsetList::iterator eit = fpit->insetlist.end();
174 for (; lit != eit; ++lit) {
175 switch (lit->inset->lyxCode()) {
176 case InsetBase::TABULAR_CODE: {
177 InsetTabular * it = static_cast<InsetTabular*>(lit->inset);
187 std::swap(in.paragraphs(), insertion);
189 // Split the paragraph for inserting the buf if necessary.
191 breakParagraphConservative(buffer.params(), pars, pit, pos);
195 pars.insert(pars.begin() + pit, insertion.begin(),
198 // merge the empty par with the last par of the insertion
199 mergeParagraph(buffer.params(), pars,
200 pit + insertion.size() - 1);
202 pars.insert(pars.begin() + pit + 1, insertion.begin(),
205 // merge the first par of the insertion with the current par
206 mergeParagraph(buffer.params(), pars, pit);
209 pit_type last_paste = pit + insertion.size() - 1;
211 // Store the new cursor position.
213 pos = pars[last_paste].size();
215 // Maybe some pasting.
216 if (!empty && last_paste + 1 != pit_type(pars.size())) {
217 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
218 mergeParagraph(buffer.params(), pars, last_paste);
219 } else if (pars[last_paste + 1].empty()) {
220 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
221 mergeParagraph(buffer.params(), pars, last_paste);
222 } else if (pars[last_paste].empty()) {
223 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
224 mergeParagraph(buffer.params(), pars, last_paste);
226 pars[last_paste + 1].stripLeadingSpaces();
231 return make_pair(PitPosPair(pit, pos), last_paste + 1);
235 PitPosPair eraseSelectionHelper(BufferParams const & params,
236 ParagraphList & pars,
237 pit_type startpit, pit_type endpit,
238 int startpos, int endpos, bool doclear)
240 if (startpit == pit_type(pars.size()) ||
241 (startpos > pars[startpit].size()))
242 return PitPosPair(endpit, endpos);
244 if (endpit == pit_type(pars.size()) ||
245 startpit == endpit) {
246 endpos -= pars[startpit].erase(startpos, endpos);
247 return PitPosPair(endpit, endpos);
250 // clear end/begin fragments of the first/last par in selection
251 bool all_erased = true;
253 pars[startpit].erase(startpos, pars[startpit].size());
254 if (pars[startpit].size() != startpos)
257 endpos -= pars[endpit].erase(0, endpos);
261 // Loop through the deleted pars if any, erasing as needed
262 for (pit_type pit = startpit + 1; pit != endpit;) {
263 // "erase" the contents of the par
264 pars[pit].erase(0, pars[pit].size());
265 if (!pars[pit].size()) {
266 // remove the par if it's now empty
267 pars.erase(pars.begin() + pit);
275 #if 0 // FIXME: why for cut but not copy ?
276 // the cut selection should begin with standard layout
278 buf->params().clear();
280 buf->layout(textclasslist[buffer->params.textclass].defaultLayoutName());
284 if (startpit + 1 == pit_type(pars.size()))
285 return PitPosPair(endpit, endpos);
288 pars[startpit + 1].stripLeadingSpaces();
291 // paste the paragraphs again, if possible
293 (pars[startpit].hasSameLayout(pars[startpit + 1]) ||
294 pars[startpit + 1].empty())) {
295 mergeParagraph(params, pars, startpit);
296 // this because endpar gets deleted here!
301 return PitPosPair(endpit, endpos);
306 void copySelectionHelper(ParagraphList & pars,
307 pit_type startpit, pit_type endpit,
308 int start, int end, textclass_type tc)
310 BOOST_ASSERT(0 <= start && start <= pars[startpit].size());
311 BOOST_ASSERT(0 <= end && end <= pars[endpit].size());
312 BOOST_ASSERT(startpit != endpit || start <= end);
314 // Clone the paragraphs within the selection.
315 ParagraphList paragraphs(pars.begin() + startpit, pars.begin() + endpit + 1);
316 for_each(paragraphs.begin(), paragraphs.end(), resetOwnerAndChanges());
318 // Cut out the end of the last paragraph.
319 Paragraph & back = paragraphs.back();
320 back.erase(end, back.size());
322 // Cut out the begin of the first paragraph
323 Paragraph & front = paragraphs.front();
324 front.erase(0, start);
326 theCuts.push(make_pair(paragraphs, tc));
331 PitPosPair cutSelectionHelper(BufferParams const & params,
332 ParagraphList & pars, pit_type startpit, pit_type endpit,
333 int startpos, int endpos, textclass_type tc, bool doclear)
335 copySelectionHelper(pars, startpit, endpit, startpos, endpos, tc);
336 return eraseSelectionHelper(params, pars, startpit, endpit,
337 startpos, endpos, doclear);
349 string grabAndEraseSelection(LCursor & cur)
351 if (!cur.selection())
353 string res = grabSelection(cur);
355 cur.selection() = false;
360 int SwitchLayoutsBetweenClasses(textclass_type c1, textclass_type c2,
361 ParagraphList & pars, ErrorList & errorlist)
363 BOOST_ASSERT(!pars.empty());
368 LyXTextClass const & tclass1 = textclasslist[c1];
369 LyXTextClass const & tclass2 = textclasslist[c2];
372 std::swap(in.paragraphs(), pars);
374 ParIterator end = par_iterator_end(in);
375 for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
376 string const name = it->layout()->name();
377 bool hasLayout = tclass2.hasLayout(name);
380 it->layout(tclass2[name]);
382 it->layout(tclass2.defaultLayout());
384 if (!hasLayout && name != tclass1.defaultLayoutName()) {
386 string const s = bformat(
387 _("Layout had to be changed from\n%1$s to %2$s\n"
388 "because of class conversion from\n%3$s to %4$s"),
389 name, it->layout()->name(), tclass1.name(), tclass2.name());
390 // To warn the user that something had to be done.
391 errorlist.push_back(ErrorItem("Changed Layout", s,
396 std::swap(in.paragraphs(), pars);
401 std::vector<string> const availableSelections(Buffer const & buffer)
403 vector<string> selList;
405 CutStack::const_iterator cit = theCuts.begin();
406 CutStack::const_iterator end = theCuts.end();
407 for (; cit != end; ++cit) {
408 // we do not use cit-> here because gcc 2.9x does not
410 ParagraphList const & pars = (*cit).first;
412 ParagraphList::const_iterator pit = pars.begin();
413 ParagraphList::const_iterator pend = pars.end();
414 for (; pit != pend; ++pit) {
415 asciiSel += pit->asString(buffer, false);
416 if (asciiSel.size() > 25) {
417 asciiSel.replace(22, string::npos, "...");
422 selList.push_back(asciiSel);
431 return theCuts.empty() ? 0 : theCuts[0].first.size();
435 void cutSelection(LCursor & cur, bool doclear, bool realcut)
437 if (cur.inTexted()) {
438 LyXText * text = cur.text();
440 // Stuff what we got on the clipboard. Even if there is no selection.
442 // There is a problem with having the stuffing here in that the
443 // larger the selection the slower LyX will get. This can be
444 // solved by running the line below only when the selection has
445 // finished. The solution used currently just works, to make it
446 // faster we need to be more clever and probably also have more
447 // calls to stuffClipboard. (Lgb)
448 cur.bv().stuffClipboard(cur.selectionAsString(true));
450 // This doesn't make sense, if there is no selection
451 if (!cur.selection())
454 // OK, we have a selection. This is always between cur.selBegin()
457 // make sure that the depth behind the selection are restored, too
458 recordUndoSelection(cur);
459 pit_type begpit = cur.selBegin().pit();
460 pit_type endpit = cur.selEnd().pit();
462 int endpos = cur.selEnd().pos();
464 BufferParams const & bp = cur.buffer().params();
466 copySelectionHelper(text->paragraphs(),
468 cur.selBegin().pos(), endpos,
472 boost::tie(endpit, endpos) =
473 eraseSelectionHelper(bp,
476 cur.selBegin().pos(), endpos,
479 // sometimes necessary
481 text->paragraphs()[begpit].stripLeadingSpaces();
483 // cutSelection can invalidate the cursor so we need to set
485 // we prefer the end for when tracking changes
489 // need a valid cursor. (Lgb)
490 cur.clearSelection();
491 text->updateCounters();
494 if (cur.inMathed()) {
495 lyxerr << "cutSelection in mathed" << endl;
498 cur.selection() = false;
504 void copySelection(LCursor & cur)
506 // stuff the selection onto the X clipboard, from an explicit copy request
507 cur.bv().stuffClipboard(cur.selectionAsString(true));
509 // this doesn't make sense, if there is no selection
510 if (!cur.selection())
513 if (cur.inTexted()) {
514 LyXText * text = cur.text();
516 // ok we have a selection. This is always between cur.selBegin()
517 // and sel_end cursor
519 // copy behind a space if there is one
520 ParagraphList & pars = text->paragraphs();
521 pos_type pos = cur.selBegin().pos();
522 pit_type par = cur.selBegin().pit();
523 while (pos < pars[par].size()
524 && pars[par].isLineSeparator(pos)
525 && (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
528 copySelectionHelper(pars, par, cur.selEnd().pit(),
529 pos, cur.selEnd().pos(), cur.buffer().params().textclass);
532 if (cur.inMathed()) {
533 lyxerr << "copySelection in mathed" << endl;
535 pars.push_back(Paragraph());
536 BufferParams const & bp = cur.buffer().params();
537 pars.back().layout(bp.getLyXTextClass().defaultLayout());
538 for_each(pars.begin(), pars.end(), resetOwnerAndChanges());
539 pars.back().insert(0, grabSelection(cur), LyXFont());
540 theCuts.push(make_pair(pars, bp.textclass));
545 std::string getSelection(Buffer const & buf, size_t sel_index)
547 return sel_index < theCuts.size()
548 ? theCuts[sel_index].first.back().asString(buf, false)
553 void pasteSelection(LCursor & cur, size_t sel_index)
555 // this does not make sense, if there is nothing to paste
556 lyxerr << "#### pasteSelection " << sel_index << endl;
557 if (!checkPastePossible(sel_index))
560 if (cur.inTexted()) {
561 LyXText * text = cur.text();
571 boost::tie(ppp, endpit) =
572 pasteSelectionHelper(cur.buffer(),
574 cur.pit(), cur.pos(),
575 cur.buffer().params().textclass,
577 bufferErrors(cur.buffer(), el);
578 cur.bv().showErrorList(_("Paste"));
580 cur.clearSelection();
582 text->setCursor(cur, ppp.first, ppp.second);
584 text->updateCounters();
587 if (cur.inMathed()) {
588 lyxerr << "### should be handled in MathNest/GridInset" << endl;
593 void setSelectionRange(LCursor & cur, pos_type length)
595 LyXText * text = cur.text();
601 text->cursorRight(cur);
606 // simple replacing. The font of the first selected character is used
607 void replaceSelectionWithString(LCursor & cur, string const & str)
609 LyXText * text = cur.text();
613 // Get font setting before we cut
614 pos_type pos = cur.selEnd().pos();
615 Paragraph & par = text->getPar(cur.selEnd().pit());
617 par.getFontSettings(cur.buffer().params(), cur.selBegin().pos());
619 // Insert the new string
620 string::const_iterator cit = str.begin();
621 string::const_iterator end = str.end();
622 for (; cit != end; ++cit, ++pos)
623 par.insertChar(pos, (*cit), font);
626 cutSelection(cur, true, false);
630 void replaceSelection(LCursor & cur)
633 cutSelection(cur, true, false);
637 // only used by the spellchecker
638 void replaceWord(LCursor & cur, string const & replacestring)
640 LyXText * text = cur.text();
643 replaceSelectionWithString(cur, replacestring);
644 setSelectionRange(cur, replacestring.length());
646 // Go back so that replacement string is also spellchecked
647 for (string::size_type i = 0; i < replacestring.length() + 1; ++i)
648 text->cursorLeft(cur);
652 void eraseSelection(LCursor & cur)
654 //lyxerr << "LCursor::eraseSelection begin: " << cur << endl;
655 CursorSlice const & i1 = cur.selBegin();
656 CursorSlice const & i2 = cur.selEnd();
657 if (i1.inset().asMathInset()) {
658 if (i1.idx() == i2.idx()) {
659 i1.cell().erase(i1.pos(), i2.pos());
661 MathInset * p = i1.asMathInset();
662 InsetBase::row_type r1, r2;
663 InsetBase::col_type c1, c2;
664 region(i1, i2, r1, r2, c1, c2);
665 for (InsetBase::row_type row = r1; row <= r2; ++row)
666 for (InsetBase::col_type col = c1; col <= c2; ++col)
667 p->cell(p->index(row, col)).clear();
670 cur.pos() = 0; // We've deleted the whole cell. Only pos 0 is valid.
673 lyxerr << "can't erase this selection 1" << endl;
675 //lyxerr << "LCursor::eraseSelection end: " << cur << endl;
679 void selDel(LCursor & cur)
681 //lyxerr << "LCursor::selDel" << endl;
682 if (cur.selection()) {
684 cur.selection() = false;
689 void selClearOrDel(LCursor & cur)
691 //lyxerr << "LCursor::selClearOrDel" << endl;
692 if (lyxrc.auto_region_delete)
695 cur.selection() = false;
699 string grabSelection(LCursor & cur)
701 if (!cur.selection())
704 CursorSlice i1 = cur.selBegin();
705 CursorSlice i2 = cur.selEnd();
707 if (i1.idx() == i2.idx()) {
708 if (i1.inset().asMathInset()) {
709 MathArray::const_iterator it = i1.cell().begin();
710 return asString(MathArray(it + i1.pos(), it + i2.pos()));
712 return "unknown selection 1";
716 InsetBase::row_type r1, r2;
717 InsetBase::col_type c1, c2;
718 region(i1, i2, r1, r2, c1, c2);
721 if (i1.inset().asMathInset()) {
722 for (InsetBase::row_type row = r1; row <= r2; ++row) {
725 for (InsetBase::col_type col = c1; col <= c2; ++col) {
728 data += asString(i1.asMathInset()->
729 cell(i1.asMathInset()->index(row, col)));
733 data = "unknown selection 2";