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
11 * Full author contact details are available in file CREDITS.
16 #include "CutAndPaste.h"
19 #include "buffer_funcs.h"
20 #include "bufferparams.h"
23 #include "errorlist.h"
24 #include "funcrequest.h"
26 #include "insetiterator.h"
31 #include "lyxtextclasslist.h"
32 #include "paragraph.h"
33 #include "paragraph_funcs.h"
34 #include "ParagraphParameters.h"
35 #include "ParagraphList_fwd.h"
36 #include "pariterator.h"
39 #include "insets/insetcharstyle.h"
40 #include "insets/insettabular.h"
42 #include "mathed/MathData.h"
43 #include "mathed/InsetMath.h"
44 #include "mathed/MathSupport.h"
46 #include "support/lstrings.h"
48 #include "frontends/Clipboard.h"
50 #include <boost/tuple/tuple.hpp>
55 using support::bformat;
56 using frontend::Clipboard;
68 typedef std::pair<pit_type, int> PitPosPair;
70 typedef limited_stack<pair<ParagraphList, textclass_type> > CutStack;
74 // store whether the tabular stack is newer than the normal copy stack
75 // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
76 // when we (hopefully) have a one-for-all paste mechanism.
77 bool dirty_tabular_stack_;
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(LCursor & cur, ParagraphList const & parlist,
104 textclass_type textclass, ErrorList & errorlist)
106 Buffer const & buffer = cur.buffer();
107 pit_type pit = cur.pit();
108 pos_type pos = cur.pos();
109 ParagraphList & pars = cur.text()->paragraphs();
112 return make_pair(PitPosPair(pit, pos), pit);
114 BOOST_ASSERT (pos <= pars[pit].size());
116 // Make a copy of the CaP paragraphs.
117 ParagraphList insertion = parlist;
118 textclass_type const tc = buffer.params().textclass;
120 // Now remove all out of the pars which is NOT allowed in the
121 // new environment and set also another font if that is required.
123 // Convert newline to paragraph break in ERT inset.
124 // This should not be here!
125 if (pars[pit].inInset() &&
126 pars[pit].inInset()->lyxCode() == InsetBase::ERT_CODE) {
127 for (ParagraphList::size_type i = 0; i < insertion.size(); ++i) {
128 for (pos_type j = 0; j < insertion[i].size(); ++j) {
129 if (insertion[i].isNewline(j)) {
130 // do not track deletion of newline
131 insertion[i].eraseChar(j, false);
132 breakParagraphConservative(
140 // If we are in an inset which returns forceDefaultParagraphs,
141 // set the paragraphs to default
142 if (cur.inset().forceDefaultParagraphs(cur.idx())) {
143 LyXLayout_ptr const layout =
144 buffer.params().getLyXTextClass().defaultLayout();
145 ParagraphList::iterator const end = insertion.end();
146 for (ParagraphList::iterator par = insertion.begin();
151 // Make sure there is no class difference.
153 // This works without copying any paragraph data because we have
154 // a specialized swap method for ParagraphList. This is important
155 // since we store pointers to insets at some places and we don't
156 // want to invalidate them.
157 insertion.swap(in.paragraphs());
158 cap::switchBetweenClasses(textclass, tc, in, errorlist);
159 insertion.swap(in.paragraphs());
161 ParagraphList::iterator tmpbuf = insertion.begin();
162 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
164 depth_type max_depth = pars[pit].getMaxDepthAfter();
166 for (; tmpbuf != insertion.end(); ++tmpbuf) {
167 // If we have a negative jump so that the depth would
168 // go below 0 depth then we have to redo the delta to
169 // this new max depth level so that subsequent
170 // paragraphs are aligned correctly to this paragraph
172 if (int(tmpbuf->params().depth()) + depth_delta < 0)
175 // Set the right depth so that we are not too deep or shallow.
176 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
177 if (tmpbuf->params().depth() > max_depth)
178 tmpbuf->params().depth(max_depth);
180 // Only set this from the 2nd on as the 2nd depends
181 // for maxDepth still on pit.
182 if (tmpbuf != insertion.begin())
183 max_depth = tmpbuf->getMaxDepthAfter();
185 // Set the inset owner of this paragraph.
186 tmpbuf->setInsetOwner(pars[pit].inInset());
187 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
188 if (tmpbuf->getChar(i) == Paragraph::META_INSET &&
189 !pars[pit].insetAllowed(tmpbuf->getInset(i)->lyxCode()))
190 // do not track deletion of invalid insets
191 tmpbuf->eraseChar(i--, false);
194 tmpbuf->setChange(Change(buffer.params().trackChanges ?
195 Change::INSERTED : Change::UNCHANGED));
198 bool const empty = pars[pit].empty();
200 // Make the buf exactly the same layout as the cursor
202 insertion.begin()->makeSameLayout(pars[pit]);
205 // Prepare the paragraphs and insets for insertion.
206 // A couple of insets store buffer references so need updating.
207 insertion.swap(in.paragraphs());
209 ParIterator fpit = par_iterator_begin(in);
210 ParIterator fend = par_iterator_end(in);
212 for (; fpit != fend; ++fpit) {
213 InsetList::const_iterator lit = fpit->insetlist.begin();
214 InsetList::const_iterator eit = fpit->insetlist.end();
216 for (; lit != eit; ++lit) {
217 switch (lit->inset->lyxCode()) {
218 case InsetBase::TABULAR_CODE: {
219 InsetTabular * it = static_cast<InsetTabular*>(lit->inset);
229 insertion.swap(in.paragraphs());
231 // Split the paragraph for inserting the buf if necessary.
233 breakParagraphConservative(buffer.params(), pars, pit, pos);
237 pars.insert(boost::next(pars.begin(), pit),
241 // merge the empty par with the last par of the insertion
242 mergeParagraph(buffer.params(), pars,
243 pit + insertion.size() - 1);
245 pars.insert(boost::next(pars.begin(), pit + 1),
249 // merge the first par of the insertion with the current par
250 mergeParagraph(buffer.params(), pars, pit);
253 pit_type last_paste = pit + insertion.size() - 1;
255 // Store the new cursor position.
257 pos = pars[last_paste].size();
259 // Join (conditionally) last pasted paragraph with next one, i.e.,
260 // the tail of the spliced document paragraph
261 if (!empty && last_paste + 1 != pit_type(pars.size())) {
262 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
263 mergeParagraph(buffer.params(), pars, last_paste);
264 } else if (pars[last_paste + 1].empty()) {
265 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
266 mergeParagraph(buffer.params(), pars, last_paste);
267 } else if (pars[last_paste].empty()) {
268 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
269 mergeParagraph(buffer.params(), pars, last_paste);
271 pars[last_paste + 1].stripLeadingSpaces();
276 return make_pair(PitPosPair(pit, pos), last_paste + 1);
280 PitPosPair eraseSelectionHelper(BufferParams const & params,
281 ParagraphList & pars,
282 pit_type startpit, pit_type endpit,
283 int startpos, int endpos, bool doclear)
285 // Start of selection is really invalid.
286 if (startpit == pit_type(pars.size()) ||
287 (startpos > pars[startpit].size()))
288 return PitPosPair(endpit, endpos);
290 // Start and end is inside same paragraph
291 if (endpit == pit_type(pars.size()) || startpit == endpit) {
292 endpos -= pars[startpit].eraseChars(startpos, endpos, params.trackChanges);
293 return PitPosPair(endpit, endpos);
296 for (pit_type pit = startpit; pit != endpit + 1;) {
297 pos_type const left = (pit == startpit ? startpos : 0);
298 pos_type const right = (pit == endpit ? endpos : pars[pit].size() + 1);
300 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.trackChanges);
302 // Logically erase only, including the end-of-paragraph character
303 pars[pit].eraseChars(left, right, params.trackChanges);
305 // Separate handling of paragraph break:
306 if (merge && pit != endpit &&
307 (pit + 1 != endpit || pars[pit].hasSameLayout(pars[pit + 1]))) {
308 pos_type const thissize = pars[pit].size();
310 pars[pit + 1].stripLeadingSpaces();
311 mergeParagraph(params, pars, pit);
319 // Ensure legal cursor pos:
322 return PitPosPair(endpit, endpos);
326 void copySelectionHelper(Buffer const & buf, ParagraphList & pars,
327 pit_type startpit, pit_type endpit,
328 int start, int end, textclass_type tc)
330 BOOST_ASSERT(0 <= start && start <= pars[startpit].size());
331 BOOST_ASSERT(0 <= end && end <= pars[endpit].size());
332 BOOST_ASSERT(startpit != endpit || start <= end);
334 // Clone the paragraphs within the selection.
335 ParagraphList paragraphs(boost::next(pars.begin(), startpit),
336 boost::next(pars.begin(), endpit + 1));
338 ParagraphList::iterator it = paragraphs.begin();
339 ParagraphList::iterator it_end = paragraphs.end();
341 for (; it != it_end; it++) {
342 // ERT paragraphs have the Language latex_language.
343 // This is invalid outside of ERT, so we need to change it
344 // to the buffer language.
345 if (it->ownerCode() == InsetBase::ERT_CODE) {
346 it->changeLanguage(buf.params(), latex_language,
349 it->setInsetOwner(0);
352 // Cut out the end of the last paragraph.
353 Paragraph & back = paragraphs.back();
354 // do not track deletion here; it is an internal action not visible to the user
355 back.eraseChars(end, back.size(), false);
357 // Cut out the begin of the first paragraph
358 Paragraph & front = paragraphs.front();
359 // again, do not track deletion
360 front.eraseChars(0, start, false);
362 theCuts.push(make_pair(paragraphs, tc));
372 docstring grabAndEraseSelection(LCursor & cur)
374 if (!cur.selection())
376 docstring res = grabSelection(cur);
382 void switchBetweenClasses(textclass_type c1, textclass_type c2,
383 InsetText & in, ErrorList & errorlist)
385 BOOST_ASSERT(!in.paragraphs().empty());
389 LyXTextClass const & tclass1 = textclasslist[c1];
390 LyXTextClass const & tclass2 = textclasslist[c2];
393 ParIterator end = par_iterator_end(in);
394 for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
395 string const name = it->layout()->name();
396 bool hasLayout = tclass2.hasLayout(name);
399 it->layout(tclass2[name]);
401 it->layout(tclass2.defaultLayout());
403 if (!hasLayout && name != tclass1.defaultLayoutName()) {
404 docstring const s = bformat(
405 _("Layout had to be changed from\n%1$s to %2$s\n"
406 "because of class conversion from\n%3$s to %4$s"),
407 from_utf8(name), from_utf8(it->layout()->name()),
408 from_utf8(tclass1.name()), from_utf8(tclass2.name()));
409 // To warn the user that something had to be done.
410 errorlist.push_back(ErrorItem(_("Changed Layout"), s,
417 InsetIterator const i_end = inset_iterator_end(in);
418 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
419 if (it->lyxCode() == InsetBase::CHARSTYLE_CODE) {
420 InsetCharStyle & inset =
421 static_cast<InsetCharStyle &>(*it);
422 string const name = inset.params().type;
423 CharStyles::iterator const found_cs =
424 tclass2.charstyle(name);
425 if (found_cs == tclass2.charstyles().end()) {
426 // The character style is undefined in tclass2
427 inset.setUndefined();
428 docstring const s = bformat(_(
429 "Character style %1$s is "
430 "undefined because of class "
431 "conversion from\n%2$s to %3$s"),
432 from_utf8(name), from_utf8(tclass1.name()),
433 from_utf8(tclass2.name()));
434 // To warn the user that something had to be done.
435 errorlist.push_back(ErrorItem(
436 _("Undefined character style"),
437 s, it.paragraph().id(), it.pos(), it.pos() + 1));
438 } else if (inset.undefined()) {
439 // The character style is undefined in
440 // tclass1 and is defined in tclass2
441 inset.setDefined(found_cs);
448 std::vector<docstring> const availableSelections(Buffer const & buffer)
450 vector<docstring> selList;
452 CutStack::const_iterator cit = theCuts.begin();
453 CutStack::const_iterator end = theCuts.end();
454 for (; cit != end; ++cit) {
455 // we do not use cit-> here because gcc 2.9x does not
457 ParagraphList const & pars = (*cit).first;
459 ParagraphList::const_iterator pit = pars.begin();
460 ParagraphList::const_iterator pend = pars.end();
461 for (; pit != pend; ++pit) {
462 asciiSel += pit->asString(buffer, false);
463 if (asciiSel.size() > 25) {
464 asciiSel.replace(22, docstring::npos,
470 selList.push_back(asciiSel);
477 size_type numberOfSelections()
479 return theCuts.size();
483 void cutSelection(LCursor & cur, bool doclear, bool realcut)
485 // This doesn't make sense, if there is no selection
486 if (!cur.selection())
489 // OK, we have a selection. This is always between cur.selBegin()
492 if (cur.inTexted()) {
493 LyXText * text = cur.text();
495 // Stuff what we got on the clipboard. Even if there is no selection.
497 // There is a problem with having the stuffing here in that the
498 // larger the selection the slower LyX will get. This can be
499 // solved by running the line below only when the selection has
500 // finished. The solution used currently just works, to make it
501 // faster we need to be more clever and probably also have more
502 // calls to theSelection().put. (Lgb)
503 // theSelection().put(cur.selectionAsString(true));
506 // make sure that the depth behind the selection are restored, too
507 recordUndoSelection(cur);
508 pit_type begpit = cur.selBegin().pit();
509 pit_type endpit = cur.selEnd().pit();
511 int endpos = cur.selEnd().pos();
513 BufferParams const & bp = cur.buffer().params();
515 copySelectionHelper(cur.buffer(),
518 cur.selBegin().pos(), endpos,
522 boost::tie(endpit, endpos) =
523 eraseSelectionHelper(bp,
526 cur.selBegin().pos(), endpos,
529 // sometimes necessary
531 text->paragraphs()[begpit].stripLeadingSpaces();
533 // cutSelection can invalidate the cursor so we need to set
535 // we prefer the end for when tracking changes
539 // need a valid cursor. (Lgb)
540 cur.clearSelection();
541 updateLabels(cur.buffer());
543 // tell tabular that a recent copy happened
544 dirtyTabularStack(false);
547 if (cur.inMathed()) {
548 if (cur.selBegin().idx() != cur.selEnd().idx()) {
549 // The current selection spans more than one cell.
551 recordUndoInset(cur);
553 // Record only the current cell to avoid a jumping
564 void copySelection(LCursor & cur)
566 // stuff the selection onto the X clipboard, from an explicit copy request
567 theClipboard().put(cur.selectionAsString(true));
569 // this doesn't make sense, if there is no selection
570 if (!cur.selection())
573 if (cur.inTexted()) {
574 LyXText * text = cur.text();
576 // ok we have a selection. This is always between cur.selBegin()
577 // and sel_end cursor
579 // copy behind a space if there is one
580 ParagraphList & pars = text->paragraphs();
581 pos_type pos = cur.selBegin().pos();
582 pit_type par = cur.selBegin().pit();
583 while (pos < pars[par].size()
584 && pars[par].isLineSeparator(pos)
585 && (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
588 copySelectionHelper(cur.buffer(), pars, par, cur.selEnd().pit(),
589 pos, cur.selEnd().pos(), cur.buffer().params().textclass);
592 if (cur.inMathed()) {
593 //lyxerr << "copySelection in mathed" << endl;
596 BufferParams const & bp = cur.buffer().params();
597 par.layout(bp.getLyXTextClass().defaultLayout());
598 par.insert(0, grabSelection(cur), LyXFont(), Change(Change::UNCHANGED));
600 theCuts.push(make_pair(pars, bp.textclass));
602 // tell tabular that a recent copy happened
603 dirtyTabularStack(false);
607 docstring getSelection(Buffer const & buf, size_t sel_index)
609 return sel_index < theCuts.size()
610 ? theCuts[sel_index].first.back().asString(buf, false)
615 void pasteParagraphList(LCursor & cur, ParagraphList const & parlist,
616 textclass_type textclass, ErrorList & errorList)
618 if (cur.inTexted()) {
619 LyXText * text = cur.text();
625 boost::tie(ppp, endpit) =
626 pasteSelectionHelper(cur, parlist,
627 textclass, errorList);
628 updateLabels(cur.buffer());
629 cur.clearSelection();
630 text->setCursor(cur, ppp.first, ppp.second);
633 // mathed is handled in InsetMathNest/InsetMathGrid
634 BOOST_ASSERT(!cur.inMathed());
638 void pasteSelection(LCursor & cur, ErrorList & errorList, size_t sel_index)
640 // this does not make sense, if there is nothing to paste
641 if (!checkPastePossible(sel_index))
645 pasteParagraphList(cur, theCuts[sel_index].first,
646 theCuts[sel_index].second, errorList);
651 // simple replacing. The font of the first selected character is used
652 void replaceSelectionWithString(LCursor & cur, docstring const & str, bool backwards)
655 DocIterator selbeg = cur.selectionBegin();
657 // Get font setting before we cut
659 selbeg.paragraph().getFontSettings(cur.buffer().params(), selbeg.pos());
661 // Insert the new string
662 pos_type pos = cur.selEnd().pos();
663 Paragraph & par = cur.selEnd().paragraph();
664 docstring::const_iterator cit = str.begin();
665 docstring::const_iterator end = str.end();
666 for (; cit != end; ++cit, ++pos)
667 par.insertChar(pos, *cit, font, cur.buffer().params().trackChanges);
670 cutSelection(cur, true, false);
672 // select the replacement
674 selbeg.pos() += str.length();
675 cur.setSelection(selbeg, -int(str.length()));
677 cur.setSelection(selbeg, str.length());
681 void replaceSelection(LCursor & cur)
684 cutSelection(cur, true, false);
688 void eraseSelection(LCursor & cur)
690 //lyxerr << "LCursor::eraseSelection begin: " << cur << endl;
691 CursorSlice const & i1 = cur.selBegin();
692 CursorSlice const & i2 = cur.selEnd();
693 if (i1.inset().asInsetMath()) {
695 if (i1.idx() == i2.idx()) {
696 i1.cell().erase(i1.pos(), i2.pos());
697 // We may have deleted i1.cell(cur.pos()).
698 // Make sure that pos is valid.
699 if (cur.pos() > cur.lastpos())
700 cur.pos() = cur.lastpos();
702 InsetMath * p = i1.asInsetMath();
703 InsetBase::row_type r1, r2;
704 InsetBase::col_type c1, c2;
705 region(i1, i2, r1, r2, c1, c2);
706 for (InsetBase::row_type row = r1; row <= r2; ++row)
707 for (InsetBase::col_type col = c1; col <= c2; ++col)
708 p->cell(p->index(row, col)).clear();
709 // We've deleted the whole cell. Only pos 0 is valid.
712 // need a valid cursor. (Lgb)
713 cur.clearSelection();
715 lyxerr << "can't erase this selection 1" << endl;
717 //lyxerr << "LCursor::eraseSelection end: " << cur << endl;
721 void selDel(LCursor & cur)
723 //lyxerr << "LCursor::selDel" << endl;
729 void selClearOrDel(LCursor & cur)
731 //lyxerr << "LCursor::selClearOrDel" << endl;
732 if (lyxrc.auto_region_delete)
735 cur.selection() = false;
739 docstring grabSelection(LCursor const & cur)
741 if (!cur.selection())
744 // FIXME: What is wrong with the following?
746 std::ostringstream os;
747 for (DocIterator dit = cur.selectionBegin();
748 dit != cur.selectionEnd(); dit.forwardPos())
749 os << asString(dit.cell());
753 CursorSlice i1 = cur.selBegin();
754 CursorSlice i2 = cur.selEnd();
756 if (i1.idx() == i2.idx()) {
757 if (i1.inset().asInsetMath()) {
758 MathArray::const_iterator it = i1.cell().begin();
759 return asString(MathArray(it + i1.pos(), it + i2.pos()));
761 return from_ascii("unknown selection 1");
765 InsetBase::row_type r1, r2;
766 InsetBase::col_type c1, c2;
767 region(i1, i2, r1, r2, c1, c2);
770 if (i1.inset().asInsetMath()) {
771 for (InsetBase::row_type row = r1; row <= r2; ++row) {
774 for (InsetBase::col_type col = c1; col <= c2; ++col) {
777 data += asString(i1.asInsetMath()->
778 cell(i1.asInsetMath()->index(row, col)));
782 data = from_ascii("unknown selection 2");
788 void dirtyTabularStack(bool b)
790 dirty_tabular_stack_ = b;
794 bool tabularStackDirty()
796 return dirty_tabular_stack_;