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 // store whether the tabular stack is newer than the normal copy stack
72 // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
73 // when we (hopefully) have a one-for-all paste mechanism.
74 bool dirty_tabular_stack_;
76 class resetOwnerAndChanges : public std::unary_function<Paragraph, void> {
78 void operator()(Paragraph & p) const {
85 void region(CursorSlice const & i1, CursorSlice const & i2,
86 InsetBase::row_type & r1, InsetBase::row_type & r2,
87 InsetBase::col_type & c1, InsetBase::col_type & c2)
89 InsetBase & p = i1.inset();
101 bool checkPastePossible(int index)
103 return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
107 pair<PitPosPair, pit_type>
108 pasteSelectionHelper(Buffer const & buffer,
109 ParagraphList & pars, pit_type pit, int pos,
110 ParagraphList const & parlist, textclass_type textclass,
111 ErrorList & errorlist)
114 return make_pair(PitPosPair(pit, pos), pit);
116 BOOST_ASSERT (pos <= pars[pit].size());
118 // Make a copy of the CaP paragraphs.
119 ParagraphList insertion = parlist;
120 textclass_type const tc = buffer.params().textclass;
122 // Now remove all out of the pars which is NOT allowed in the
123 // new environment and set also another font if that is required.
125 // Convert newline to paragraph break in ERT inset.
126 // This should not be here!
127 if (pars[pit].inInset() &&
128 pars[pit].inInset()->lyxCode() == InsetBase::ERT_CODE) {
129 for (ParagraphList::size_type i = 0; i < insertion.size(); ++i) {
130 for (pos_type j = 0; j < insertion[i].size(); ++j) {
131 if (insertion[i].isNewline(j)) {
132 insertion[i].erase(j);
133 breakParagraphConservative(
141 // Make sure there is no class difference.
142 lyx::cap::SwitchBetweenClasses(textclass, tc, insertion, errorlist);
144 ParagraphList::iterator tmpbuf = insertion.begin();
145 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
147 Paragraph::depth_type max_depth = pars[pit].getMaxDepthAfter();
149 for (; tmpbuf != insertion.end(); ++tmpbuf) {
150 // If we have a negative jump so that the depth would
151 // go below 0 depth then we have to redo the delta to
152 // this new max depth level so that subsequent
153 // paragraphs are aligned correctly to this paragraph
155 if (int(tmpbuf->params().depth()) + depth_delta < 0)
158 // Set the right depth so that we are not too deep or shallow.
159 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
160 if (tmpbuf->params().depth() > max_depth)
161 tmpbuf->params().depth(max_depth);
163 // Only set this from the 2nd on as the 2nd depends
164 // for maxDepth still on pit.
165 if (tmpbuf != insertion.begin())
166 max_depth = tmpbuf->getMaxDepthAfter();
168 // Set the inset owner of this paragraph.
169 tmpbuf->setInsetOwner(pars[pit].inInset());
170 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
171 if (tmpbuf->getChar(i) == Paragraph::META_INSET &&
172 !pars[pit].insetAllowed(tmpbuf->getInset(i)->lyxCode()))
177 bool const empty = pars[pit].empty();
179 // Make the buf exactly the same layout as the cursor
181 insertion.begin()->makeSameLayout(pars[pit]);
184 // Prepare the paragraphs and insets for insertion.
185 // A couple of insets store buffer references so need updating.
187 std::swap(in.paragraphs(), insertion);
189 ParIterator fpit = par_iterator_begin(in);
190 ParIterator fend = par_iterator_end(in);
192 for (; fpit != fend; ++fpit) {
193 InsetList::iterator lit = fpit->insetlist.begin();
194 InsetList::iterator eit = fpit->insetlist.end();
196 for (; lit != eit; ++lit) {
197 switch (lit->inset->lyxCode()) {
198 case InsetBase::TABULAR_CODE: {
199 InsetTabular * it = static_cast<InsetTabular*>(lit->inset);
209 std::swap(in.paragraphs(), insertion);
211 // Split the paragraph for inserting the buf if necessary.
213 breakParagraphConservative(buffer.params(), pars, pit, pos);
217 pars.insert(pars.begin() + pit, insertion.begin(),
220 // merge the empty par with the last par of the insertion
221 mergeParagraph(buffer.params(), pars,
222 pit + insertion.size() - 1);
224 pars.insert(pars.begin() + pit + 1, insertion.begin(),
227 // merge the first par of the insertion with the current par
228 mergeParagraph(buffer.params(), pars, pit);
231 pit_type last_paste = pit + insertion.size() - 1;
233 // Store the new cursor position.
235 pos = pars[last_paste].size();
237 // Maybe some pasting.
238 if (!empty && last_paste + 1 != pit_type(pars.size())) {
239 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
240 mergeParagraph(buffer.params(), pars, last_paste);
241 } else if (pars[last_paste + 1].empty()) {
242 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
243 mergeParagraph(buffer.params(), pars, last_paste);
244 } else if (pars[last_paste].empty()) {
245 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
246 mergeParagraph(buffer.params(), pars, last_paste);
248 pars[last_paste + 1].stripLeadingSpaces();
253 return make_pair(PitPosPair(pit, pos), last_paste + 1);
257 PitPosPair eraseSelectionHelper(BufferParams const & params,
258 ParagraphList & pars,
259 pit_type startpit, pit_type endpit,
260 int startpos, int endpos, bool doclear)
262 // Start of selection is really invalid.
263 if (startpit == pit_type(pars.size()) ||
264 (startpos > pars[startpit].size()))
265 return PitPosPair(endpit, endpos);
267 // Start and end is inside same paragraph
268 if (endpit == pit_type(pars.size()) ||
269 startpit == endpit) {
270 endpos -= pars[startpit].erase(startpos, endpos);
271 return PitPosPair(endpit, endpos);
274 // A paragraph break has to be physically removed by merging, but
275 // only if either (1) change tracking is off, or (2) the para break
277 for (pit_type pit = startpit; pit != endpit + 1;) {
278 bool const merge = !params.tracking_changes ||
279 pars[pit].lookupChange(pars[pit].size()) ==
281 pos_type const left = ( pit == startpit ? startpos : 0 );
282 pos_type const right = ( pit == endpit ? endpos :
283 pars[pit].size() + 1 );
284 // Logical erase only:
285 pars[pit].erase(left, right);
286 // Separate handling of para break:
287 if (merge && pit != endpit &&
288 pars[pit].hasSameLayout(pars[pit + 1])) {
289 pos_type const thissize = pars[pit].size();
291 pars[pit + 1].stripLeadingSpaces();
292 mergeParagraph(params, pars, pit);
300 // Ensure legal cursor pos:
303 return PitPosPair(endpit, endpos);
307 void copySelectionHelper(ParagraphList & pars,
308 pit_type startpit, pit_type endpit,
309 int start, int end, textclass_type tc)
311 BOOST_ASSERT(0 <= start && start <= pars[startpit].size());
312 BOOST_ASSERT(0 <= end && end <= pars[endpit].size());
313 BOOST_ASSERT(startpit != endpit || start <= end);
315 // Clone the paragraphs within the selection.
316 ParagraphList paragraphs(pars.begin() + startpit, pars.begin() + endpit + 1);
318 for_each(paragraphs.begin(), paragraphs.end(), resetOwnerAndChanges());
320 // Cut out the end of the last paragraph.
321 Paragraph & back = paragraphs.back();
322 back.erase(end, back.size());
324 // Cut out the begin of the first paragraph
325 Paragraph & front = paragraphs.front();
326 front.erase(0, start);
328 theCuts.push(make_pair(paragraphs, tc));
339 string grabAndEraseSelection(LCursor & cur)
341 if (!cur.selection())
343 string res = grabSelection(cur);
349 void SwitchBetweenClasses(textclass_type c1, textclass_type c2,
350 ParagraphList & pars, ErrorList & errorlist)
352 BOOST_ASSERT(!pars.empty());
356 LyXTextClass const & tclass1 = textclasslist[c1];
357 LyXTextClass const & tclass2 = textclasslist[c2];
360 std::swap(in.paragraphs(), pars);
363 ParIterator end = par_iterator_end(in);
364 for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
365 string const name = it->layout()->name();
366 bool hasLayout = tclass2.hasLayout(name);
369 it->layout(tclass2[name]);
371 it->layout(tclass2.defaultLayout());
373 if (!hasLayout && name != tclass1.defaultLayoutName()) {
374 string const s = bformat(
375 _("Layout had to be changed from\n%1$s to %2$s\n"
376 "because of class conversion from\n%3$s to %4$s"),
377 name, it->layout()->name(), tclass1.name(), tclass2.name());
378 // To warn the user that something had to be done.
379 errorlist.push_back(ErrorItem(_("Changed Layout"), s,
386 InsetIterator const i_end = inset_iterator_end(in);
387 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
388 if (it->lyxCode() == InsetBase::CHARSTYLE_CODE) {
389 InsetCharStyle & inset =
390 static_cast<InsetCharStyle &>(*it);
391 string const name = inset.params().type;
392 CharStyles::iterator const found_cs =
393 tclass2.charstyle(name);
394 if (found_cs == tclass2.charstyles().end()) {
395 // The character style is undefined in tclass2
396 inset.setUndefined();
397 string const s = bformat(_(
398 "Character style %1$s is "
399 "undefined because of class "
400 "conversion from\n%2$s to %3$s"),
401 name, tclass1.name(), tclass2.name());
402 // To warn the user that something had to be done.
403 errorlist.push_back(ErrorItem(
404 _("Undefined character style"),
405 s, it.paragraph().id(),
406 it.pos(), it.pos() + 1));
407 } else if (inset.undefined()) {
408 // The character style is undefined in
409 // tclass1 and is defined in tclass2
410 inset.setDefined(found_cs);
415 std::swap(in.paragraphs(), pars);
419 std::vector<string> const availableSelections(Buffer const & buffer)
421 vector<string> selList;
423 CutStack::const_iterator cit = theCuts.begin();
424 CutStack::const_iterator end = theCuts.end();
425 for (; cit != end; ++cit) {
426 // we do not use cit-> here because gcc 2.9x does not
428 ParagraphList const & pars = (*cit).first;
430 ParagraphList::const_iterator pit = pars.begin();
431 ParagraphList::const_iterator pend = pars.end();
432 for (; pit != pend; ++pit) {
433 asciiSel += pit->asString(buffer, false);
434 if (asciiSel.size() > 25) {
435 asciiSel.replace(22, string::npos, "...");
440 selList.push_back(asciiSel);
447 lyx::size_type numberOfSelections()
449 return theCuts.size();
453 void cutSelection(LCursor & cur, bool doclear, bool realcut)
455 // This doesn't make sense, if there is no selection
456 if (!cur.selection())
459 // OK, we have a selection. This is always between cur.selBegin()
462 if (cur.inTexted()) {
463 LyXText * text = cur.text();
465 // Stuff what we got on the clipboard. Even if there is no selection.
467 // There is a problem with having the stuffing here in that the
468 // larger the selection the slower LyX will get. This can be
469 // solved by running the line below only when the selection has
470 // finished. The solution used currently just works, to make it
471 // faster we need to be more clever and probably also have more
472 // calls to stuffClipboard. (Lgb)
473 // cur.bv().stuffClipboard(cur.selectionAsString(true));
475 // make sure that the depth behind the selection are restored, too
476 recordUndoSelection(cur);
477 pit_type begpit = cur.selBegin().pit();
478 pit_type endpit = cur.selEnd().pit();
480 int endpos = cur.selEnd().pos();
482 BufferParams const & bp = cur.buffer().params();
484 copySelectionHelper(text->paragraphs(),
486 cur.selBegin().pos(), endpos,
490 boost::tie(endpit, endpos) =
491 eraseSelectionHelper(bp,
494 cur.selBegin().pos(), endpos,
497 // sometimes necessary
499 text->paragraphs()[begpit].stripLeadingSpaces();
501 // cutSelection can invalidate the cursor so we need to set
503 // we prefer the end for when tracking changes
507 // need a valid cursor. (Lgb)
508 cur.clearSelection();
509 updateCounters(cur.buffer());
511 // tell tabular that a recent copy happened
512 dirtyTabularStack(false);
515 if (cur.inMathed()) {
516 if (cur.selBegin().idx() != cur.selEnd().idx()) {
517 // The current selection spans more than one cell.
519 recordUndoInset(cur);
521 // Record only the current cell to avoid a jumping
532 void copySelection(LCursor & cur)
534 // stuff the selection onto the X clipboard, from an explicit copy request
535 cur.bv().stuffClipboard(cur.selectionAsString(true));
537 // this doesn't make sense, if there is no selection
538 if (!cur.selection())
541 if (cur.inTexted()) {
542 LyXText * text = cur.text();
544 // ok we have a selection. This is always between cur.selBegin()
545 // and sel_end cursor
547 // copy behind a space if there is one
548 ParagraphList & pars = text->paragraphs();
549 pos_type pos = cur.selBegin().pos();
550 pit_type par = cur.selBegin().pit();
551 while (pos < pars[par].size()
552 && pars[par].isLineSeparator(pos)
553 && (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
556 copySelectionHelper(pars, par, cur.selEnd().pit(),
557 pos, cur.selEnd().pos(), cur.buffer().params().textclass);
560 if (cur.inMathed()) {
561 lyxerr << "copySelection in mathed" << endl;
563 pars.push_back(Paragraph());
564 BufferParams const & bp = cur.buffer().params();
565 pars.back().layout(bp.getLyXTextClass().defaultLayout());
566 for_each(pars.begin(), pars.end(), resetOwnerAndChanges());
567 pars.back().insert(0, grabSelection(cur), LyXFont());
568 theCuts.push(make_pair(pars, bp.textclass));
570 // tell tabular that a recent copy happened
571 dirtyTabularStack(false);
575 std::string getSelection(Buffer const & buf, size_t sel_index)
577 return sel_index < theCuts.size()
578 ? theCuts[sel_index].first.back().asString(buf, false)
583 void pasteParagraphList(LCursor & cur, ParagraphList const & parlist,
584 textclass_type textclass)
586 if (cur.inTexted()) {
587 LyXText * text = cur.text();
596 boost::tie(ppp, endpit) =
597 pasteSelectionHelper(cur.buffer(),
599 cur.pit(), cur.pos(),
602 bufferErrors(cur.buffer(), el);
603 updateCounters(cur.buffer());
604 cur.clearSelection();
605 text->setCursor(cur, ppp.first, ppp.second);
608 // mathed is handled in MathNestInset/MathGridInset
609 BOOST_ASSERT(!cur.inMathed());
613 void pasteSelection(LCursor & cur, size_t sel_index)
615 // this does not make sense, if there is nothing to paste
616 if (!checkPastePossible(sel_index))
619 pasteParagraphList(cur, theCuts[sel_index].first,
620 theCuts[sel_index].second);
621 cur.bv().showErrorList(_("Paste"));
626 void setSelectionRange(LCursor & cur, pos_type length)
628 LyXText * text = cur.text();
634 text->cursorRight(cur);
639 // simple replacing. The font of the first selected character is used
640 void replaceSelectionWithString(LCursor & cur, string const & str)
642 LyXText * text = cur.text();
646 // Get font setting before we cut
647 pos_type pos = cur.selEnd().pos();
648 Paragraph & par = text->getPar(cur.selEnd().pit());
650 par.getFontSettings(cur.buffer().params(), cur.selBegin().pos());
652 // Insert the new string
653 string::const_iterator cit = str.begin();
654 string::const_iterator end = str.end();
655 for (; cit != end; ++cit, ++pos)
656 par.insertChar(pos, (*cit), font);
659 cutSelection(cur, true, false);
663 void replaceSelection(LCursor & cur)
666 cutSelection(cur, true, false);
670 // only used by the spellchecker
671 void replaceWord(LCursor & cur, string const & replacestring)
673 LyXText * text = cur.text();
676 replaceSelectionWithString(cur, replacestring);
677 setSelectionRange(cur, replacestring.length());
679 // Go back so that replacement string is also spellchecked
680 for (string::size_type i = 0; i < replacestring.length() + 1; ++i)
681 text->cursorLeft(cur);
685 void eraseSelection(LCursor & cur)
687 //lyxerr << "LCursor::eraseSelection begin: " << cur << endl;
688 CursorSlice const & i1 = cur.selBegin();
689 CursorSlice const & i2 = cur.selEnd();
690 if (i1.inset().asMathInset()) {
692 if (i1.idx() == i2.idx()) {
693 i1.cell().erase(i1.pos(), i2.pos());
694 // We may have deleted i1.cell(cur.pos()).
695 // Make sure that pos is valid.
696 if (cur.pos() > cur.lastpos())
697 cur.pos() = cur.lastpos();
699 MathInset * p = i1.asMathInset();
700 InsetBase::row_type r1, r2;
701 InsetBase::col_type c1, c2;
702 region(i1, i2, r1, r2, c1, c2);
703 for (InsetBase::row_type row = r1; row <= r2; ++row)
704 for (InsetBase::col_type col = c1; col <= c2; ++col)
705 p->cell(p->index(row, col)).clear();
706 // We've deleted the whole cell. Only pos 0 is valid.
709 // need a valid cursor. (Lgb)
710 cur.clearSelection();
712 lyxerr << "can't erase this selection 1" << endl;
714 //lyxerr << "LCursor::eraseSelection end: " << cur << endl;
718 void selDel(LCursor & cur)
720 //lyxerr << "LCursor::selDel" << endl;
726 void selClearOrDel(LCursor & cur)
728 //lyxerr << "LCursor::selClearOrDel" << endl;
729 if (lyxrc.auto_region_delete)
732 cur.selection() = false;
736 string grabSelection(LCursor const & cur)
738 if (!cur.selection())
741 // FIXME: What is wrong with the following?
743 std::ostringstream os;
744 for (DocIterator dit = cur.selectionBegin();
745 dit != cur.selectionEnd(); dit.forwardPos())
746 os << asString(dit.cell());
750 CursorSlice i1 = cur.selBegin();
751 CursorSlice i2 = cur.selEnd();
753 if (i1.idx() == i2.idx()) {
754 if (i1.inset().asMathInset()) {
755 MathArray::const_iterator it = i1.cell().begin();
756 return asString(MathArray(it + i1.pos(), it + i2.pos()));
758 return "unknown selection 1";
762 InsetBase::row_type r1, r2;
763 InsetBase::col_type c1, c2;
764 region(i1, i2, r1, r2, c1, c2);
767 if (i1.inset().asMathInset()) {
768 for (InsetBase::row_type row = r1; row <= r2; ++row) {
771 for (InsetBase::col_type col = c1; col <= c2; ++col) {
774 data += asString(i1.asMathInset()->
775 cell(i1.asMathInset()->index(row, col)));
779 data = "unknown selection 2";
785 void dirtyTabularStack(bool b)
787 dirty_tabular_stack_ = b;
791 bool tabularStackDirty()
793 return dirty_tabular_stack_;