]> git.lyx.org Git - lyx.git/blob - src/CutAndPaste.C
Fix crash that occurs if the cursor is in a table cell when the document class
[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  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 #include <config.h>
14
15 #include "CutAndPaste.h"
16
17 #include "buffer.h"
18 #include "buffer_funcs.h"
19 #include "bufferparams.h"
20 #include "BufferView.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 "lyxrc.h"
30 #include "lyxtext.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"
37 #include "undo.h"
38
39 #include "insets/insetcharstyle.h"
40 #include "insets/insettabular.h"
41
42 #include "mathed/math_data.h"
43 #include "mathed/math_inset.h"
44 #include "mathed/math_support.h"
45
46 #include "support/lstrings.h"
47
48 #include <boost/tuple/tuple.hpp>
49
50 using lyx::pos_type;
51 using lyx::pit_type;
52 using lyx::textclass_type;
53
54 using lyx::support::bformat;
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 {
65
66 typedef std::pair<lyx::pit_type, int> PitPosPair;
67
68 typedef limited_stack<pair<ParagraphList, textclass_type> > CutStack;
69
70 CutStack theCuts(10);
71
72 // store whether the tabular stack is newer than the normal copy stack
73 // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
74 // when we (hopefully) have a one-for-all paste mechanism.
75 bool dirty_tabular_stack_;
76
77 class resetParagraph : public std::unary_function<Paragraph, Buffer const &> {
78 public:
79         resetParagraph(Buffer const & b) : buffer_(b) {}
80         void operator()(Paragraph & p) const {
81                 p.cleanChanges();
82                 // ERT paragraphs have the Language latex_language.
83                 // This is invalid outside of ERT, so we need to change it
84                 // to the buffer language.
85                 if (p.ownerCode() == InsetBase::ERT_CODE) {
86                         p.changeLanguage(buffer_.params(), latex_language,
87                                          buffer_.getLanguage());
88                 }
89                 p.setInsetOwner(0);
90         }
91 private:
92         Buffer const & buffer_;
93 };
94
95
96 void region(CursorSlice const & i1, CursorSlice const & i2,
97         InsetBase::row_type & r1, InsetBase::row_type & r2,
98         InsetBase::col_type & c1, InsetBase::col_type & c2)
99 {
100         InsetBase & p = i1.inset();
101         c1 = p.col(i1.idx());
102         c2 = p.col(i2.idx());
103         if (c1 > c2)
104                 std::swap(c1, c2);
105         r1 = p.row(i1.idx());
106         r2 = p.row(i2.idx());
107         if (r1 > r2)
108                 std::swap(r1, r2);
109 }
110
111
112 bool checkPastePossible(int index)
113 {
114         return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
115 }
116
117
118 pair<PitPosPair, pit_type>
119 pasteSelectionHelper(Buffer const & buffer,
120                      ParagraphList & pars, pit_type pit, int pos,
121                      ParagraphList const & parlist, textclass_type textclass,
122                      ErrorList & errorlist)
123 {
124         if (parlist.empty())
125                 return make_pair(PitPosPair(pit, pos), pit);
126
127         BOOST_ASSERT (pos <= pars[pit].size());
128
129         // Make a copy of the CaP paragraphs.
130         ParagraphList insertion = parlist;
131         textclass_type const tc = buffer.params().textclass;
132
133         // Now remove all out of the pars which is NOT allowed in the
134         // new environment and set also another font if that is required.
135
136         // Convert newline to paragraph break in ERT inset.
137         // This should not be here!
138         if (pars[pit].inInset() &&
139             pars[pit].inInset()->lyxCode() == InsetBase::ERT_CODE) {
140                 for (ParagraphList::size_type i = 0; i < insertion.size(); ++i) {
141                         for (pos_type j = 0; j < insertion[i].size(); ++j) {
142                                 if (insertion[i].isNewline(j)) {
143                                         insertion[i].erase(j);
144                                         breakParagraphConservative(
145                                                         buffer.params(),
146                                                         insertion, i, j);
147                                 }
148                         }
149                 }
150         }
151
152         // Make sure there is no class difference.
153         InsetText in;
154         // This works without copying any paragraph data because we have
155         // a specialized swap method for ParagraphList. This is important
156         // since we store pointers to insets at some places and we don't
157         // want to invalidate them.
158         insertion.swap(in.paragraphs());
159         lyx::cap::switchBetweenClasses(textclass, tc, in, errorlist);
160         insertion.swap(in.paragraphs());
161
162         ParagraphList::iterator tmpbuf = insertion.begin();
163         int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
164
165         Paragraph::depth_type max_depth = pars[pit].getMaxDepthAfter();
166
167         for (; tmpbuf != insertion.end(); ++tmpbuf) {
168                 // If we have a negative jump so that the depth would
169                 // go below 0 depth then we have to redo the delta to
170                 // this new max depth level so that subsequent
171                 // paragraphs are aligned correctly to this paragraph
172                 // at level 0.
173                 if (int(tmpbuf->params().depth()) + depth_delta < 0)
174                         depth_delta = 0;
175
176                 // Set the right depth so that we are not too deep or shallow.
177                 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
178                 if (tmpbuf->params().depth() > max_depth)
179                         tmpbuf->params().depth(max_depth);
180
181                 // Only set this from the 2nd on as the 2nd depends
182                 // for maxDepth still on pit.
183                 if (tmpbuf != insertion.begin())
184                         max_depth = tmpbuf->getMaxDepthAfter();
185
186                 // Set the inset owner of this paragraph.
187                 tmpbuf->setInsetOwner(pars[pit].inInset());
188                 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
189                         if (tmpbuf->getChar(i) == Paragraph::META_INSET &&
190                             !pars[pit].insetAllowed(tmpbuf->getInset(i)->lyxCode()))
191                                 tmpbuf->erase(i--);
192                 }
193
194                 // reset change tracking status
195                 if (buffer.params().tracking_changes)
196                         tmpbuf->cleanChanges(Paragraph::trackingOn);
197                 else
198                         tmpbuf->cleanChanges(Paragraph::trackingOff);
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::iterator lit = fpit->insetlist.begin();
217                 InsetList::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();
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()) ||
295             startpit == endpit) {
296                 endpos -= pars[startpit].erase(startpos, endpos);
297                 return PitPosPair(endpit, endpos);
298         }
299
300         // A paragraph break has to be physically removed by merging, but
301         // only if either (1) change tracking is off, or (2) the para break
302         // is "blue"
303         for (pit_type pit = startpit; pit != endpit + 1;) {
304                 bool const merge = !params.tracking_changes ||
305                         pars[pit].lookupChange(pars[pit].size()) ==
306                         Change::INSERTED;
307                 pos_type const left  = ( pit == startpit ? startpos : 0 );
308                 pos_type const right = ( pit == endpit ? endpos :
309                                 pars[pit].size() + 1 );
310                 // Logical erase only:
311                 pars[pit].erase(left, right);
312                 // Separate handling of para break:
313                 if (merge && pit != endpit &&
314                    (pit + 1 != endpit || pars[pit].hasSameLayout(pars[pit + 1]))) {
315                         pos_type const thissize = pars[pit].size();
316                         if (doclear)
317                                 pars[pit + 1].stripLeadingSpaces();
318                         mergeParagraph(params, pars, pit);
319                         --endpit;
320                         if (pit == endpit)
321                                 endpos += thissize;
322                 } else
323                         ++pit;
324         }
325
326         // Ensure legal cursor pos:
327         endpit = startpit;
328         endpos = startpos;
329         return PitPosPair(endpit, endpos);
330 }
331
332
333 void copySelectionHelper(Buffer const & buf, ParagraphList & pars,
334         pit_type startpit, pit_type endpit,
335         int start, int end, textclass_type tc)
336 {
337         BOOST_ASSERT(0 <= start && start <= pars[startpit].size());
338         BOOST_ASSERT(0 <= end && end <= pars[endpit].size());
339         BOOST_ASSERT(startpit != endpit || start <= end);
340
341         // Clone the paragraphs within the selection.
342         ParagraphList paragraphs(boost::next(pars.begin(), startpit),
343                                  boost::next(pars.begin(), endpit + 1));
344
345         for_each(paragraphs.begin(), paragraphs.end(), resetParagraph(buf));
346
347         // Cut out the end of the last paragraph.
348         Paragraph & back = paragraphs.back();
349         back.erase(end, back.size());
350
351         // Cut out the begin of the first paragraph
352         Paragraph & front = paragraphs.front();
353         front.erase(0, start);
354
355         theCuts.push(make_pair(paragraphs, tc));
356 }
357
358 } // namespace anon
359
360
361
362
363 namespace lyx {
364 namespace cap {
365
366 string grabAndEraseSelection(LCursor & cur)
367 {
368         if (!cur.selection())
369                 return string();
370         string res = grabSelection(cur);
371         eraseSelection(cur);
372         return res;
373 }
374
375
376 void switchBetweenClasses(textclass_type c1, textclass_type c2,
377         InsetText & in, ErrorList & errorlist)
378 {
379         BOOST_ASSERT(!in.paragraphs().empty());
380         if (c1 == c2)
381                 return;
382
383         LyXTextClass const & tclass1 = textclasslist[c1];
384         LyXTextClass const & tclass2 = textclasslist[c2];
385
386         // layouts
387         ParIterator end = par_iterator_end(in);
388         for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
389                 string const name = it->layout()->name();
390                 bool hasLayout = tclass2.hasLayout(name);
391
392                 if (hasLayout)
393                         it->layout(tclass2[name]);
394                 else
395                         it->layout(tclass2.defaultLayout());
396
397                 if (!hasLayout && name != tclass1.defaultLayoutName()) {
398                         string const s = bformat(
399                                 _("Layout had to be changed from\n%1$s to %2$s\n"
400                                 "because of class conversion from\n%3$s to %4$s"),
401                          name, it->layout()->name(), tclass1.name(), tclass2.name());
402                         // To warn the user that something had to be done.
403                         errorlist.push_back(ErrorItem(_("Changed Layout"), s,
404                                                       it->id(), 0,
405                                                       it->size()));
406                 }
407         }
408
409         // character styles
410         InsetIterator const i_end = inset_iterator_end(in);
411         for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
412                 if (it->lyxCode() == InsetBase::CHARSTYLE_CODE) {
413                         InsetCharStyle & inset =
414                                 static_cast<InsetCharStyle &>(*it);
415                         string const name = inset.params().type;
416                         CharStyles::iterator const found_cs =
417                                 tclass2.charstyle(name);
418                         if (found_cs == tclass2.charstyles().end()) {
419                                 // The character style is undefined in tclass2
420                                 inset.setUndefined();
421                                 string const s = bformat(_(
422                                         "Character style %1$s is "
423                                         "undefined because of class "
424                                         "conversion from\n%2$s to %3$s"),
425                                          name, tclass1.name(), tclass2.name());
426                                 // To warn the user that something had to be done.
427                                 errorlist.push_back(ErrorItem(
428                                                 _("Undefined character style"),
429                                                 s, it.paragraph().id(),
430                                                 it.pos(), it.pos() + 1));
431                         } else if (inset.undefined()) {
432                                 // The character style is undefined in
433                                 // tclass1 and is defined in tclass2
434                                 inset.setDefined(found_cs);
435                         }
436                 }
437         }
438 }
439
440
441 std::vector<string> const availableSelections(Buffer const & buffer)
442 {
443         vector<string> selList;
444
445         CutStack::const_iterator cit = theCuts.begin();
446         CutStack::const_iterator end = theCuts.end();
447         for (; cit != end; ++cit) {
448                 // we do not use cit-> here because gcc 2.9x does not
449                 // like it (JMarc)
450                 ParagraphList const & pars = (*cit).first;
451                 string asciiSel;
452                 ParagraphList::const_iterator pit = pars.begin();
453                 ParagraphList::const_iterator pend = pars.end();
454                 for (; pit != pend; ++pit) {
455                         asciiSel += pit->asString(buffer, false);
456                         if (asciiSel.size() > 25) {
457                                 asciiSel.replace(22, string::npos, "...");
458                                 break;
459                         }
460                 }
461
462                 selList.push_back(asciiSel);
463         }
464
465         return selList;
466 }
467
468
469 lyx::size_type numberOfSelections()
470 {
471         return theCuts.size();
472 }
473
474
475 void cutSelection(LCursor & cur, bool doclear, bool realcut)
476 {
477         // This doesn't make sense, if there is no selection
478         if (!cur.selection())
479                 return;
480
481         // OK, we have a selection. This is always between cur.selBegin()
482         // and cur.selEnd()
483
484         if (cur.inTexted()) {
485                 LyXText * text = cur.text();
486                 BOOST_ASSERT(text);
487                 // Stuff what we got on the clipboard. Even if there is no selection.
488
489                 // There is a problem with having the stuffing here in that the
490                 // larger the selection the slower LyX will get. This can be
491                 // solved by running the line below only when the selection has
492                 // finished. The solution used currently just works, to make it
493                 // faster we need to be more clever and probably also have more
494                 // calls to stuffClipboard. (Lgb)
495 //              cur.bv().stuffClipboard(cur.selectionAsString(true));
496
497                 // make sure that the depth behind the selection are restored, too
498                 recordUndoSelection(cur);
499                 pit_type begpit = cur.selBegin().pit();
500                 pit_type endpit = cur.selEnd().pit();
501
502                 int endpos = cur.selEnd().pos();
503
504                 BufferParams const & bp = cur.buffer().params();
505                 if (realcut) {
506                         copySelectionHelper(cur.buffer(),
507                                 text->paragraphs(),
508                                 begpit, endpit,
509                                 cur.selBegin().pos(), endpos,
510                                 bp.textclass);
511                 }
512
513                 boost::tie(endpit, endpos) =
514                         eraseSelectionHelper(bp,
515                                 text->paragraphs(),
516                                 begpit, endpit,
517                                 cur.selBegin().pos(), endpos,
518                                 doclear);
519
520                 // sometimes necessary
521                 if (doclear)
522                         text->paragraphs()[begpit].stripLeadingSpaces();
523
524                 // cutSelection can invalidate the cursor so we need to set
525                 // it anew. (Lgb)
526                 // we prefer the end for when tracking changes
527                 cur.pos() = endpos;
528                 cur.pit() = endpit;
529
530                 // need a valid cursor. (Lgb)
531                 cur.clearSelection();
532                 updateLabels(cur.buffer());
533
534                 // tell tabular that a recent copy happened
535                 dirtyTabularStack(false);
536         }
537
538         if (cur.inMathed()) {
539                 if (cur.selBegin().idx() != cur.selEnd().idx()) {
540                         // The current selection spans more than one cell.
541                         // Record all cells
542                         recordUndoInset(cur);
543                 } else {
544                         // Record only the current cell to avoid a jumping
545                         // cursor after undo
546                         recordUndo(cur);
547                 }
548                 if (realcut)
549                         copySelection(cur);
550                 eraseSelection(cur);
551         }
552 }
553
554
555 void copySelection(LCursor & cur)
556 {
557         // stuff the selection onto the X clipboard, from an explicit copy request
558         cur.bv().stuffClipboard(cur.selectionAsString(true));
559
560         // this doesn't make sense, if there is no selection
561         if (!cur.selection())
562                 return;
563
564         if (cur.inTexted()) {
565                 LyXText * text = cur.text();
566                 BOOST_ASSERT(text);
567                 // ok we have a selection. This is always between cur.selBegin()
568                 // and sel_end cursor
569
570                 // copy behind a space if there is one
571                 ParagraphList & pars = text->paragraphs();
572                 pos_type pos = cur.selBegin().pos();
573                 pit_type par = cur.selBegin().pit();
574                 while (pos < pars[par].size()
575                                          && pars[par].isLineSeparator(pos)
576                                          && (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
577                         ++pos;
578
579                 copySelectionHelper(cur.buffer(), pars, par, cur.selEnd().pit(),
580                         pos, cur.selEnd().pos(), cur.buffer().params().textclass);
581         }
582
583         if (cur.inMathed()) {
584                 lyxerr << "copySelection in mathed" << endl;
585                 ParagraphList pars;
586                 pars.push_back(Paragraph());
587                 BufferParams const & bp = cur.buffer().params();
588                 pars.back().layout(bp.getLyXTextClass().defaultLayout());
589                 for_each(pars.begin(), pars.end(), resetParagraph(cur.buffer()));
590                 pars.back().insert(0, grabSelection(cur), LyXFont());
591                 theCuts.push(make_pair(pars, bp.textclass));
592         }
593         // tell tabular that a recent copy happened
594         dirtyTabularStack(false);
595 }
596
597
598 std::string getSelection(Buffer const & buf, size_t sel_index)
599 {
600         return sel_index < theCuts.size()
601                 ? theCuts[sel_index].first.back().asString(buf, false)
602                 : string();
603 }
604
605
606 void pasteParagraphList(LCursor & cur, ParagraphList const & parlist,
607                         textclass_type textclass)
608 {
609         if (cur.inTexted()) {
610                 LyXText * text = cur.text();
611                 BOOST_ASSERT(text);
612
613                 recordUndo(cur);
614
615                 pit_type endpit;
616                 PitPosPair ppp;
617                 ErrorList el;
618
619                 boost::tie(ppp, endpit) =
620                         pasteSelectionHelper(cur.buffer(),
621                                              text->paragraphs(),
622                                              cur.pit(), cur.pos(),
623                                              parlist, textclass,
624                                              el);
625                 bufferErrors(cur.buffer(), el);
626                 updateLabels(cur.buffer());
627                 cur.clearSelection();
628                 text->setCursor(cur, ppp.first, ppp.second);
629         }
630
631         // mathed is handled in MathNestInset/MathGridInset
632         BOOST_ASSERT(!cur.inMathed());
633 }
634
635
636 void pasteSelection(LCursor & cur, size_t sel_index)
637 {
638         // this does not make sense, if there is nothing to paste
639         if (!checkPastePossible(sel_index))
640                 return;
641
642         pasteParagraphList(cur, theCuts[sel_index].first,
643                            theCuts[sel_index].second);
644         cur.bv().showErrorList(_("Paste"));
645         cur.setSelection();
646 }
647
648
649 void setSelectionRange(LCursor & cur, pos_type length)
650 {
651         LyXText * text = cur.text();
652         BOOST_ASSERT(text);
653         if (!length)
654                 return;
655         cur.resetAnchor();
656         while (length--)
657                 text->cursorRight(cur);
658         cur.setSelection();
659 }
660
661
662 // simple replacing. The font of the first selected character is used
663 void replaceSelectionWithString(LCursor & cur, string const & str)
664 {
665         LyXText * text = cur.text();
666         BOOST_ASSERT(text);
667         recordUndo(cur);
668
669         // Get font setting before we cut
670         pos_type pos = cur.selEnd().pos();
671         Paragraph & par = text->getPar(cur.selEnd().pit());
672         LyXFont const font =
673                 par.getFontSettings(cur.buffer().params(), cur.selBegin().pos());
674
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);
680
681         // Cut the selection
682         cutSelection(cur, true, false);
683 }
684
685
686 void replaceSelection(LCursor & cur)
687 {
688         if (cur.selection())
689                 cutSelection(cur, true, false);
690 }
691
692
693 // only used by the spellchecker
694 void replaceWord(LCursor & cur, string const & replacestring)
695 {
696         LyXText * text = cur.text();
697         BOOST_ASSERT(text);
698
699         replaceSelectionWithString(cur, replacestring);
700         setSelectionRange(cur, replacestring.length());
701
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);
705 }
706
707
708 void eraseSelection(LCursor & cur)
709 {
710         //lyxerr << "LCursor::eraseSelection begin: " << cur << endl;
711         CursorSlice const & i1 = cur.selBegin();
712         CursorSlice const & i2 = cur.selEnd();
713         if (i1.inset().asMathInset()) {
714                 cur.top() = i1;
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();
721                 } else {
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.
730                         cur.pos() = 0;
731                 }
732                 // need a valid cursor. (Lgb)
733                 cur.clearSelection();
734         } else {
735                 lyxerr << "can't erase this selection 1" << endl;
736         }
737         //lyxerr << "LCursor::eraseSelection end: " << cur << endl;
738 }
739
740
741 void selDel(LCursor & cur)
742 {
743         //lyxerr << "LCursor::selDel" << endl;
744         if (cur.selection())
745                 eraseSelection(cur);
746 }
747
748
749 void selClearOrDel(LCursor & cur)
750 {
751         //lyxerr << "LCursor::selClearOrDel" << endl;
752         if (lyxrc.auto_region_delete)
753                 selDel(cur);
754         else
755                 cur.selection() = false;
756 }
757
758
759 string grabSelection(LCursor const & cur)
760 {
761         if (!cur.selection())
762                 return string();
763
764         // FIXME: What is wrong with the following?
765 #if 0
766         std::ostringstream os;
767         for (DocIterator dit = cur.selectionBegin();
768              dit != cur.selectionEnd(); dit.forwardPos())
769                 os << asString(dit.cell());
770         return os.str();
771 #endif
772
773         CursorSlice i1 = cur.selBegin();
774         CursorSlice i2 = cur.selEnd();
775
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()));
780                 } else {
781                         return "unknown selection 1";
782                 }
783         }
784
785         InsetBase::row_type r1, r2;
786         InsetBase::col_type c1, c2;
787         region(i1, i2, r1, r2, c1, c2);
788
789         string data;
790         if (i1.inset().asMathInset()) {
791                 for (InsetBase::row_type row = r1; row <= r2; ++row) {
792                         if (row > r1)
793                                 data += "\\\\";
794                         for (InsetBase::col_type col = c1; col <= c2; ++col) {
795                                 if (col > c1)
796                                         data += '&';
797                                 data += asString(i1.asMathInset()->
798                                         cell(i1.asMathInset()->index(row, col)));
799                         }
800                 }
801         } else {
802                 data = "unknown selection 2";
803         }
804         return data;
805 }
806
807
808 void dirtyTabularStack(bool b)
809 {
810         dirty_tabular_stack_ = b;
811 }
812
813
814 bool tabularStackDirty()
815 {
816         return dirty_tabular_stack_;
817 }
818
819
820 } // namespace cap
821 } // namespace lyx