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"
22 #include "errorlist.h"
23 #include "funcrequest.h"
25 #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/MathData.h"
42 #include "mathed/InsetMath.h"
43 #include "mathed/MathSupport.h"
45 #include "support/lstrings.h"
47 #include "frontends/Clipboard.h"
49 #include <boost/tuple/tuple.hpp>
54 using support::bformat;
55 using frontend::Clipboard;
67 typedef std::pair<pit_type, int> PitPosPair;
69 typedef limited_stack<pair<ParagraphList, textclass_type> > CutStack;
73 // store whether the tabular stack is newer than the normal copy stack
74 // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
75 // when we (hopefully) have a one-for-all paste mechanism.
76 bool dirty_tabular_stack_;
79 void region(CursorSlice const & i1, CursorSlice const & i2,
80 InsetBase::row_type & r1, InsetBase::row_type & r2,
81 InsetBase::col_type & c1, InsetBase::col_type & c2)
83 InsetBase & p = i1.inset();
95 bool checkPastePossible(int index)
97 return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
101 pair<PitPosPair, pit_type>
102 pasteSelectionHelper(LCursor & cur, ParagraphList const & parlist,
103 textclass_type textclass, ErrorList & errorlist)
105 Buffer const & buffer = cur.buffer();
106 pit_type pit = cur.pit();
107 pos_type pos = cur.pos();
108 ParagraphList & pars = cur.text()->paragraphs();
111 return make_pair(PitPosPair(pit, pos), pit);
113 BOOST_ASSERT (pos <= pars[pit].size());
115 // Make a copy of the CaP paragraphs.
116 ParagraphList insertion = parlist;
117 textclass_type const tc = buffer.params().textclass;
119 // Now remove all out of the pars which is NOT allowed in the
120 // new environment and set also another font if that is required.
122 // Convert newline to paragraph break in ERT inset.
123 // This should not be here!
124 if (pars[pit].inInset() &&
125 pars[pit].inInset()->lyxCode() == InsetBase::ERT_CODE) {
126 for (ParagraphList::size_type i = 0; i < insertion.size(); ++i) {
127 for (pos_type j = 0; j < insertion[i].size(); ++j) {
128 if (insertion[i].isNewline(j)) {
129 // do not track deletion of newline
130 insertion[i].eraseChar(j, false);
131 breakParagraphConservative(
139 // If we are in an inset which returns forceDefaultParagraphs,
140 // set the paragraphs to default
141 if (cur.inset().forceDefaultParagraphs(cur.idx())) {
142 LyXLayout_ptr const layout =
143 buffer.params().getLyXTextClass().defaultLayout();
144 ParagraphList::iterator const end = insertion.end();
145 for (ParagraphList::iterator par = insertion.begin();
150 // Make sure there is no class difference.
152 // This works without copying any paragraph data because we have
153 // a specialized swap method for ParagraphList. This is important
154 // since we store pointers to insets at some places and we don't
155 // want to invalidate them.
156 insertion.swap(in.paragraphs());
157 cap::switchBetweenClasses(textclass, tc, in, errorlist);
158 insertion.swap(in.paragraphs());
160 ParagraphList::iterator tmpbuf = insertion.begin();
161 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
163 depth_type max_depth = pars[pit].getMaxDepthAfter();
165 for (; tmpbuf != insertion.end(); ++tmpbuf) {
166 // If we have a negative jump so that the depth would
167 // go below 0 depth then we have to redo the delta to
168 // this new max depth level so that subsequent
169 // paragraphs are aligned correctly to this paragraph
171 if (int(tmpbuf->params().depth()) + depth_delta < 0)
174 // Set the right depth so that we are not too deep or shallow.
175 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
176 if (tmpbuf->params().depth() > max_depth)
177 tmpbuf->params().depth(max_depth);
179 // Only set this from the 2nd on as the 2nd depends
180 // for maxDepth still on pit.
181 if (tmpbuf != insertion.begin())
182 max_depth = tmpbuf->getMaxDepthAfter();
184 // Set the inset owner of this paragraph.
185 tmpbuf->setInsetOwner(pars[pit].inInset());
186 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
187 if (tmpbuf->getChar(i) == Paragraph::META_INSET &&
188 !pars[pit].insetAllowed(tmpbuf->getInset(i)->lyxCode()))
189 // do not track deletion of invalid insets
190 tmpbuf->eraseChar(i--, false);
193 tmpbuf->setChange(Change(buffer.params().trackChanges ?
194 Change::INSERTED : Change::UNCHANGED));
197 bool const empty = pars[pit].empty();
199 // Make the buf exactly the same layout as the cursor
201 insertion.begin()->makeSameLayout(pars[pit]);
204 // Prepare the paragraphs and insets for insertion.
205 // A couple of insets store buffer references so need updating.
206 insertion.swap(in.paragraphs());
208 ParIterator fpit = par_iterator_begin(in);
209 ParIterator fend = par_iterator_end(in);
211 for (; fpit != fend; ++fpit) {
212 InsetList::iterator lit = fpit->insetlist.begin();
213 InsetList::iterator eit = fpit->insetlist.end();
215 for (; lit != eit; ++lit) {
216 switch (lit->inset->lyxCode()) {
217 case InsetBase::TABULAR_CODE: {
218 InsetTabular * it = static_cast<InsetTabular*>(lit->inset);
228 insertion.swap(in.paragraphs());
230 // Split the paragraph for inserting the buf if necessary.
232 breakParagraphConservative(buffer.params(), pars, pit, pos);
236 pars.insert(boost::next(pars.begin(), pit),
240 // merge the empty par with the last par of the insertion
241 mergeParagraph(buffer.params(), pars,
242 pit + insertion.size() - 1);
244 pars.insert(boost::next(pars.begin(), pit + 1),
248 // merge the first par of the insertion with the current par
249 mergeParagraph(buffer.params(), pars, pit);
252 pit_type last_paste = pit + insertion.size() - 1;
254 // Store the new cursor position.
256 pos = pars[last_paste].size();
258 // Join (conditionally) last pasted paragraph with next one, i.e.,
259 // the tail of the spliced document paragraph
260 if (!empty && last_paste + 1 != pit_type(pars.size())) {
261 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
262 mergeParagraph(buffer.params(), pars, last_paste);
263 } else if (pars[last_paste + 1].empty()) {
264 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
265 mergeParagraph(buffer.params(), pars, last_paste);
266 } else if (pars[last_paste].empty()) {
267 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
268 mergeParagraph(buffer.params(), pars, last_paste);
270 pars[last_paste + 1].stripLeadingSpaces();
275 return make_pair(PitPosPair(pit, pos), last_paste + 1);
279 PitPosPair eraseSelectionHelper(BufferParams const & params,
280 ParagraphList & pars,
281 pit_type startpit, pit_type endpit,
282 int startpos, int endpos, bool doclear)
284 // Start of selection is really invalid.
285 if (startpit == pit_type(pars.size()) ||
286 (startpos > pars[startpit].size()))
287 return PitPosPair(endpit, endpos);
289 // Start and end is inside same paragraph
290 if (endpit == pit_type(pars.size()) || startpit == endpit) {
291 endpos -= pars[startpit].eraseChars(startpos, endpos, params.trackChanges);
292 return PitPosPair(endpit, endpos);
295 // A paragraph break has to be physically removed by merging, but
296 // only if either (1) change tracking is off, or (2) the para break
298 for (pit_type pit = startpit; pit != endpit + 1;) {
299 // FIXME: Change tracking (MG)
300 bool const merge = !params.trackChanges ||
301 pars[pit].isInserted(pars[pit].size());
302 pos_type const left = (pit == startpit ? startpos : 0);
303 pos_type const right = (pit == endpit ? endpos : pars[pit].size() + 1);
304 // Logical erase only:
305 pars[pit].eraseChars(left, right, false);
306 // Separate handling of para break:
307 if (merge && pit != endpit &&
308 (pit + 1 != endpit || pars[pit].hasSameLayout(pars[pit + 1]))) {
309 pos_type const thissize = pars[pit].size();
311 pars[pit + 1].stripLeadingSpaces();
312 mergeParagraph(params, pars, pit);
320 // Ensure legal cursor pos:
323 return PitPosPair(endpit, endpos);
327 void copySelectionHelper(Buffer const & buf, ParagraphList & pars,
328 pit_type startpit, pit_type endpit,
329 int start, int end, textclass_type tc)
331 BOOST_ASSERT(0 <= start && start <= pars[startpit].size());
332 BOOST_ASSERT(0 <= end && end <= pars[endpit].size());
333 BOOST_ASSERT(startpit != endpit || start <= end);
335 // Clone the paragraphs within the selection.
336 ParagraphList paragraphs(boost::next(pars.begin(), startpit),
337 boost::next(pars.begin(), endpit + 1));
339 ParagraphList::iterator it = paragraphs.begin();
340 ParagraphList::iterator it_end = paragraphs.end();
342 for (; it != it_end; it++) {
343 // ERT paragraphs have the Language latex_language.
344 // This is invalid outside of ERT, so we need to change it
345 // to the buffer language.
346 if (it->ownerCode() == InsetBase::ERT_CODE) {
347 it->changeLanguage(buf.params(), latex_language,
350 it->setInsetOwner(0);
353 // Cut out the end of the last paragraph.
354 Paragraph & back = paragraphs.back();
355 // do not track deletion here; it is an internal action not visible to the user
356 back.eraseChars(end, back.size(), false);
358 // Cut out the begin of the first paragraph
359 Paragraph & front = paragraphs.front();
360 // again, do not track deletion
361 front.eraseChars(0, start, false);
363 theCuts.push(make_pair(paragraphs, tc));
373 docstring grabAndEraseSelection(LCursor & cur)
375 if (!cur.selection())
377 docstring res = grabSelection(cur);
383 void switchBetweenClasses(textclass_type c1, textclass_type c2,
384 InsetText & in, ErrorList & errorlist)
386 BOOST_ASSERT(!in.paragraphs().empty());
390 LyXTextClass const & tclass1 = textclasslist[c1];
391 LyXTextClass const & tclass2 = textclasslist[c2];
394 ParIterator end = par_iterator_end(in);
395 for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
396 string const name = it->layout()->name();
397 bool hasLayout = tclass2.hasLayout(name);
400 it->layout(tclass2[name]);
402 it->layout(tclass2.defaultLayout());
404 if (!hasLayout && name != tclass1.defaultLayoutName()) {
405 docstring const s = bformat(
406 _("Layout had to be changed from\n%1$s to %2$s\n"
407 "because of class conversion from\n%3$s to %4$s"),
408 from_utf8(name), from_utf8(it->layout()->name()),
409 from_utf8(tclass1.name()), from_utf8(tclass2.name()));
410 // To warn the user that something had to be done.
411 errorlist.push_back(ErrorItem(_("Changed Layout"), s,
418 InsetIterator const i_end = inset_iterator_end(in);
419 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
420 if (it->lyxCode() == InsetBase::CHARSTYLE_CODE) {
421 InsetCharStyle & inset =
422 static_cast<InsetCharStyle &>(*it);
423 string const name = inset.params().type;
424 CharStyles::iterator const found_cs =
425 tclass2.charstyle(name);
426 if (found_cs == tclass2.charstyles().end()) {
427 // The character style is undefined in tclass2
428 inset.setUndefined();
429 docstring const s = bformat(_(
430 "Character style %1$s is "
431 "undefined because of class "
432 "conversion from\n%2$s to %3$s"),
433 from_utf8(name), from_utf8(tclass1.name()),
434 from_utf8(tclass2.name()));
435 // To warn the user that something had to be done.
436 errorlist.push_back(ErrorItem(
437 _("Undefined character style"),
438 s, it.paragraph().id(), it.pos(), it.pos() + 1));
439 } else if (inset.undefined()) {
440 // The character style is undefined in
441 // tclass1 and is defined in tclass2
442 inset.setDefined(found_cs);
449 std::vector<docstring> const availableSelections(Buffer const & buffer)
451 vector<docstring> selList;
453 CutStack::const_iterator cit = theCuts.begin();
454 CutStack::const_iterator end = theCuts.end();
455 for (; cit != end; ++cit) {
456 // we do not use cit-> here because gcc 2.9x does not
458 ParagraphList const & pars = (*cit).first;
460 ParagraphList::const_iterator pit = pars.begin();
461 ParagraphList::const_iterator pend = pars.end();
462 for (; pit != pend; ++pit) {
463 asciiSel += pit->asString(buffer, false);
464 if (asciiSel.size() > 25) {
465 asciiSel.replace(22, docstring::npos,
471 selList.push_back(asciiSel);
478 size_type numberOfSelections()
480 return theCuts.size();
484 void cutSelection(LCursor & cur, bool doclear, bool realcut)
486 // This doesn't make sense, if there is no selection
487 if (!cur.selection())
490 // OK, we have a selection. This is always between cur.selBegin()
493 if (cur.inTexted()) {
494 LyXText * text = cur.text();
496 // Stuff what we got on the clipboard. Even if there is no selection.
498 // There is a problem with having the stuffing here in that the
499 // larger the selection the slower LyX will get. This can be
500 // solved by running the line below only when the selection has
501 // finished. The solution used currently just works, to make it
502 // faster we need to be more clever and probably also have more
503 // calls to theSelection().put. (Lgb)
504 // theSelection().put(cur.selectionAsString(true));
507 // make sure that the depth behind the selection are restored, too
508 recordUndoSelection(cur);
509 pit_type begpit = cur.selBegin().pit();
510 pit_type endpit = cur.selEnd().pit();
512 int endpos = cur.selEnd().pos();
514 BufferParams const & bp = cur.buffer().params();
516 copySelectionHelper(cur.buffer(),
519 cur.selBegin().pos(), endpos,
523 boost::tie(endpit, endpos) =
524 eraseSelectionHelper(bp,
527 cur.selBegin().pos(), endpos,
530 // sometimes necessary
532 text->paragraphs()[begpit].stripLeadingSpaces();
534 // cutSelection can invalidate the cursor so we need to set
536 // we prefer the end for when tracking changes
540 // need a valid cursor. (Lgb)
541 cur.clearSelection();
542 updateLabels(cur.buffer());
544 // tell tabular that a recent copy happened
545 dirtyTabularStack(false);
548 if (cur.inMathed()) {
549 if (cur.selBegin().idx() != cur.selEnd().idx()) {
550 // The current selection spans more than one cell.
552 recordUndoInset(cur);
554 // Record only the current cell to avoid a jumping
565 void copySelection(LCursor & cur)
567 // stuff the selection onto the X clipboard, from an explicit copy request
568 theClipboard().put(cur.selectionAsString(true));
570 // this doesn't make sense, if there is no selection
571 if (!cur.selection())
574 if (cur.inTexted()) {
575 LyXText * text = cur.text();
577 // ok we have a selection. This is always between cur.selBegin()
578 // and sel_end cursor
580 // copy behind a space if there is one
581 ParagraphList & pars = text->paragraphs();
582 pos_type pos = cur.selBegin().pos();
583 pit_type par = cur.selBegin().pit();
584 while (pos < pars[par].size()
585 && pars[par].isLineSeparator(pos)
586 && (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
589 copySelectionHelper(cur.buffer(), pars, par, cur.selEnd().pit(),
590 pos, cur.selEnd().pos(), cur.buffer().params().textclass);
593 if (cur.inMathed()) {
594 //lyxerr << "copySelection in mathed" << endl;
597 BufferParams const & bp = cur.buffer().params();
598 par.layout(bp.getLyXTextClass().defaultLayout());
599 par.insert(0, grabSelection(cur), LyXFont(), Change(Change::UNCHANGED));
601 theCuts.push(make_pair(pars, bp.textclass));
603 // tell tabular that a recent copy happened
604 dirtyTabularStack(false);
608 docstring getSelection(Buffer const & buf, size_t sel_index)
610 return sel_index < theCuts.size()
611 ? theCuts[sel_index].first.back().asString(buf, false)
616 void pasteParagraphList(LCursor & cur, ParagraphList const & parlist,
617 textclass_type textclass, ErrorList & errorList)
619 if (cur.inTexted()) {
620 LyXText * text = cur.text();
626 boost::tie(ppp, endpit) =
627 pasteSelectionHelper(cur, parlist,
628 textclass, errorList);
629 updateLabels(cur.buffer());
630 cur.clearSelection();
631 text->setCursor(cur, ppp.first, ppp.second);
634 // mathed is handled in InsetMathNest/InsetMathGrid
635 BOOST_ASSERT(!cur.inMathed());
639 void pasteSelection(LCursor & cur, ErrorList & errorList, size_t sel_index)
641 // this does not make sense, if there is nothing to paste
642 if (!checkPastePossible(sel_index))
646 pasteParagraphList(cur, theCuts[sel_index].first,
647 theCuts[sel_index].second, errorList);
652 // simple replacing. The font of the first selected character is used
653 void replaceSelectionWithString(LCursor & cur, string const & str, bool backwards)
656 DocIterator selbeg = cur.selectionBegin();
658 // Get font setting before we cut
660 selbeg.paragraph().getFontSettings(cur.buffer().params(), selbeg.pos());
662 // Insert the new string
663 pos_type pos = cur.selEnd().pos();
664 Paragraph & par = cur.selEnd().paragraph();
665 string::const_iterator cit = str.begin();
666 string::const_iterator end = str.end();
667 for (; cit != end; ++cit, ++pos)
668 par.insertChar(pos, (*cit), font, cur.buffer().params().trackChanges);
671 cutSelection(cur, true, false);
673 // select the replacement
675 selbeg.pos() += str.length();
676 cur.setSelection(selbeg, -int(str.length()));
678 cur.setSelection(selbeg, str.length());
682 void replaceSelection(LCursor & cur)
685 cutSelection(cur, true, false);
689 void eraseSelection(LCursor & cur)
691 //lyxerr << "LCursor::eraseSelection begin: " << cur << endl;
692 CursorSlice const & i1 = cur.selBegin();
693 CursorSlice const & i2 = cur.selEnd();
694 if (i1.inset().asInsetMath()) {
696 if (i1.idx() == i2.idx()) {
697 i1.cell().erase(i1.pos(), i2.pos());
698 // We may have deleted i1.cell(cur.pos()).
699 // Make sure that pos is valid.
700 if (cur.pos() > cur.lastpos())
701 cur.pos() = cur.lastpos();
703 InsetMath * p = i1.asInsetMath();
704 InsetBase::row_type r1, r2;
705 InsetBase::col_type c1, c2;
706 region(i1, i2, r1, r2, c1, c2);
707 for (InsetBase::row_type row = r1; row <= r2; ++row)
708 for (InsetBase::col_type col = c1; col <= c2; ++col)
709 p->cell(p->index(row, col)).clear();
710 // We've deleted the whole cell. Only pos 0 is valid.
713 // need a valid cursor. (Lgb)
714 cur.clearSelection();
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;
730 void selClearOrDel(LCursor & cur)
732 //lyxerr << "LCursor::selClearOrDel" << endl;
733 if (lyxrc.auto_region_delete)
736 cur.selection() = false;
740 docstring grabSelection(LCursor const & cur)
742 if (!cur.selection())
745 // FIXME: What is wrong with the following?
747 std::ostringstream os;
748 for (DocIterator dit = cur.selectionBegin();
749 dit != cur.selectionEnd(); dit.forwardPos())
750 os << asString(dit.cell());
754 CursorSlice i1 = cur.selBegin();
755 CursorSlice i2 = cur.selEnd();
757 if (i1.idx() == i2.idx()) {
758 if (i1.inset().asInsetMath()) {
759 MathArray::const_iterator it = i1.cell().begin();
760 return asString(MathArray(it + i1.pos(), it + i2.pos()));
762 return from_ascii("unknown selection 1");
766 InsetBase::row_type r1, r2;
767 InsetBase::col_type c1, c2;
768 region(i1, i2, r1, r2, c1, c2);
771 if (i1.inset().asInsetMath()) {
772 for (InsetBase::row_type row = r1; row <= r2; ++row) {
775 for (InsetBase::col_type col = c1; col <= c2; ++col) {
778 data += asString(i1.asInsetMath()->
779 cell(i1.asInsetMath()->index(row, col)));
783 data = from_ascii("unknown selection 2");
789 void dirtyTabularStack(bool b)
791 dirty_tabular_stack_ = b;
795 bool tabularStackDirty()
797 return dirty_tabular_stack_;