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, ParagraphList & pars,
109 pit_type pit, int pos,
110 textclass_type tc, size_t cut_index, ErrorList & errorlist)
112 if (!checkPastePossible(cut_index))
113 return make_pair(PitPosPair(pit, pos), pit);
115 BOOST_ASSERT (pos <= pars[pit].size());
117 // Make a copy of the CaP paragraphs.
118 ParagraphList insertion = theCuts[cut_index].first;
119 textclass_type const textclass = theCuts[cut_index].second;
121 // Now remove all out of the pars which is NOT allowed in the
122 // new environment and set also another font if that is required.
124 // Convert newline to paragraph break in ERT inset.
125 // This should not be here!
126 if (pars[pit].inInset() &&
127 pars[pit].inInset()->lyxCode() == InsetBase::ERT_CODE) {
128 for (ParagraphList::size_type i = 0; i < insertion.size(); ++i) {
129 for (pos_type j = 0; j < insertion[i].size(); ++j) {
130 if (insertion[i].isNewline(j)) {
131 insertion[i].erase(j);
132 breakParagraphConservative(
140 // Make sure there is no class difference.
141 lyx::cap::SwitchBetweenClasses(textclass, tc, insertion, errorlist);
143 ParagraphList::iterator tmpbuf = insertion.begin();
144 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
146 Paragraph::depth_type max_depth = pars[pit].getMaxDepthAfter();
148 for (; tmpbuf != insertion.end(); ++tmpbuf) {
149 // If we have a negative jump so that the depth would
150 // go below 0 depth then we have to redo the delta to
151 // this new max depth level so that subsequent
152 // paragraphs are aligned correctly to this paragraph
154 if (int(tmpbuf->params().depth()) + depth_delta < 0)
157 // Set the right depth so that we are not too deep or shallow.
158 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
159 if (tmpbuf->params().depth() > max_depth)
160 tmpbuf->params().depth(max_depth);
162 // Only set this from the 2nd on as the 2nd depends
163 // for maxDepth still on pit.
164 if (tmpbuf != insertion.begin())
165 max_depth = tmpbuf->getMaxDepthAfter();
167 // Set the inset owner of this paragraph.
168 tmpbuf->setInsetOwner(pars[pit].inInset());
169 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
170 if (tmpbuf->getChar(i) == Paragraph::META_INSET &&
171 !pars[pit].insetAllowed(tmpbuf->getInset(i)->lyxCode()))
176 bool const empty = pars[pit].empty();
178 // Make the buf exactly the same layout as the cursor
180 insertion.begin()->makeSameLayout(pars[pit]);
183 // Prepare the paragraphs and insets for insertion.
184 // A couple of insets store buffer references so need updating.
186 std::swap(in.paragraphs(), insertion);
188 ParIterator fpit = par_iterator_begin(in);
189 ParIterator fend = par_iterator_end(in);
191 for (; fpit != fend; ++fpit) {
192 InsetList::iterator lit = fpit->insetlist.begin();
193 InsetList::iterator eit = fpit->insetlist.end();
195 for (; lit != eit; ++lit) {
196 switch (lit->inset->lyxCode()) {
197 case InsetBase::TABULAR_CODE: {
198 InsetTabular * it = static_cast<InsetTabular*>(lit->inset);
208 std::swap(in.paragraphs(), insertion);
210 // Split the paragraph for inserting the buf if necessary.
212 breakParagraphConservative(buffer.params(), pars, pit, pos);
216 pars.insert(pars.begin() + pit, insertion.begin(),
219 // merge the empty par with the last par of the insertion
220 mergeParagraph(buffer.params(), pars,
221 pit + insertion.size() - 1);
223 pars.insert(pars.begin() + pit + 1, insertion.begin(),
226 // merge the first par of the insertion with the current par
227 mergeParagraph(buffer.params(), pars, pit);
230 pit_type last_paste = pit + insertion.size() - 1;
232 // Store the new cursor position.
234 pos = pars[last_paste].size();
236 // Maybe some pasting.
237 if (!empty && last_paste + 1 != pit_type(pars.size())) {
238 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
239 mergeParagraph(buffer.params(), pars, last_paste);
240 } else if (pars[last_paste + 1].empty()) {
241 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
242 mergeParagraph(buffer.params(), pars, last_paste);
243 } else if (pars[last_paste].empty()) {
244 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
245 mergeParagraph(buffer.params(), pars, last_paste);
247 pars[last_paste + 1].stripLeadingSpaces();
252 return make_pair(PitPosPair(pit, pos), last_paste + 1);
256 PitPosPair eraseSelectionHelper(BufferParams const & params,
257 ParagraphList & pars,
258 pit_type startpit, pit_type endpit,
259 int startpos, int endpos, bool doclear)
261 // Start of selection is really invalid.
262 if (startpit == pit_type(pars.size()) ||
263 (startpos > pars[startpit].size()))
264 return PitPosPair(endpit, endpos);
266 // Start and end is inside same paragraph
267 if (endpit == pit_type(pars.size()) ||
268 startpit == endpit) {
269 endpos -= pars[startpit].erase(startpos, endpos);
270 return PitPosPair(endpit, endpos);
273 bool all_erased = true;
275 // Clear fragments of the first par in selection
276 pars[startpit].erase(startpos, pars[startpit].size());
277 if (pars[startpit].size() != startpos)
280 // Clear fragments of the last par in selection
281 endpos -= pars[endpit].erase(0, endpos);
285 // Erase all the "middle" paragraphs.
286 if (params.tracking_changes) {
287 // Look through the deleted pars if any, erasing as needed
288 for (pit_type pit = startpit + 1; pit != endpit;) {
289 // "erase" the contents of the par
290 pars[pit].erase(0, pars[pit].size());
291 if (pars[pit].empty()) {
292 // remove the par if it's now empty
293 pars.erase(pars.begin() + pit);
301 pars.erase(pars.begin() + startpit + 1, pars.begin() + endpit);
302 endpit = startpit + 1;
305 #if 0 // FIXME: why for cut but not copy ?
306 // the cut selection should begin with standard layout
308 buf->params().clear();
310 buf->layout(textclasslist[buffer->params.textclass].defaultLayoutName());
314 if (startpit + 1 == pit_type(pars.size()))
315 return PitPosPair(endpit, endpos);
318 pars[startpit + 1].stripLeadingSpaces();
321 // Merge first and last paragraph, if possible
323 (pars[startpit].hasSameLayout(pars[startpit + 1]) ||
324 pars[startpit + 1].empty())) {
325 mergeParagraph(params, pars, startpit);
326 // This because endpar gets deleted here!
331 return PitPosPair(endpit, endpos);
335 void copySelectionHelper(ParagraphList & pars,
336 pit_type startpit, pit_type endpit,
337 int start, int end, textclass_type tc)
339 BOOST_ASSERT(0 <= start && start <= pars[startpit].size());
340 BOOST_ASSERT(0 <= end && end <= pars[endpit].size());
341 BOOST_ASSERT(startpit != endpit || start <= end);
343 // Clone the paragraphs within the selection.
344 ParagraphList paragraphs(pars.begin() + startpit, pars.begin() + endpit + 1);
346 for_each(paragraphs.begin(), paragraphs.end(), resetOwnerAndChanges());
348 // Cut out the end of the last paragraph.
349 Paragraph & back = paragraphs.back();
350 back.erase(end, back.size());
352 // Cut out the begin of the first paragraph
353 Paragraph & front = paragraphs.front();
354 front.erase(0, start);
356 theCuts.push(make_pair(paragraphs, tc));
367 string grabAndEraseSelection(LCursor & cur)
369 if (!cur.selection())
371 string res = grabSelection(cur);
377 void SwitchBetweenClasses(textclass_type c1, textclass_type c2,
378 ParagraphList & pars, ErrorList & errorlist)
380 BOOST_ASSERT(!pars.empty());
384 LyXTextClass const & tclass1 = textclasslist[c1];
385 LyXTextClass const & tclass2 = textclasslist[c2];
388 std::swap(in.paragraphs(), pars);
391 ParIterator end = par_iterator_end(in);
392 for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
393 string const name = it->layout()->name();
394 bool hasLayout = tclass2.hasLayout(name);
397 it->layout(tclass2[name]);
399 it->layout(tclass2.defaultLayout());
401 if (!hasLayout && name != tclass1.defaultLayoutName()) {
402 string const s = bformat(
403 _("Layout had to be changed from\n%1$s to %2$s\n"
404 "because of class conversion from\n%3$s to %4$s"),
405 name, it->layout()->name(), tclass1.name(), tclass2.name());
406 // To warn the user that something had to be done.
407 errorlist.push_back(ErrorItem(_("Changed Layout"), s,
414 InsetIterator const i_end = inset_iterator_end(in);
415 for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
416 if (it->lyxCode() == InsetBase::CHARSTYLE_CODE) {
417 InsetCharStyle & inset =
418 static_cast<InsetCharStyle &>(*it);
419 string const name = inset.params().type;
420 CharStyles::iterator const found_cs =
421 tclass2.charstyle(name);
422 if (found_cs == tclass2.charstyles().end()) {
423 // The character style is undefined in tclass2
424 inset.setUndefined();
425 string const s = bformat(_(
426 "Character style %1$s is "
427 "undefined because of class "
428 "conversion from\n%2$s to %3$s"),
429 name, tclass1.name(), tclass2.name());
430 // To warn the user that something had to be done.
431 errorlist.push_back(ErrorItem(
432 _("Undefined character style"),
433 s, it.paragraph().id(),
434 it.pos(), it.pos() + 1));
435 } else if (inset.undefined()) {
436 // The character style is undefined in
437 // tclass1 and is defined in tclass2
438 inset.setDefined(found_cs);
443 std::swap(in.paragraphs(), pars);
447 std::vector<string> const availableSelections(Buffer const & buffer)
449 vector<string> selList;
451 CutStack::const_iterator cit = theCuts.begin();
452 CutStack::const_iterator end = theCuts.end();
453 for (; cit != end; ++cit) {
454 // we do not use cit-> here because gcc 2.9x does not
456 ParagraphList const & pars = (*cit).first;
458 ParagraphList::const_iterator pit = pars.begin();
459 ParagraphList::const_iterator pend = pars.end();
460 for (; pit != pend; ++pit) {
461 asciiSel += pit->asString(buffer, false);
462 if (asciiSel.size() > 25) {
463 asciiSel.replace(22, string::npos, "...");
468 selList.push_back(asciiSel);
475 lyx::size_type numberOfSelections()
477 return theCuts.size();
481 void cutSelection(LCursor & cur, bool doclear, bool realcut)
483 // This doesn't make sense, if there is no selection
484 if (!cur.selection())
487 // OK, we have a selection. This is always between cur.selBegin()
490 if (cur.inTexted()) {
491 LyXText * text = cur.text();
493 // Stuff what we got on the clipboard. Even if there is no selection.
495 // There is a problem with having the stuffing here in that the
496 // larger the selection the slower LyX will get. This can be
497 // solved by running the line below only when the selection has
498 // finished. The solution used currently just works, to make it
499 // faster we need to be more clever and probably also have more
500 // calls to stuffClipboard. (Lgb)
501 // cur.bv().stuffClipboard(cur.selectionAsString(true));
503 // make sure that the depth behind the selection are restored, too
504 recordUndoSelection(cur);
505 pit_type begpit = cur.selBegin().pit();
506 pit_type endpit = cur.selEnd().pit();
508 int endpos = cur.selEnd().pos();
510 BufferParams const & bp = cur.buffer().params();
512 copySelectionHelper(text->paragraphs(),
514 cur.selBegin().pos(), endpos,
518 boost::tie(endpit, endpos) =
519 eraseSelectionHelper(bp,
522 cur.selBegin().pos(), endpos,
525 // sometimes necessary
527 text->paragraphs()[begpit].stripLeadingSpaces();
529 // cutSelection can invalidate the cursor so we need to set
531 // we prefer the end for when tracking changes
535 // need a valid cursor. (Lgb)
536 cur.clearSelection();
537 updateCounters(cur.buffer());
539 // tell tabular that a recent copy happened
540 dirtyTabularStack(false);
543 if (cur.inMathed()) {
544 if (cur.selBegin().idx() != cur.selEnd().idx()) {
545 // The current selection spans more than one cell.
547 recordUndoInset(cur);
549 // Record only the current cell to avoid a jumping
560 void copySelection(LCursor & cur)
562 // stuff the selection onto the X clipboard, from an explicit copy request
563 cur.bv().stuffClipboard(cur.selectionAsString(true));
565 // this doesn't make sense, if there is no selection
566 if (!cur.selection())
569 if (cur.inTexted()) {
570 LyXText * text = cur.text();
572 // ok we have a selection. This is always between cur.selBegin()
573 // and sel_end cursor
575 // copy behind a space if there is one
576 ParagraphList & pars = text->paragraphs();
577 pos_type pos = cur.selBegin().pos();
578 pit_type par = cur.selBegin().pit();
579 while (pos < pars[par].size()
580 && pars[par].isLineSeparator(pos)
581 && (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
584 copySelectionHelper(pars, par, cur.selEnd().pit(),
585 pos, cur.selEnd().pos(), cur.buffer().params().textclass);
588 if (cur.inMathed()) {
589 lyxerr << "copySelection in mathed" << endl;
591 pars.push_back(Paragraph());
592 BufferParams const & bp = cur.buffer().params();
593 pars.back().layout(bp.getLyXTextClass().defaultLayout());
594 for_each(pars.begin(), pars.end(), resetOwnerAndChanges());
595 pars.back().insert(0, grabSelection(cur), LyXFont());
596 theCuts.push(make_pair(pars, bp.textclass));
598 // tell tabular that a recent copy happened
599 dirtyTabularStack(false);
603 std::string getSelection(Buffer const & buf, size_t sel_index)
605 return sel_index < theCuts.size()
606 ? theCuts[sel_index].first.back().asString(buf, false)
611 void pasteSelection(LCursor & cur, size_t sel_index)
613 // this does not make sense, if there is nothing to paste
614 lyxerr << "#### pasteSelection " << sel_index << endl;
615 if (!checkPastePossible(sel_index))
618 if (cur.inTexted()) {
619 LyXText * text = cur.text();
629 boost::tie(ppp, endpit) =
630 pasteSelectionHelper(cur.buffer(),
632 cur.pit(), cur.pos(),
633 cur.buffer().params().textclass,
635 bufferErrors(cur.buffer(), el);
636 cur.bv().showErrorList(_("Paste"));
638 cur.clearSelection();
639 text->setCursor(cur, ppp.first, ppp.second);
641 updateCounters(cur.buffer());
644 // mathed is handled in MathNestInset/MathGridInset
645 BOOST_ASSERT(!cur.inMathed());
649 void setSelectionRange(LCursor & cur, pos_type length)
651 LyXText * text = cur.text();
657 text->cursorRight(cur);
662 // simple replacing. The font of the first selected character is used
663 void replaceSelectionWithString(LCursor & cur, string const & str)
665 LyXText * text = cur.text();
669 // Get font setting before we cut
670 pos_type pos = cur.selEnd().pos();
671 Paragraph & par = text->getPar(cur.selEnd().pit());
673 par.getFontSettings(cur.buffer().params(), cur.selBegin().pos());
675 // Insert the new string
676 string::const_iterator cit = str.begin();
677 string::const_iterator end = str.end();
678 for (; cit != end; ++cit, ++pos)
679 par.insertChar(pos, (*cit), font);
682 cutSelection(cur, true, false);
686 void replaceSelection(LCursor & cur)
689 cutSelection(cur, true, false);
693 // only used by the spellchecker
694 void replaceWord(LCursor & cur, string const & replacestring)
696 LyXText * text = cur.text();
699 replaceSelectionWithString(cur, replacestring);
700 setSelectionRange(cur, replacestring.length());
702 // Go back so that replacement string is also spellchecked
703 for (string::size_type i = 0; i < replacestring.length() + 1; ++i)
704 text->cursorLeft(cur);
708 void eraseSelection(LCursor & cur)
710 //lyxerr << "LCursor::eraseSelection begin: " << cur << endl;
711 CursorSlice const & i1 = cur.selBegin();
712 CursorSlice const & i2 = cur.selEnd();
713 if (i1.inset().asMathInset()) {
715 if (i1.idx() == i2.idx()) {
716 i1.cell().erase(i1.pos(), i2.pos());
717 // We may have deleted i1.cell(cur.pos()).
718 // Make sure that pos is valid.
719 if (cur.pos() > cur.lastpos())
720 cur.pos() = cur.lastpos();
722 MathInset * p = i1.asMathInset();
723 InsetBase::row_type r1, r2;
724 InsetBase::col_type c1, c2;
725 region(i1, i2, r1, r2, c1, c2);
726 for (InsetBase::row_type row = r1; row <= r2; ++row)
727 for (InsetBase::col_type col = c1; col <= c2; ++col)
728 p->cell(p->index(row, col)).clear();
729 // We've deleted the whole cell. Only pos 0 is valid.
732 // need a valid cursor. (Lgb)
733 cur.clearSelection();
735 lyxerr << "can't erase this selection 1" << endl;
737 //lyxerr << "LCursor::eraseSelection end: " << cur << endl;
741 void selDel(LCursor & cur)
743 //lyxerr << "LCursor::selDel" << endl;
749 void selClearOrDel(LCursor & cur)
751 //lyxerr << "LCursor::selClearOrDel" << endl;
752 if (lyxrc.auto_region_delete)
755 cur.selection() = false;
759 string grabSelection(LCursor const & cur)
761 if (!cur.selection())
764 // FIXME: What is wrong with the following?
766 std::ostringstream os;
767 for (DocIterator dit = cur.selectionBegin();
768 dit != cur.selectionEnd(); dit.forwardPos())
769 os << asString(dit.cell());
773 CursorSlice i1 = cur.selBegin();
774 CursorSlice i2 = cur.selEnd();
776 if (i1.idx() == i2.idx()) {
777 if (i1.inset().asMathInset()) {
778 MathArray::const_iterator it = i1.cell().begin();
779 return asString(MathArray(it + i1.pos(), it + i2.pos()));
781 return "unknown selection 1";
785 InsetBase::row_type r1, r2;
786 InsetBase::col_type c1, c2;
787 region(i1, i2, r1, r2, c1, c2);
790 if (i1.inset().asMathInset()) {
791 for (InsetBase::row_type row = r1; row <= r2; ++row) {
794 for (InsetBase::col_type col = c1; col <= c2; ++col) {
797 data += asString(i1.asMathInset()->
798 cell(i1.asMathInset()->index(row, col)));
802 data = "unknown selection 2";
808 void dirtyTabularStack(bool b)
810 dirty_tabular_stack_ = b;
814 bool tabularStackDirty()
816 return dirty_tabular_stack_;