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"
26 #include "insetiterator.h"
30 #include "lyxtextclasslist.h"
31 #include "paragraph.h"
32 #include "paragraph_funcs.h"
33 #include "ParagraphParameters.h"
34 #include "ParagraphList_fwd.h"
35 #include "pariterator.h"
38 #include "insets/insetcharstyle.h"
39 #include "insets/insettabular.h"
41 #include "mathed/math_data.h"
42 #include "mathed/math_inset.h"
43 #include "mathed/math_support.h"
45 #include "support/lstrings.h"
47 #include <boost/tuple/tuple.hpp>
51 using lyx::textclass_type;
53 using lyx::support::bformat;
65 typedef std::pair<lyx::pit_type, int> PitPosPair;
67 typedef limited_stack<pair<ParagraphList, textclass_type> > CutStack;
71 class resetOwnerAndChanges : public std::unary_function<Paragraph, void> {
73 void operator()(Paragraph & p) const {
80 void region(CursorSlice const & i1, CursorSlice const & i2,
81 InsetBase::row_type & r1, InsetBase::row_type & r2,
82 InsetBase::col_type & c1, InsetBase::col_type & c2)
84 InsetBase & p = i1.inset();
96 bool checkPastePossible(int index)
98 return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
102 pair<PitPosPair, pit_type>
103 pasteSelectionHelper(Buffer const & buffer, ParagraphList & pars,
104 pit_type pit, int pos,
105 textclass_type tc, size_t cut_index, ErrorList & errorlist)
107 if (!checkPastePossible(cut_index))
108 return make_pair(PitPosPair(pit, pos), pit);
110 BOOST_ASSERT (pos <= pars[pit].size());
112 // Make a copy of the CaP paragraphs.
113 ParagraphList insertion = theCuts[cut_index].first;
114 textclass_type const textclass = theCuts[cut_index].second;
116 // Now remove all out of the pars which is NOT allowed in the
117 // new environment and set also another font if that is required.
119 // Convert newline to paragraph break in ERT inset.
120 // This should not be here!
121 if (pars[pit].inInset() &&
122 pars[pit].inInset()->lyxCode() == InsetBase::ERT_CODE) {
123 for (ParagraphList::size_type i = 0; i < insertion.size(); ++i) {
124 for (pos_type j = 0; j < insertion[i].size(); ++j) {
125 if (insertion[i].isNewline(j)) {
126 insertion[i].erase(j);
127 breakParagraphConservative(
135 // Make sure there is no class difference.
136 lyx::cap::SwitchBetweenClasses(textclass, tc, insertion, errorlist);
138 ParagraphList::iterator tmpbuf = insertion.begin();
139 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
141 Paragraph::depth_type max_depth = pars[pit].getMaxDepthAfter();
143 for (; tmpbuf != insertion.end(); ++tmpbuf) {
144 // If we have a negative jump so that the depth would
145 // go below 0 depth then we have to redo the delta to
146 // this new max depth level so that subsequent
147 // paragraphs are aligned correctly to this paragraph
149 if (int(tmpbuf->params().depth()) + depth_delta < 0)
152 // Set the right depth so that we are not too deep or shallow.
153 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
154 if (tmpbuf->params().depth() > max_depth)
155 tmpbuf->params().depth(max_depth);
157 // Only set this from the 2nd on as the 2nd depends
158 // for maxDepth still on pit.
159 if (tmpbuf != insertion.begin())
160 max_depth = tmpbuf->getMaxDepthAfter();
162 // Set the inset owner of this paragraph.
163 tmpbuf->setInsetOwner(pars[pit].inInset());
164 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
165 if (tmpbuf->getChar(i) == Paragraph::META_INSET &&
166 !pars[pit].insetAllowed(tmpbuf->getInset(i)->lyxCode()))
171 bool const empty = pars[pit].empty();
173 // Make the buf exactly the same layout as the cursor
175 insertion.begin()->makeSameLayout(pars[pit]);
178 // Prepare the paragraphs and insets for insertion.
179 // A couple of insets store buffer references so need updating.
181 std::swap(in.paragraphs(), insertion);
183 ParIterator fpit = par_iterator_begin(in);
184 ParIterator fend = par_iterator_end(in);
186 for (; fpit != fend; ++fpit) {
187 InsetList::iterator lit = fpit->insetlist.begin();
188 InsetList::iterator eit = fpit->insetlist.end();
190 for (; lit != eit; ++lit) {
191 switch (lit->inset->lyxCode()) {
192 case InsetBase::TABULAR_CODE: {
193 InsetTabular * it = static_cast<InsetTabular*>(lit->inset);
203 std::swap(in.paragraphs(), insertion);
205 // Split the paragraph for inserting the buf if necessary.
207 breakParagraphConservative(buffer.params(), pars, pit, pos);
211 pars.insert(pars.begin() + pit, insertion.begin(),
214 // merge the empty par with the last par of the insertion
215 mergeParagraph(buffer.params(), pars,
216 pit + insertion.size() - 1);
218 pars.insert(pars.begin() + pit + 1, insertion.begin(),
221 // merge the first par of the insertion with the current par
222 mergeParagraph(buffer.params(), pars, pit);
225 pit_type last_paste = pit + insertion.size() - 1;
227 // Store the new cursor position.
229 pos = pars[last_paste].size();
231 // Maybe some pasting.
232 if (!empty && last_paste + 1 != pit_type(pars.size())) {
233 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
234 mergeParagraph(buffer.params(), pars, last_paste);
235 } else if (pars[last_paste + 1].empty()) {
236 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
237 mergeParagraph(buffer.params(), pars, last_paste);
238 } else if (pars[last_paste].empty()) {
239 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
240 mergeParagraph(buffer.params(), pars, last_paste);
242 pars[last_paste + 1].stripLeadingSpaces();
247 return make_pair(PitPosPair(pit, pos), last_paste + 1);
251 PitPosPair eraseSelectionHelper(BufferParams const & params,
252 ParagraphList & pars,
253 pit_type startpit, pit_type endpit,
254 int startpos, int endpos, bool doclear)
256 // Start of selection is really invalid.
257 if (startpit == pit_type(pars.size()) ||
258 (startpos > pars[startpit].size()))
259 return PitPosPair(endpit, endpos);
261 // Start and end is inside same paragraph
262 if (endpit == pit_type(pars.size()) ||
263 startpit == endpit) {
264 endpos -= pars[startpit].erase(startpos, endpos);
265 return PitPosPair(endpit, endpos);
268 bool all_erased = true;
270 // Clear fragments of the first par in selection
271 pars[startpit].erase(startpos, pars[startpit].size());
272 if (pars[startpit].size() != startpos)
275 // Clear fragments of the last par in selection
276 endpos -= pars[endpit].erase(0, endpos);
280 // Erase all the "middle" paragraphs.
281 if (params.tracking_changes) {
282 // Look through the deleted pars if any, erasing as needed
283 for (pit_type pit = startpit + 1; pit != endpit;) {
284 // "erase" the contents of the par
285 pars[pit].erase(0, pars[pit].size());
286 if (pars[pit].empty()) {
287 // remove the par if it's now empty
288 pars.erase(pars.begin() + pit);
296 pars.erase(pars.begin() + startpit + 1, pars.begin() + endpit);
297 endpit = startpit + 1;
300 #if 0 // FIXME: why for cut but not copy ?
301 // the cut selection should begin with standard layout
303 buf->params().clear();
305 buf->layout(textclasslist[buffer->params.textclass].defaultLayoutName());
309 if (startpit + 1 == pit_type(pars.size()))
310 return PitPosPair(endpit, endpos);
313 pars[startpit + 1].stripLeadingSpaces();
316 // Merge first and last paragraph, if possible
318 (pars[startpit].hasSameLayout(pars[startpit + 1]) ||
319 pars[startpit + 1].empty())) {
320 mergeParagraph(params, pars, startpit);
321 // This because endpar gets deleted here!
326 return PitPosPair(endpit, endpos);
330 void copySelectionHelper(ParagraphList & pars,
331 pit_type startpit, pit_type endpit,
332 int start, int end, textclass_type tc)
334 BOOST_ASSERT(0 <= start && start <= pars[startpit].size());
335 BOOST_ASSERT(0 <= end && end <= pars[endpit].size());
336 BOOST_ASSERT(startpit != endpit || start <= end);
338 // Clone the paragraphs within the selection.
339 ParagraphList paragraphs(pars.begin() + startpit, pars.begin() + endpit + 1);
341 for_each(paragraphs.begin(), paragraphs.end(), resetOwnerAndChanges());
343 // Cut out the end of the last paragraph.
344 Paragraph & back = paragraphs.back();
345 back.erase(end, back.size());
347 // Cut out the begin of the first paragraph
348 Paragraph & front = paragraphs.front();
349 front.erase(0, start);
351 theCuts.push(make_pair(paragraphs, tc));
362 string grabAndEraseSelection(LCursor & cur)
364 if (!cur.selection())
366 string res = grabSelection(cur);
368 cur.selection() = false;
373 void SwitchBetweenClasses(textclass_type c1, textclass_type c2,
374 ParagraphList & pars, ErrorList & errorlist)
376 BOOST_ASSERT(!pars.empty());
380 LyXTextClass const & tclass1 = textclasslist[c1];
381 LyXTextClass const & tclass2 = textclasslist[c2];
384 std::swap(in.paragraphs(), pars);
387 ParIterator end = par_iterator_end(in);
388 for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
389 string const name = it->layout()->name();
390 bool hasLayout = tclass2.hasLayout(name);
393 it->layout(tclass2[name]);
395 it->layout(tclass2.defaultLayout());
397 if (!hasLayout && name != tclass1.defaultLayoutName()) {
398 string const s = bformat(
399 _("Layout had to be changed from\n%1$s to %2$s\n"
400 "because of class conversion from\n%3$s to %4$s"),
401 name, it->layout()->name(), tclass1.name(), tclass2.name());
402 // To warn the user that something had to be done.
403 errorlist.push_back(ErrorItem(_("Changed Layout"), s,
410 InsetIterator const i_end = inset_iterator_end(in);
411 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
412 if (it->lyxCode() == InsetBase::CHARSTYLE_CODE) {
413 InsetCharStyle & inset =
414 static_cast<InsetCharStyle &>(*it);
415 string const name = inset.params().type;
416 CharStyles::iterator const found_cs =
417 tclass2.charstyle(name);
418 if (found_cs == tclass2.charstyles().end()) {
419 // The character style is undefined in tclass2
420 inset.setUndefined();
421 string const s = bformat(_(
422 "Character style %1$s is "
423 "undefined because of class "
424 "conversion from\n%2$s to %3$s"),
425 name, tclass1.name(), tclass2.name());
426 // To warn the user that something had to be done.
427 errorlist.push_back(ErrorItem(
428 _("Undefined character style"),
429 s, it.paragraph().id(),
430 it.pos(), it.pos() + 1));
431 } else if (inset.undefined()) {
432 // The character style is undefined in
433 // tclass1 and is defined in tclass2
434 inset.setDefined(found_cs);
439 std::swap(in.paragraphs(), pars);
443 std::vector<string> const availableSelections(Buffer const & buffer)
445 vector<string> selList;
447 CutStack::const_iterator cit = theCuts.begin();
448 CutStack::const_iterator end = theCuts.end();
449 for (; cit != end; ++cit) {
450 // we do not use cit-> here because gcc 2.9x does not
452 ParagraphList const & pars = (*cit).first;
454 ParagraphList::const_iterator pit = pars.begin();
455 ParagraphList::const_iterator pend = pars.end();
456 for (; pit != pend; ++pit) {
457 asciiSel += pit->asString(buffer, false);
458 if (asciiSel.size() > 25) {
459 asciiSel.replace(22, string::npos, "...");
464 selList.push_back(asciiSel);
473 return theCuts.empty() ? 0 : theCuts[0].first.size();
477 void cutSelection(LCursor & cur, bool doclear, bool realcut)
479 if (cur.inTexted()) {
480 LyXText * text = cur.text();
482 // Stuff what we got on the clipboard. Even if there is no selection.
484 // There is a problem with having the stuffing here in that the
485 // larger the selection the slower LyX will get. This can be
486 // solved by running the line below only when the selection has
487 // finished. The solution used currently just works, to make it
488 // faster we need to be more clever and probably also have more
489 // calls to stuffClipboard. (Lgb)
490 // cur.bv().stuffClipboard(cur.selectionAsString(true));
492 // This doesn't make sense, if there is no selection
493 if (!cur.selection())
496 // OK, we have a selection. This is always between cur.selBegin()
499 // make sure that the depth behind the selection are restored, too
500 recordUndoSelection(cur);
501 pit_type begpit = cur.selBegin().pit();
502 pit_type endpit = cur.selEnd().pit();
504 int endpos = cur.selEnd().pos();
506 BufferParams const & bp = cur.buffer().params();
508 copySelectionHelper(text->paragraphs(),
510 cur.selBegin().pos(), endpos,
514 boost::tie(endpit, endpos) =
515 eraseSelectionHelper(bp,
518 cur.selBegin().pos(), endpos,
521 // sometimes necessary
523 text->paragraphs()[begpit].stripLeadingSpaces();
525 // cutSelection can invalidate the cursor so we need to set
527 // we prefer the end for when tracking changes
531 // need a valid cursor. (Lgb)
532 cur.clearSelection();
533 updateCounters(cur.buffer());
536 if (cur.inMathed()) {
537 lyxerr << "cutSelection in mathed" << endl;
540 cur.selection() = false;
546 void copySelection(LCursor & cur)
548 // stuff the selection onto the X clipboard, from an explicit copy request
549 cur.bv().stuffClipboard(cur.selectionAsString(true));
551 // this doesn't make sense, if there is no selection
552 if (!cur.selection())
555 if (cur.inTexted()) {
556 LyXText * text = cur.text();
558 // ok we have a selection. This is always between cur.selBegin()
559 // and sel_end cursor
561 // copy behind a space if there is one
562 ParagraphList & pars = text->paragraphs();
563 pos_type pos = cur.selBegin().pos();
564 pit_type par = cur.selBegin().pit();
565 while (pos < pars[par].size()
566 && pars[par].isLineSeparator(pos)
567 && (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
570 copySelectionHelper(pars, par, cur.selEnd().pit(),
571 pos, cur.selEnd().pos(), cur.buffer().params().textclass);
574 if (cur.inMathed()) {
575 lyxerr << "copySelection in mathed" << endl;
577 pars.push_back(Paragraph());
578 BufferParams const & bp = cur.buffer().params();
579 pars.back().layout(bp.getLyXTextClass().defaultLayout());
580 for_each(pars.begin(), pars.end(), resetOwnerAndChanges());
581 pars.back().insert(0, grabSelection(cur), LyXFont());
582 theCuts.push(make_pair(pars, bp.textclass));
587 std::string getSelection(Buffer const & buf, size_t sel_index)
589 return sel_index < theCuts.size()
590 ? theCuts[sel_index].first.back().asString(buf, false)
595 void pasteSelection(LCursor & cur, size_t sel_index)
597 // this does not make sense, if there is nothing to paste
598 lyxerr << "#### pasteSelection " << sel_index << endl;
599 if (!checkPastePossible(sel_index))
602 if (cur.inTexted()) {
603 LyXText * text = cur.text();
613 boost::tie(ppp, endpit) =
614 pasteSelectionHelper(cur.buffer(),
616 cur.pit(), cur.pos(),
617 cur.buffer().params().textclass,
619 bufferErrors(cur.buffer(), el);
620 cur.bv().showErrorList(_("Paste"));
622 cur.clearSelection();
624 text->setCursor(cur, ppp.first, ppp.second);
626 updateCounters(cur.buffer());
629 if (cur.inMathed()) {
630 lyxerr << "### should be handled in MathNest/GridInset" << endl;
635 void setSelectionRange(LCursor & cur, pos_type length)
637 LyXText * text = cur.text();
643 text->cursorRight(cur);
648 // simple replacing. The font of the first selected character is used
649 void replaceSelectionWithString(LCursor & cur, string const & str)
651 LyXText * text = cur.text();
655 // Get font setting before we cut
656 pos_type pos = cur.selEnd().pos();
657 Paragraph & par = text->getPar(cur.selEnd().pit());
659 par.getFontSettings(cur.buffer().params(), cur.selBegin().pos());
661 // Insert the new string
662 string::const_iterator cit = str.begin();
663 string::const_iterator end = str.end();
664 for (; cit != end; ++cit, ++pos)
665 par.insertChar(pos, (*cit), font);
668 cutSelection(cur, true, false);
672 void replaceSelection(LCursor & cur)
675 cutSelection(cur, true, false);
679 // only used by the spellchecker
680 void replaceWord(LCursor & cur, string const & replacestring)
682 LyXText * text = cur.text();
685 replaceSelectionWithString(cur, replacestring);
686 setSelectionRange(cur, replacestring.length());
688 // Go back so that replacement string is also spellchecked
689 for (string::size_type i = 0; i < replacestring.length() + 1; ++i)
690 text->cursorLeft(cur);
694 void eraseSelection(LCursor & cur)
696 //lyxerr << "LCursor::eraseSelection begin: " << cur << endl;
697 CursorSlice const & i1 = cur.selBegin();
698 CursorSlice const & i2 = cur.selEnd();
699 if (i1.inset().asMathInset()) {
701 if (i1.idx() == i2.idx()) {
702 i1.cell().erase(i1.pos(), i2.pos());
704 MathInset * p = i1.asMathInset();
705 InsetBase::row_type r1, r2;
706 InsetBase::col_type c1, c2;
707 region(i1, i2, r1, r2, c1, c2);
708 for (InsetBase::row_type row = r1; row <= r2; ++row)
709 for (InsetBase::col_type col = c1; col <= c2; ++col)
710 p->cell(p->index(row, col)).clear();
711 // We've deleted the whole cell. Only pos 0 is valid.
716 lyxerr << "can't erase this selection 1" << endl;
718 //lyxerr << "LCursor::eraseSelection end: " << cur << endl;
722 void selDel(LCursor & cur)
724 //lyxerr << "LCursor::selDel" << endl;
725 if (cur.selection()) {
727 cur.selection() = false;
732 void selClearOrDel(LCursor & cur)
734 //lyxerr << "LCursor::selClearOrDel" << endl;
735 if (lyxrc.auto_region_delete)
738 cur.selection() = false;
742 string grabSelection(LCursor & cur)
744 if (!cur.selection())
747 CursorSlice i1 = cur.selBegin();
748 CursorSlice i2 = cur.selEnd();
750 if (i1.idx() == i2.idx()) {
751 if (i1.inset().asMathInset()) {
752 MathArray::const_iterator it = i1.cell().begin();
753 return asString(MathArray(it + i1.pos(), it + i2.pos()));
755 return "unknown selection 1";
759 InsetBase::row_type r1, r2;
760 InsetBase::col_type c1, c2;
761 region(i1, i2, r1, r2, c1, c2);
764 if (i1.inset().asMathInset()) {
765 for (InsetBase::row_type row = r1; row <= r2; ++row) {
768 for (InsetBase::col_type col = c1; col <= c2; ++col) {
771 data += asString(i1.asMathInset()->
772 cell(i1.asMathInset()->index(row, col)));
776 data = "unknown selection 2";