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"
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/Gui.h"
49 #include "frontends/LyXView.h"
50 #include "frontends/Clipboard.h"
52 #include <boost/tuple/tuple.hpp>
56 using lyx::textclass_type;
58 using lyx::support::bformat;
60 using lyx::frontend::Gui;
61 using lyx::frontend::Clipboard;
73 typedef std::pair<lyx::pit_type, int> PitPosPair;
75 typedef limited_stack<pair<ParagraphList, textclass_type> > CutStack;
79 // store whether the tabular stack is newer than the normal copy stack
80 // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
81 // when we (hopefully) have a one-for-all paste mechanism.
82 bool dirty_tabular_stack_;
84 class resetParagraph : public std::unary_function<Paragraph, Buffer const &> {
86 resetParagraph(Buffer const & b) : buffer_(b) {}
87 void operator()(Paragraph & p) const {
89 // ERT paragraphs have the Language latex_language.
90 // This is invalid outside of ERT, so we need to change it
91 // to the buffer language.
92 if (p.ownerCode() == InsetBase::ERT_CODE) {
93 p.changeLanguage(buffer_.params(), latex_language,
94 buffer_.getLanguage());
99 Buffer const & buffer_;
103 void region(CursorSlice const & i1, CursorSlice const & i2,
104 InsetBase::row_type & r1, InsetBase::row_type & r2,
105 InsetBase::col_type & c1, InsetBase::col_type & c2)
107 InsetBase & p = i1.inset();
108 c1 = p.col(i1.idx());
109 c2 = p.col(i2.idx());
112 r1 = p.row(i1.idx());
113 r2 = p.row(i2.idx());
119 bool checkPastePossible(int index)
121 return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
125 pair<PitPosPair, pit_type>
126 pasteSelectionHelper(Buffer const & buffer,
127 ParagraphList & pars, pit_type pit, int pos,
128 ParagraphList const & parlist, textclass_type textclass,
129 ErrorList & errorlist)
132 return make_pair(PitPosPair(pit, pos), pit);
134 BOOST_ASSERT (pos <= pars[pit].size());
136 // Make a copy of the CaP paragraphs.
137 ParagraphList insertion = parlist;
138 textclass_type const tc = buffer.params().textclass;
140 // Now remove all out of the pars which is NOT allowed in the
141 // new environment and set also another font if that is required.
143 // Convert newline to paragraph break in ERT inset.
144 // This should not be here!
145 if (pars[pit].inInset() &&
146 pars[pit].inInset()->lyxCode() == InsetBase::ERT_CODE) {
147 for (ParagraphList::size_type i = 0; i < insertion.size(); ++i) {
148 for (pos_type j = 0; j < insertion[i].size(); ++j) {
149 if (insertion[i].isNewline(j)) {
150 insertion[i].erase(j);
151 breakParagraphConservative(
159 // Make sure there is no class difference.
161 // This works without copying any paragraph data because we have
162 // a specialized swap method for ParagraphList. This is important
163 // since we store pointers to insets at some places and we don't
164 // want to invalidate them.
165 insertion.swap(in.paragraphs());
166 lyx::cap::switchBetweenClasses(textclass, tc, in, errorlist);
167 insertion.swap(in.paragraphs());
169 ParagraphList::iterator tmpbuf = insertion.begin();
170 int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
172 Paragraph::depth_type max_depth = pars[pit].getMaxDepthAfter();
174 for (; tmpbuf != insertion.end(); ++tmpbuf) {
175 // If we have a negative jump so that the depth would
176 // go below 0 depth then we have to redo the delta to
177 // this new max depth level so that subsequent
178 // paragraphs are aligned correctly to this paragraph
180 if (int(tmpbuf->params().depth()) + depth_delta < 0)
183 // Set the right depth so that we are not too deep or shallow.
184 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
185 if (tmpbuf->params().depth() > max_depth)
186 tmpbuf->params().depth(max_depth);
188 // Only set this from the 2nd on as the 2nd depends
189 // for maxDepth still on pit.
190 if (tmpbuf != insertion.begin())
191 max_depth = tmpbuf->getMaxDepthAfter();
193 // Set the inset owner of this paragraph.
194 tmpbuf->setInsetOwner(pars[pit].inInset());
195 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
196 if (tmpbuf->getChar(i) == Paragraph::META_INSET &&
197 !pars[pit].insetAllowed(tmpbuf->getInset(i)->lyxCode()))
201 // reset change tracking status
202 if (buffer.params().tracking_changes)
203 tmpbuf->cleanChanges(Paragraph::trackingOn);
205 tmpbuf->cleanChanges(Paragraph::trackingOff);
208 bool const empty = pars[pit].empty();
210 // Make the buf exactly the same layout as the cursor
212 insertion.begin()->makeSameLayout(pars[pit]);
215 // Prepare the paragraphs and insets for insertion.
216 // A couple of insets store buffer references so need updating.
217 insertion.swap(in.paragraphs());
219 ParIterator fpit = par_iterator_begin(in);
220 ParIterator fend = par_iterator_end(in);
222 for (; fpit != fend; ++fpit) {
223 InsetList::iterator lit = fpit->insetlist.begin();
224 InsetList::iterator eit = fpit->insetlist.end();
226 for (; lit != eit; ++lit) {
227 switch (lit->inset->lyxCode()) {
228 case InsetBase::TABULAR_CODE: {
229 InsetTabular * it = static_cast<InsetTabular*>(lit->inset);
239 insertion.swap(in.paragraphs());
241 // Split the paragraph for inserting the buf if necessary.
243 breakParagraphConservative(buffer.params(), pars, pit, pos);
247 pars.insert(boost::next(pars.begin(), pit),
251 // merge the empty par with the last par of the insertion
252 mergeParagraph(buffer.params(), pars,
253 pit + insertion.size() - 1);
255 pars.insert(boost::next(pars.begin(), pit + 1),
259 // merge the first par of the insertion with the current par
260 mergeParagraph(buffer.params(), pars, pit);
263 pit_type last_paste = pit + insertion.size() - 1;
265 // Store the new cursor position.
267 pos = pars[last_paste].size();
269 // Join (conditionally) last pasted paragraph with next one, i.e.,
270 // the tail of the spliced document paragraph
271 if (!empty && last_paste + 1 != pit_type(pars.size())) {
272 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
273 mergeParagraph(buffer.params(), pars, last_paste);
274 } else if (pars[last_paste + 1].empty()) {
275 pars[last_paste + 1].makeSameLayout(pars[last_paste]);
276 mergeParagraph(buffer.params(), pars, last_paste);
277 } else if (pars[last_paste].empty()) {
278 pars[last_paste].makeSameLayout(pars[last_paste + 1]);
279 mergeParagraph(buffer.params(), pars, last_paste);
281 pars[last_paste + 1].stripLeadingSpaces();
286 return make_pair(PitPosPair(pit, pos), last_paste + 1);
290 PitPosPair eraseSelectionHelper(BufferParams const & params,
291 ParagraphList & pars,
292 pit_type startpit, pit_type endpit,
293 int startpos, int endpos, bool doclear)
295 // Start of selection is really invalid.
296 if (startpit == pit_type(pars.size()) ||
297 (startpos > pars[startpit].size()))
298 return PitPosPair(endpit, endpos);
300 // Start and end is inside same paragraph
301 if (endpit == pit_type(pars.size()) ||
302 startpit == endpit) {
303 endpos -= pars[startpit].erase(startpos, endpos);
304 return PitPosPair(endpit, endpos);
307 // A paragraph break has to be physically removed by merging, but
308 // only if either (1) change tracking is off, or (2) the para break
310 for (pit_type pit = startpit; pit != endpit + 1;) {
311 bool const merge = !params.tracking_changes ||
312 pars[pit].lookupChange(pars[pit].size()) ==
314 pos_type const left = ( pit == startpit ? startpos : 0 );
315 pos_type const right = ( pit == endpit ? endpos :
316 pars[pit].size() + 1 );
317 // Logical erase only:
318 pars[pit].erase(left, right);
319 // Separate handling of para break:
320 if (merge && pit != endpit &&
321 (pit + 1 != endpit || pars[pit].hasSameLayout(pars[pit + 1]))) {
322 pos_type const thissize = pars[pit].size();
324 pars[pit + 1].stripLeadingSpaces();
325 mergeParagraph(params, pars, pit);
333 // Ensure legal cursor pos:
336 return PitPosPair(endpit, endpos);
340 void copySelectionHelper(Buffer const & buf, ParagraphList & pars,
341 pit_type startpit, pit_type endpit,
342 int start, int end, textclass_type tc)
344 BOOST_ASSERT(0 <= start && start <= pars[startpit].size());
345 BOOST_ASSERT(0 <= end && end <= pars[endpit].size());
346 BOOST_ASSERT(startpit != endpit || start <= end);
348 // Clone the paragraphs within the selection.
349 ParagraphList paragraphs(boost::next(pars.begin(), startpit),
350 boost::next(pars.begin(), endpit + 1));
352 for_each(paragraphs.begin(), paragraphs.end(), resetParagraph(buf));
354 // Cut out the end of the last paragraph.
355 Paragraph & back = paragraphs.back();
356 back.erase(end, back.size());
358 // Cut out the begin of the first paragraph
359 Paragraph & front = paragraphs.front();
360 front.erase(0, start);
362 theCuts.push(make_pair(paragraphs, tc));
373 string grabAndEraseSelection(LCursor & cur)
375 if (!cur.selection())
377 string 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 lyx::from_utf8(name), lyx::from_utf8(it->layout()->name()),
409 lyx::from_utf8(tclass1.name()), lyx::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 lyx::from_utf8(name), lyx::from_utf8(tclass1.name()),
434 lyx::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<string> const availableSelections(Buffer const & buffer)
451 vector<string> 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, string::npos, "...");
470 selList.push_back(asciiSel);
477 lyx::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 cur.bv().owner()->gui().selection().put. (Lgb)
503 // cur.bv().owner()->gui().selection().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 cur.bv().owner()->gui().clipboard().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;
595 pars.push_back(Paragraph());
596 BufferParams const & bp = cur.buffer().params();
597 pars.back().layout(bp.getLyXTextClass().defaultLayout());
598 for_each(pars.begin(), pars.end(), resetParagraph(cur.buffer()));
599 pars.back().insert(0, grabSelection(cur), LyXFont());
600 theCuts.push(make_pair(pars, bp.textclass));
602 // tell tabular that a recent copy happened
603 dirtyTabularStack(false);
607 std::string 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();
627 boost::tie(ppp, endpit) =
628 pasteSelectionHelper(cur.buffer(),
630 cur.pit(), cur.pos(),
633 updateLabels(cur.buffer());
634 cur.clearSelection();
635 text->setCursor(cur, ppp.first, ppp.second);
638 // mathed is handled in InsetMathNest/InsetMathGrid
639 BOOST_ASSERT(!cur.inMathed());
643 void pasteSelection(LCursor & cur, ErrorList & errorList, size_t sel_index)
645 // this does not make sense, if there is nothing to paste
646 if (!checkPastePossible(sel_index))
649 pasteParagraphList(cur, theCuts[sel_index].first,
650 theCuts[sel_index].second, errorList);
655 // simple replacing. The font of the first selected character is used
656 void replaceSelectionWithString(LCursor & cur, string const & str, bool backwards)
659 DocIterator selbeg = cur.selectionBegin();
661 // Get font setting before we cut
663 selbeg.paragraph().getFontSettings(cur.buffer().params(), selbeg.pos());
665 // Insert the new string
666 pos_type pos = cur.selEnd().pos();
667 Paragraph & par = cur.selEnd().paragraph();
668 string::const_iterator cit = str.begin();
669 string::const_iterator end = str.end();
670 for (; cit != end; ++cit, ++pos)
671 par.insertChar(pos, (*cit), font);
674 cutSelection(cur, true, false);
676 // select the replacement
678 selbeg.pos() += str.length();
679 cur.setSelection(selbeg, -str.length());
681 cur.setSelection(selbeg, str.length());
685 void replaceSelection(LCursor & cur)
688 cutSelection(cur, true, false);
692 void eraseSelection(LCursor & cur)
694 //lyxerr << "LCursor::eraseSelection begin: " << cur << endl;
695 CursorSlice const & i1 = cur.selBegin();
696 CursorSlice const & i2 = cur.selEnd();
697 if (i1.inset().asInsetMath()) {
699 if (i1.idx() == i2.idx()) {
700 i1.cell().erase(i1.pos(), i2.pos());
701 // We may have deleted i1.cell(cur.pos()).
702 // Make sure that pos is valid.
703 if (cur.pos() > cur.lastpos())
704 cur.pos() = cur.lastpos();
706 InsetMath * p = i1.asInsetMath();
707 InsetBase::row_type r1, r2;
708 InsetBase::col_type c1, c2;
709 region(i1, i2, r1, r2, c1, c2);
710 for (InsetBase::row_type row = r1; row <= r2; ++row)
711 for (InsetBase::col_type col = c1; col <= c2; ++col)
712 p->cell(p->index(row, col)).clear();
713 // We've deleted the whole cell. Only pos 0 is valid.
716 // need a valid cursor. (Lgb)
717 cur.clearSelection();
719 lyxerr << "can't erase this selection 1" << endl;
721 //lyxerr << "LCursor::eraseSelection end: " << cur << endl;
725 void selDel(LCursor & cur)
727 //lyxerr << "LCursor::selDel" << endl;
733 void selClearOrDel(LCursor & cur)
735 //lyxerr << "LCursor::selClearOrDel" << endl;
736 if (lyxrc.auto_region_delete)
739 cur.selection() = false;
743 string grabSelection(LCursor const & cur)
745 if (!cur.selection())
748 // FIXME: What is wrong with the following?
750 std::ostringstream os;
751 for (DocIterator dit = cur.selectionBegin();
752 dit != cur.selectionEnd(); dit.forwardPos())
753 os << asString(dit.cell());
757 CursorSlice i1 = cur.selBegin();
758 CursorSlice i2 = cur.selEnd();
760 if (i1.idx() == i2.idx()) {
761 if (i1.inset().asInsetMath()) {
762 MathArray::const_iterator it = i1.cell().begin();
763 return asString(MathArray(it + i1.pos(), it + i2.pos()));
765 return "unknown selection 1";
769 InsetBase::row_type r1, r2;
770 InsetBase::col_type c1, c2;
771 region(i1, i2, r1, r2, c1, c2);
774 if (i1.inset().asInsetMath()) {
775 for (InsetBase::row_type row = r1; row <= r2; ++row) {
778 for (InsetBase::col_type col = c1; col <= c2; ++col) {
781 data += asString(i1.asInsetMath()->
782 cell(i1.asInsetMath()->index(row, col)));
786 data = "unknown selection 2";
792 void dirtyTabularStack(bool b)
794 dirty_tabular_stack_ = b;
798 bool tabularStackDirty()
800 return dirty_tabular_stack_;