]> git.lyx.org Git - lyx.git/blob - src/CutAndPaste.C
A better fix for bug 675:
[lyx.git] / src / CutAndPaste.C
1 /*
2  * \file CutAndPaste.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Jürgen Vigna
7  * \author Lars Gullik Bjønnes
8  * \author Alfredo Braunstein
9  * \author Michael Gerz
10  *
11  * Full author contact details are available in file CREDITS.
12  */
13
14 #include <config.h>
15
16 #include "CutAndPaste.h"
17
18 #include "buffer.h"
19 #include "buffer_funcs.h"
20 #include "bufferparams.h"
21 #include "cursor.h"
22 #include "debug.h"
23 #include "errorlist.h"
24 #include "funcrequest.h"
25 #include "gettext.h"
26 #include "insetiterator.h"
27 #include "language.h"
28 #include "lfuns.h"
29 #include "lyxfunc.h"
30 #include "lyxrc.h"
31 #include "lyxtext.h"
32 #include "lyxtextclasslist.h"
33 #include "paragraph.h"
34 #include "paragraph_funcs.h"
35 #include "ParagraphParameters.h"
36 #include "ParagraphList_fwd.h"
37 #include "pariterator.h"
38 #include "undo.h"
39
40 #include "insets/insetcharstyle.h"
41 #include "insets/insettabular.h"
42
43 #include "mathed/MathData.h"
44 #include "mathed/InsetMath.h"
45 #include "mathed/MathSupport.h"
46
47 #include "support/lstrings.h"
48
49 #include "frontends/Clipboard.h"
50 #include "frontends/Selection.h"
51
52 #include <boost/tuple/tuple.hpp>
53
54 #include <string>
55
56 using std::endl;
57 using std::for_each;
58 using std::make_pair;
59 using std::pair;
60 using std::vector;
61 using std::string;
62
63
64 namespace lyx {
65
66 using support::bformat;
67 using frontend::Clipboard;
68
69 namespace {
70
71 typedef std::pair<pit_type, int> PitPosPair;
72
73 typedef limited_stack<pair<ParagraphList, textclass_type> > CutStack;
74
75 CutStack theCuts(10);
76
77 // store whether the tabular stack is newer than the normal copy stack
78 // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
79 // when we (hopefully) have a one-for-all paste mechanism.
80 bool dirty_tabular_stack_ = false;
81
82
83 void region(CursorSlice const & i1, CursorSlice const & i2,
84         InsetBase::row_type & r1, InsetBase::row_type & r2,
85         InsetBase::col_type & c1, InsetBase::col_type & c2)
86 {
87         InsetBase & p = i1.inset();
88         c1 = p.col(i1.idx());
89         c2 = p.col(i2.idx());
90         if (c1 > c2)
91                 std::swap(c1, c2);
92         r1 = p.row(i1.idx());
93         r2 = p.row(i2.idx());
94         if (r1 > r2)
95                 std::swap(r1, r2);
96 }
97
98
99 bool checkPastePossible(int index)
100 {
101         return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
102 }
103
104
105 pair<PitPosPair, pit_type>
106 pasteSelectionHelper(LCursor & cur, ParagraphList const & parlist,
107                      textclass_type textclass, ErrorList & errorlist)
108 {
109         Buffer const & buffer = cur.buffer();
110         pit_type pit = cur.pit();
111         pos_type pos = cur.pos();
112         ParagraphList & pars = cur.text()->paragraphs();
113
114         if (parlist.empty())
115                 return make_pair(PitPosPair(pit, pos), pit);
116
117         BOOST_ASSERT (pos <= pars[pit].size());
118
119         // Make a copy of the CaP paragraphs.
120         ParagraphList insertion = parlist;
121         textclass_type const tc = buffer.params().textclass;
122
123         // Now remove all out of the pars which is NOT allowed in the
124         // new environment and set also another font if that is required.
125
126         // Convert newline to paragraph break in ERT inset.
127         // This should not be here!
128         if (pars[pit].inInset() &&
129             pars[pit].inInset()->lyxCode() == InsetBase::ERT_CODE) {
130                 for (ParagraphList::size_type i = 0; i < insertion.size(); ++i) {
131                         for (pos_type j = 0; j < insertion[i].size(); ++j) {
132                                 if (insertion[i].isNewline(j)) {
133                                         // do not track deletion of newline
134                                         insertion[i].eraseChar(j, false);
135                                         breakParagraphConservative(
136                                                         buffer.params(),
137                                                         insertion, i, j);
138                                 }
139                         }
140                 }
141         }
142
143         // If we are in an inset which returns forceDefaultParagraphs,
144         // set the paragraphs to default
145         if (cur.inset().forceDefaultParagraphs(cur.idx())) {
146                 LyXLayout_ptr const layout = 
147                         buffer.params().getLyXTextClass().defaultLayout();
148                 ParagraphList::iterator const end = insertion.end();
149                 for (ParagraphList::iterator par = insertion.begin(); 
150                                 par != end; ++par)
151                         par->layout(layout);
152         }
153
154         // Make sure there is no class difference.
155         InsetText in;
156         // This works without copying any paragraph data because we have
157         // a specialized swap method for ParagraphList. This is important
158         // since we store pointers to insets at some places and we don't
159         // want to invalidate them.
160         insertion.swap(in.paragraphs());
161         cap::switchBetweenClasses(textclass, tc, in, errorlist);
162         insertion.swap(in.paragraphs());
163
164         ParagraphList::iterator tmpbuf = insertion.begin();
165         int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
166
167         depth_type max_depth = pars[pit].getMaxDepthAfter();
168
169         for (; tmpbuf != insertion.end(); ++tmpbuf) {
170                 // If we have a negative jump so that the depth would
171                 // go below 0 depth then we have to redo the delta to
172                 // this new max depth level so that subsequent
173                 // paragraphs are aligned correctly to this paragraph
174                 // at level 0.
175                 if (int(tmpbuf->params().depth()) + depth_delta < 0)
176                         depth_delta = 0;
177
178                 // Set the right depth so that we are not too deep or shallow.
179                 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
180                 if (tmpbuf->params().depth() > max_depth)
181                         tmpbuf->params().depth(max_depth);
182
183                 // Only set this from the 2nd on as the 2nd depends
184                 // for maxDepth still on pit.
185                 if (tmpbuf != insertion.begin())
186                         max_depth = tmpbuf->getMaxDepthAfter();
187
188                 // Set the inset owner of this paragraph.
189                 tmpbuf->setInsetOwner(pars[pit].inInset());
190                 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
191                         if (tmpbuf->getChar(i) == Paragraph::META_INSET &&
192                             !pars[pit].insetAllowed(tmpbuf->getInset(i)->lyxCode()))
193                                 // do not track deletion of invalid insets
194                                 tmpbuf->eraseChar(i--, false);
195                 }
196
197                 tmpbuf->setChange(Change(buffer.params().trackChanges ?
198                                          Change::INSERTED : Change::UNCHANGED));
199         }
200
201         bool const empty = pars[pit].empty();
202         if (!empty) {
203                 // Make the buf exactly the same layout as the cursor
204                 // paragraph.
205                 insertion.begin()->makeSameLayout(pars[pit]);
206         }
207
208         // Prepare the paragraphs and insets for insertion.
209         // A couple of insets store buffer references so need updating.
210         insertion.swap(in.paragraphs());
211
212         ParIterator fpit = par_iterator_begin(in);
213         ParIterator fend = par_iterator_end(in);
214
215         for (; fpit != fend; ++fpit) {
216                 InsetList::const_iterator lit = fpit->insetlist.begin();
217                 InsetList::const_iterator eit = fpit->insetlist.end();
218
219                 for (; lit != eit; ++lit) {
220                         switch (lit->inset->lyxCode()) {
221                         case InsetBase::TABULAR_CODE: {
222                                 InsetTabular * it = static_cast<InsetTabular*>(lit->inset);
223                                 it->buffer(&buffer);
224                                 break;
225                         }
226
227                         default:
228                                 break; // nothing
229                         }
230                 }
231         }
232         insertion.swap(in.paragraphs());
233
234         // Split the paragraph for inserting the buf if necessary.
235         if (!empty)
236                 breakParagraphConservative(buffer.params(), pars, pit, pos);
237
238         // Paste it!
239         if (empty) {
240                 pars.insert(boost::next(pars.begin(), pit),
241                             insertion.begin(),
242                             insertion.end());
243
244                 // merge the empty par with the last par of the insertion
245                 mergeParagraph(buffer.params(), pars,
246                                pit + insertion.size() - 1);
247         } else {
248                 pars.insert(boost::next(pars.begin(), pit + 1),
249                             insertion.begin(),
250                             insertion.end());
251
252                 // merge the first par of the insertion with the current par
253                 mergeParagraph(buffer.params(), pars, pit);
254         }
255
256         pit_type last_paste = pit + insertion.size() - 1;
257
258         // Store the new cursor position.
259         pit = last_paste;
260         pos = pars[last_paste].size();
261
262         // Join (conditionally) last pasted paragraph with next one, i.e.,
263         // the tail of the spliced document paragraph
264         if (!empty && last_paste + 1 != pit_type(pars.size())) {
265                 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
266                         mergeParagraph(buffer.params(), pars, last_paste);
267                 } else if (pars[last_paste + 1].empty()) {
268                         pars[last_paste + 1].makeSameLayout(pars[last_paste]);
269                         mergeParagraph(buffer.params(), pars, last_paste);
270                 } else if (pars[last_paste].empty()) {
271                         pars[last_paste].makeSameLayout(pars[last_paste + 1]);
272                         mergeParagraph(buffer.params(), pars, last_paste);
273                 } else {
274                         pars[last_paste + 1].stripLeadingSpaces(buffer.params().trackChanges);
275                         ++last_paste;
276                 }
277         }
278
279         return make_pair(PitPosPair(pit, pos), last_paste + 1);
280 }
281
282
283 PitPosPair eraseSelectionHelper(BufferParams const & params,
284         ParagraphList & pars,
285         pit_type startpit, pit_type endpit,
286         int startpos, int endpos, bool doclear)
287 {
288         // Start of selection is really invalid.
289         if (startpit == pit_type(pars.size()) ||
290             (startpos > pars[startpit].size()))
291                 return PitPosPair(endpit, endpos);
292
293         // Start and end is inside same paragraph
294         if (endpit == pit_type(pars.size()) || startpit == endpit) {
295                 endpos -= pars[startpit].eraseChars(startpos, endpos, params.trackChanges);
296                 return PitPosPair(endpit, endpos);
297         }
298
299         for (pit_type pit = startpit; pit != endpit + 1;) {
300                 pos_type const left  = (pit == startpit ? startpos : 0);
301                 pos_type const right = (pit == endpit ? endpos : pars[pit].size() + 1);
302
303                 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.trackChanges);
304
305                 // Logically erase only, including the end-of-paragraph character
306                 pars[pit].eraseChars(left, right, params.trackChanges);
307
308                 // Separate handling of paragraph break:
309                 if (merge && pit != endpit &&
310                     (pit + 1 != endpit || pars[pit].hasSameLayout(pars[pit + 1]))) {
311                         pos_type const thissize = pars[pit].size();
312                         if (doclear)
313                                 pars[pit + 1].stripLeadingSpaces(params.trackChanges);
314                         mergeParagraph(params, pars, pit);
315                         --endpit;
316                         if (pit == endpit)
317                                 endpos += thissize;
318                 } else
319                         ++pit;
320         }
321
322         // Ensure legal cursor pos:
323         endpit = startpit;
324         endpos = startpos;
325         return PitPosPair(endpit, endpos);
326 }
327
328
329 void putClipboard(ParagraphList const & paragraphs, textclass_type textclass,
330                   docstring const & plaintext)
331 {
332         Buffer buffer(string(), false);
333         buffer.setUnnamed(true);
334         buffer.paragraphs() = paragraphs;
335         buffer.params().textclass = textclass;
336         std::ostringstream lyx;
337         if (buffer.write(lyx))
338                 theClipboard().put(lyx.str(), plaintext);
339         else
340                 theClipboard().put(string(), plaintext);
341 }
342
343
344 void copySelectionHelper(Buffer const & buf, ParagraphList & pars,
345         pit_type startpit, pit_type endpit,
346         int start, int end, textclass_type tc)
347 {
348         BOOST_ASSERT(0 <= start && start <= pars[startpit].size());
349         BOOST_ASSERT(0 <= end && end <= pars[endpit].size());
350         BOOST_ASSERT(startpit != endpit || start <= end);
351
352         // Clone the paragraphs within the selection.
353         ParagraphList paragraphs(boost::next(pars.begin(), startpit),
354                                  boost::next(pars.begin(), endpit + 1));
355
356         ParagraphList::iterator it = paragraphs.begin();
357         ParagraphList::iterator it_end = paragraphs.end();
358
359         for (; it != it_end; it++) {
360                 // ERT paragraphs have the Language latex_language.
361                 // This is invalid outside of ERT, so we need to change it
362                 // to the buffer language.
363                 if (it->ownerCode() == InsetBase::ERT_CODE) {
364                         it->changeLanguage(buf.params(), latex_language,
365                                            buf.getLanguage());
366                 }
367                 it->setInsetOwner(0);
368         }
369
370         // Cut out the end of the last paragraph.
371         Paragraph & back = paragraphs.back();
372         // do not track deletion here; it is an internal action not visible to the user
373         back.eraseChars(end, back.size(), false);
374
375         // Cut out the begin of the first paragraph
376         Paragraph & front = paragraphs.front();
377         // again, do not track deletion
378         front.eraseChars(0, start, false);
379
380         theCuts.push(make_pair(paragraphs, tc));
381 }
382
383 } // namespace anon
384
385
386
387
388 namespace cap {
389
390 docstring grabAndEraseSelection(LCursor & cur)
391 {
392         if (!cur.selection())
393                 return docstring();
394         docstring res = grabSelection(cur);
395         eraseSelection(cur);
396         return res;
397 }
398
399
400 void switchBetweenClasses(textclass_type c1, textclass_type c2,
401         InsetText & in, ErrorList & errorlist)
402 {
403         BOOST_ASSERT(!in.paragraphs().empty());
404         if (c1 == c2)
405                 return;
406
407         LyXTextClass const & tclass1 = textclasslist[c1];
408         LyXTextClass const & tclass2 = textclasslist[c2];
409
410         // layouts
411         ParIterator end = par_iterator_end(in);
412         for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
413                 string const name = it->layout()->name();
414                 bool hasLayout = tclass2.hasLayout(name);
415
416                 if (hasLayout)
417                         it->layout(tclass2[name]);
418                 else
419                         it->layout(tclass2.defaultLayout());
420
421                 if (!hasLayout && name != tclass1.defaultLayoutName()) {
422                         docstring const s = bformat(
423                                                  _("Layout had to be changed from\n%1$s to %2$s\n"
424                                                 "because of class conversion from\n%3$s to %4$s"),
425                          from_utf8(name), from_utf8(it->layout()->name()),
426                          from_utf8(tclass1.name()), from_utf8(tclass2.name()));
427                         // To warn the user that something had to be done.
428                         errorlist.push_back(ErrorItem(_("Changed Layout"), s,
429                                                       it->id(), 0,
430                                                       it->size()));
431                 }
432         }
433
434         // character styles
435         InsetIterator const i_end = inset_iterator_end(in);
436         for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
437                 if (it->lyxCode() == InsetBase::CHARSTYLE_CODE) {
438                         InsetCharStyle & inset =
439                                 static_cast<InsetCharStyle &>(*it);
440                         string const name = inset.params().type;
441                         CharStyles::iterator const found_cs =
442                                 tclass2.charstyle(name);
443                         if (found_cs == tclass2.charstyles().end()) {
444                                 // The character style is undefined in tclass2
445                                 inset.setUndefined();
446                                 docstring const s = bformat(_(
447                                         "Character style %1$s is "
448                                         "undefined because of class "
449                                         "conversion from\n%2$s to %3$s"),
450                                          from_utf8(name), from_utf8(tclass1.name()),
451                                          from_utf8(tclass2.name()));
452                                 // To warn the user that something had to be done.
453                                 errorlist.push_back(ErrorItem(
454                                         _("Undefined character style"),
455                                         s, it.paragraph().id(), it.pos(), it.pos() + 1));
456                         } else if (inset.undefined()) {
457                                 // The character style is undefined in
458                                 // tclass1 and is defined in tclass2
459                                 inset.setDefined(found_cs);
460                         }
461                 }
462         }
463 }
464
465
466 std::vector<docstring> const availableSelections(Buffer const & buffer)
467 {
468         vector<docstring> selList;
469
470         CutStack::const_iterator cit = theCuts.begin();
471         CutStack::const_iterator end = theCuts.end();
472         for (; cit != end; ++cit) {
473                 // we do not use cit-> here because gcc 2.9x does not
474                 // like it (JMarc)
475                 ParagraphList const & pars = (*cit).first;
476                 docstring asciiSel;
477                 ParagraphList::const_iterator pit = pars.begin();
478                 ParagraphList::const_iterator pend = pars.end();
479                 for (; pit != pend; ++pit) {
480                         asciiSel += pit->asString(buffer, false);
481                         if (asciiSel.size() > 25) {
482                                 asciiSel.replace(22, docstring::npos,
483                                                  from_ascii("..."));
484                                 break;
485                         }
486                 }
487
488                 selList.push_back(asciiSel);
489         }
490
491         return selList;
492 }
493
494
495 size_type numberOfSelections()
496 {
497         return theCuts.size();
498 }
499
500
501 void cutSelection(LCursor & cur, bool doclear, bool realcut)
502 {
503         // This doesn't make sense, if there is no selection
504         if (!cur.selection())
505                 return;
506
507         // OK, we have a selection. This is always between cur.selBegin()
508         // and cur.selEnd()
509
510         if (cur.inTexted()) {
511                 LyXText * text = cur.text();
512                 BOOST_ASSERT(text);
513
514                 // make sure that the depth behind the selection are restored, too
515                 recordUndoSelection(cur);
516                 pit_type begpit = cur.selBegin().pit();
517                 pit_type endpit = cur.selEnd().pit();
518
519                 int endpos = cur.selEnd().pos();
520
521                 BufferParams const & bp = cur.buffer().params();
522                 if (realcut) {
523                         copySelectionHelper(cur.buffer(),
524                                 text->paragraphs(),
525                                 begpit, endpit,
526                                 cur.selBegin().pos(), endpos,
527                                 bp.textclass);
528                         // Stuff what we got on the clipboard.
529                         // Even if there is no selection.
530                         putClipboard(theCuts[0].first, theCuts[0].second,
531                                 cur.selectionAsString(true));
532                 }
533
534                 boost::tie(endpit, endpos) =
535                         eraseSelectionHelper(bp,
536                                 text->paragraphs(),
537                                 begpit, endpit,
538                                 cur.selBegin().pos(), endpos,
539                                 doclear);
540
541                 // sometimes necessary
542                 if (doclear)
543                         text->paragraphs()[begpit].stripLeadingSpaces(bp.trackChanges);
544
545                 // cutSelection can invalidate the cursor so we need to set
546                 // it anew. (Lgb)
547                 // we prefer the end for when tracking changes
548                 cur.pos() = endpos;
549                 cur.pit() = endpit;
550
551                 // need a valid cursor. (Lgb)
552                 cur.clearSelection();
553                 updateLabels(cur.buffer());
554                 theSelection().haveSelection(false);
555
556                 // tell tabular that a recent copy happened
557                 dirtyTabularStack(false);
558         }
559
560         if (cur.inMathed()) {
561                 if (cur.selBegin().idx() != cur.selEnd().idx()) {
562                         // The current selection spans more than one cell.
563                         // Record all cells
564                         recordUndoInset(cur);
565                 } else {
566                         // Record only the current cell to avoid a jumping
567                         // cursor after undo
568                         recordUndo(cur);
569                 }
570                 if (realcut)
571                         copySelection(cur);
572                 eraseSelection(cur);
573         }
574 }
575
576
577 void copySelection(LCursor & cur)
578 {
579         copySelection(cur, cur.selectionAsString(true));
580 }
581
582
583 void copySelection(LCursor & cur, docstring const & plaintext)
584 {
585         copySelectionToStack(cur);
586
587         // stuff the selection onto the X clipboard, from an explicit copy request
588         putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
589 }
590
591
592 void copySelectionToStack(LCursor & cur)
593 {
594         // this doesn't make sense, if there is no selection
595         if (!cur.selection())
596                 return;
597
598         if (cur.inTexted()) {
599                 LyXText * text = cur.text();
600                 BOOST_ASSERT(text);
601                 // ok we have a selection. This is always between cur.selBegin()
602                 // and sel_end cursor
603
604                 // copy behind a space if there is one
605                 ParagraphList & pars = text->paragraphs();
606                 pos_type pos = cur.selBegin().pos();
607                 pit_type par = cur.selBegin().pit();
608                 while (pos < pars[par].size()
609                                          && pars[par].isLineSeparator(pos)
610                                          && (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
611                         ++pos;
612
613                 copySelectionHelper(cur.buffer(), pars, par, cur.selEnd().pit(),
614                         pos, cur.selEnd().pos(), cur.buffer().params().textclass);
615         }
616
617         if (cur.inMathed()) {
618                 //lyxerr << "copySelection in mathed" << endl;
619                 ParagraphList pars;
620                 Paragraph par;
621                 BufferParams const & bp = cur.buffer().params();
622                 par.layout(bp.getLyXTextClass().defaultLayout());
623                 par.insert(0, grabSelection(cur), LyXFont(), Change(Change::UNCHANGED));
624                 pars.push_back(par);
625                 theCuts.push(make_pair(pars, bp.textclass));
626         }
627         // tell tabular that a recent copy happened
628         dirtyTabularStack(false);
629 }
630
631
632 docstring getSelection(Buffer const & buf, size_t sel_index)
633 {
634         return sel_index < theCuts.size()
635                 ? theCuts[sel_index].first.back().asString(buf, false)
636                 : docstring();
637 }
638
639
640 void pasteParagraphList(LCursor & cur, ParagraphList const & parlist,
641                         textclass_type textclass, ErrorList & errorList)
642 {
643         if (cur.inTexted()) {
644                 LyXText * text = cur.text();
645                 BOOST_ASSERT(text);
646
647                 pit_type endpit;
648                 PitPosPair ppp;
649
650                 boost::tie(ppp, endpit) =
651                         pasteSelectionHelper(cur, parlist,
652                                              textclass, errorList);
653                 updateLabels(cur.buffer());
654                 cur.clearSelection();
655                 text->setCursor(cur.top(), ppp.first, ppp.second);
656         }
657
658         // mathed is handled in InsetMathNest/InsetMathGrid
659         BOOST_ASSERT(!cur.inMathed());
660 }
661
662
663 void pasteClipboard(LCursor & cur, ErrorList & errorList, bool asParagraphs)
664 {
665         // Use internal clipboard if it is the most recent one
666         if (theClipboard().isInternal()) {
667                 pasteSelection(cur, errorList, 0);
668                 return;
669         }
670
671         // First try LyX format
672         if (theClipboard().hasLyXContents()) {
673                 string lyx = theClipboard().getAsLyX();
674                 if (!lyx.empty()) {
675                         Buffer buffer(string(), false);
676                         buffer.setUnnamed(true);
677                         if (buffer.readString(lyx)) {
678                                 recordUndo(cur);
679                                 pasteParagraphList(cur, buffer.paragraphs(),
680                                         buffer.params().textclass, errorList);
681                                 cur.setSelection();
682                                 return;
683                         }
684                 }
685         }
686
687         // Then try plain text
688         docstring const text = theClipboard().getAsText();
689         if (text.empty())
690                 return;
691         recordUndo(cur);
692         if (asParagraphs)
693                 cur.text()->insertStringAsParagraphs(cur, text);
694         else
695                 cur.text()->insertStringAsLines(cur, text);
696 }
697
698
699 void pasteSelection(LCursor & cur, ErrorList & errorList, size_t sel_index)
700 {
701         // this does not make sense, if there is nothing to paste
702         if (!checkPastePossible(sel_index))
703                 return;
704
705         recordUndo(cur);
706         pasteParagraphList(cur, theCuts[sel_index].first,
707                            theCuts[sel_index].second, errorList);
708         cur.setSelection();
709 }
710
711
712 void replaceSelectionWithString(LCursor & cur, docstring const & str, bool backwards)
713 {
714         recordUndo(cur);
715         DocIterator selbeg = cur.selectionBegin();
716
717         // Get font setting before we cut
718         LyXFont const font =
719                 selbeg.paragraph().getFontSettings(cur.buffer().params(), selbeg.pos());
720
721         // Insert the new string
722         pos_type pos = cur.selEnd().pos();
723         Paragraph & par = cur.selEnd().paragraph();
724         docstring::const_iterator cit = str.begin();
725         docstring::const_iterator end = str.end();
726         for (; cit != end; ++cit, ++pos)
727                 par.insertChar(pos, *cit, font, cur.buffer().params().trackChanges);
728
729         // Cut the selection
730         cutSelection(cur, true, false);
731
732         // select the replacement
733         if (backwards) {
734                 selbeg.pos() += str.length();
735                 cur.setSelection(selbeg, -int(str.length()));
736         } else
737                 cur.setSelection(selbeg, str.length());
738 }
739
740
741 void replaceSelection(LCursor & cur)
742 {
743         if (cur.selection())
744                 cutSelection(cur, true, false);
745 }
746
747
748 void eraseSelection(LCursor & cur)
749 {
750         //lyxerr << "cap::eraseSelection begin: " << cur << endl;
751         CursorSlice const & i1 = cur.selBegin();
752         CursorSlice const & i2 = cur.selEnd();
753         if (i1.inset().asInsetMath()) {
754                 cur.top() = i1;
755                 if (i1.idx() == i2.idx()) {
756                         i1.cell().erase(i1.pos(), i2.pos());
757                         // We may have deleted i1.cell(cur.pos()).
758                         // Make sure that pos is valid.
759                         if (cur.pos() > cur.lastpos())
760                                 cur.pos() = cur.lastpos();
761                 } else {
762                         InsetMath * p = i1.asInsetMath();
763                         InsetBase::row_type r1, r2;
764                         InsetBase::col_type c1, c2;
765                         region(i1, i2, r1, r2, c1, c2);
766                         for (InsetBase::row_type row = r1; row <= r2; ++row)
767                                 for (InsetBase::col_type col = c1; col <= c2; ++col)
768                                         p->cell(p->index(row, col)).clear();
769                         // We've deleted the whole cell. Only pos 0 is valid.
770                         cur.pos() = 0;
771                 }
772                 // need a valid cursor. (Lgb)
773                 cur.clearSelection();
774                 theSelection().haveSelection(false);
775         } else {
776                 lyxerr << "can't erase this selection 1" << endl;
777         }
778         //lyxerr << "cap::eraseSelection end: " << cur << endl;
779 }
780
781
782 void selDel(LCursor & cur)
783 {
784         //lyxerr << "cap::selDel" << endl;
785         if (cur.selection())
786                 eraseSelection(cur);
787 }
788
789
790 void selClearOrDel(LCursor & cur)
791 {
792         //lyxerr << "cap::selClearOrDel" << endl;
793         if (lyxrc.auto_region_delete)
794                 selDel(cur);
795         else
796                 cur.selection() = false;
797 }
798
799
800 docstring grabSelection(LCursor const & cur)
801 {
802         if (!cur.selection())
803                 return docstring();
804
805         // FIXME: What is wrong with the following?
806 #if 0
807         std::ostringstream os;
808         for (DocIterator dit = cur.selectionBegin();
809              dit != cur.selectionEnd(); dit.forwardPos())
810                 os << asString(dit.cell());
811         return os.str();
812 #endif
813
814         CursorSlice i1 = cur.selBegin();
815         CursorSlice i2 = cur.selEnd();
816
817         if (i1.idx() == i2.idx()) {
818                 if (i1.inset().asInsetMath()) {
819                         MathArray::const_iterator it = i1.cell().begin();
820                         return asString(MathArray(it + i1.pos(), it + i2.pos()));
821                 } else {
822                         return from_ascii("unknown selection 1");
823                 }
824         }
825
826         InsetBase::row_type r1, r2;
827         InsetBase::col_type c1, c2;
828         region(i1, i2, r1, r2, c1, c2);
829
830         docstring data;
831         if (i1.inset().asInsetMath()) {
832                 for (InsetBase::row_type row = r1; row <= r2; ++row) {
833                         if (row > r1)
834                                 data += "\\\\";
835                         for (InsetBase::col_type col = c1; col <= c2; ++col) {
836                                 if (col > c1)
837                                         data += '&';
838                                 data += asString(i1.asInsetMath()->
839                                         cell(i1.asInsetMath()->index(row, col)));
840                         }
841                 }
842         } else {
843                 data = from_ascii("unknown selection 2");
844         }
845         return data;
846 }
847
848
849 void dirtyTabularStack(bool b)
850 {
851         dirty_tabular_stack_ = b;
852 }
853
854
855 bool tabularStackDirty()
856 {
857         return dirty_tabular_stack_;
858 }
859
860
861 } // namespace cap
862
863 } // namespace lyx