]> git.lyx.org Git - lyx.git/blob - src/CutAndPaste.C
Fix bug 2476:
[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         lyx::cap::switchBetweenClasses(textclass, tc, insertion, errorlist);
154
155         ParagraphList::iterator tmpbuf = insertion.begin();
156         int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
157
158         Paragraph::depth_type max_depth = pars[pit].getMaxDepthAfter();
159
160         for (; tmpbuf != insertion.end(); ++tmpbuf) {
161                 // If we have a negative jump so that the depth would
162                 // go below 0 depth then we have to redo the delta to
163                 // this new max depth level so that subsequent
164                 // paragraphs are aligned correctly to this paragraph
165                 // at level 0.
166                 if (int(tmpbuf->params().depth()) + depth_delta < 0)
167                         depth_delta = 0;
168
169                 // Set the right depth so that we are not too deep or shallow.
170                 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
171                 if (tmpbuf->params().depth() > max_depth)
172                         tmpbuf->params().depth(max_depth);
173
174                 // Only set this from the 2nd on as the 2nd depends
175                 // for maxDepth still on pit.
176                 if (tmpbuf != insertion.begin())
177                         max_depth = tmpbuf->getMaxDepthAfter();
178
179                 // Set the inset owner of this paragraph.
180                 tmpbuf->setInsetOwner(pars[pit].inInset());
181                 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
182                         if (tmpbuf->getChar(i) == Paragraph::META_INSET &&
183                             !pars[pit].insetAllowed(tmpbuf->getInset(i)->lyxCode()))
184                                 tmpbuf->erase(i--);
185                 }
186
187                 // reset change tracking status
188                 if (buffer.params().tracking_changes)
189                         tmpbuf->cleanChanges(Paragraph::trackingOn);
190                 else
191                         tmpbuf->cleanChanges(Paragraph::trackingOff);
192         }
193
194         bool const empty = pars[pit].empty();
195         if (!empty) {
196                 // Make the buf exactly the same layout as the cursor
197                 // paragraph.
198                 insertion.begin()->makeSameLayout(pars[pit]);
199         }
200
201         // Prepare the paragraphs and insets for insertion.
202         // A couple of insets store buffer references so need updating.
203         InsetText in;
204         std::swap(in.paragraphs(), insertion);
205
206         ParIterator fpit = par_iterator_begin(in);
207         ParIterator fend = par_iterator_end(in);
208
209         for (; fpit != fend; ++fpit) {
210                 InsetList::iterator lit = fpit->insetlist.begin();
211                 InsetList::iterator eit = fpit->insetlist.end();
212
213                 for (; lit != eit; ++lit) {
214                         switch (lit->inset->lyxCode()) {
215                         case InsetBase::TABULAR_CODE: {
216                                 InsetTabular * it = static_cast<InsetTabular*>(lit->inset);
217                                 it->buffer(&buffer);
218                                 break;
219                         }
220
221                         default:
222                                 break; // nothing
223                         }
224                 }
225         }
226         std::swap(in.paragraphs(), insertion);
227
228         // Split the paragraph for inserting the buf if necessary.
229         if (!empty)
230                 breakParagraphConservative(buffer.params(), pars, pit, pos);
231
232         // Paste it!
233         if (empty) {
234                 pars.insert(boost::next(pars.begin(), pit),
235                             insertion.begin(),
236                             insertion.end());
237
238                 // merge the empty par with the last par of the insertion
239                 mergeParagraph(buffer.params(), pars,
240                                pit + insertion.size() - 1);
241         } else {
242                 pars.insert(boost::next(pars.begin(), pit + 1),
243                             insertion.begin(),
244                             insertion.end());
245
246                 // merge the first par of the insertion with the current par
247                 mergeParagraph(buffer.params(), pars, pit);
248         }
249
250         pit_type last_paste = pit + insertion.size() - 1;
251
252         // Store the new cursor position.
253         pit = last_paste;
254         pos = pars[last_paste].size();
255
256         // Join (conditionally) last pasted paragraph with next one, i.e.,
257         // the tail of the spliced document paragraph
258         if (!empty && last_paste + 1 != pit_type(pars.size())) {
259                 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
260                         mergeParagraph(buffer.params(), pars, last_paste);
261                 } else if (pars[last_paste + 1].empty()) {
262                         pars[last_paste + 1].makeSameLayout(pars[last_paste]);
263                         mergeParagraph(buffer.params(), pars, last_paste);
264                 } else if (pars[last_paste].empty()) {
265                         pars[last_paste].makeSameLayout(pars[last_paste + 1]);
266                         mergeParagraph(buffer.params(), pars, last_paste);
267                 } else {
268                         pars[last_paste + 1].stripLeadingSpaces();
269                         ++last_paste;
270                 }
271         }
272
273         return make_pair(PitPosPair(pit, pos), last_paste + 1);
274 }
275
276
277 PitPosPair eraseSelectionHelper(BufferParams const & params,
278         ParagraphList & pars,
279         pit_type startpit, pit_type endpit,
280         int startpos, int endpos, bool doclear)
281 {
282         // Start of selection is really invalid.
283         if (startpit == pit_type(pars.size()) ||
284             (startpos > pars[startpit].size()))
285                 return PitPosPair(endpit, endpos);
286
287         // Start and end is inside same paragraph
288         if (endpit == pit_type(pars.size()) ||
289             startpit == endpit) {
290                 endpos -= pars[startpit].erase(startpos, endpos);
291                 return PitPosPair(endpit, endpos);
292         }
293
294         // A paragraph break has to be physically removed by merging, but
295         // only if either (1) change tracking is off, or (2) the para break
296         // is "blue"
297         for (pit_type pit = startpit; pit != endpit + 1;) {
298                 bool const merge = !params.tracking_changes ||
299                         pars[pit].lookupChange(pars[pit].size()) ==
300                         Change::INSERTED;
301                 pos_type const left  = ( pit == startpit ? startpos : 0 );
302                 pos_type const right = ( pit == endpit ? endpos :
303                                 pars[pit].size() + 1 );
304                 // Logical erase only:
305                 pars[pit].erase(left, right);
306                 // Separate handling of para break:
307                 if (merge && pit != endpit &&
308                    pars[pit].hasSameLayout(pars[pit + 1])) {
309                         pos_type const thissize = pars[pit].size();
310                         if (doclear)
311                                 pars[pit + 1].stripLeadingSpaces();
312                         mergeParagraph(params, pars, pit);
313                         --endpit;
314                         if (pit == endpit)
315                                 endpos += thissize;
316                 } else
317                         ++pit;
318         }
319
320         // Ensure legal cursor pos:
321         endpit = startpit;
322         endpos = startpos;
323         return PitPosPair(endpit, endpos);
324 }
325
326
327 void copySelectionHelper(Buffer const & buf, ParagraphList & pars,
328         pit_type startpit, pit_type endpit,
329         int start, int end, textclass_type tc)
330 {
331         BOOST_ASSERT(0 <= start && start <= pars[startpit].size());
332         BOOST_ASSERT(0 <= end && end <= pars[endpit].size());
333         BOOST_ASSERT(startpit != endpit || start <= end);
334
335         // Clone the paragraphs within the selection.
336         ParagraphList paragraphs(boost::next(pars.begin(), startpit),
337                                  boost::next(pars.begin(), endpit + 1));
338
339         for_each(paragraphs.begin(), paragraphs.end(), resetParagraph(buf));
340
341         // Cut out the end of the last paragraph.
342         Paragraph & back = paragraphs.back();
343         back.erase(end, back.size());
344
345         // Cut out the begin of the first paragraph
346         Paragraph & front = paragraphs.front();
347         front.erase(0, start);
348
349         theCuts.push(make_pair(paragraphs, tc));
350 }
351
352 } // namespace anon
353
354
355
356
357 namespace lyx {
358 namespace cap {
359
360 string grabAndEraseSelection(LCursor & cur)
361 {
362         if (!cur.selection())
363                 return string();
364         string res = grabSelection(cur);
365         eraseSelection(cur);
366         return res;
367 }
368
369
370 void switchBetweenClasses(textclass_type c1, textclass_type c2,
371         ParagraphList & pars, ErrorList & errorlist)
372 {
373         BOOST_ASSERT(!pars.empty());
374         if (c1 == c2)
375                 return;
376
377         LyXTextClass const & tclass1 = textclasslist[c1];
378         LyXTextClass const & tclass2 = textclasslist[c2];
379
380         InsetText in;
381         std::swap(in.paragraphs(), pars);
382
383         // layouts
384         ParIterator end = par_iterator_end(in);
385         for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
386                 string const name = it->layout()->name();
387                 bool hasLayout = tclass2.hasLayout(name);
388
389                 if (hasLayout)
390                         it->layout(tclass2[name]);
391                 else
392                         it->layout(tclass2.defaultLayout());
393
394                 if (!hasLayout && name != tclass1.defaultLayoutName()) {
395                         string const s = bformat(
396                                 _("Layout had to be changed from\n%1$s to %2$s\n"
397                                 "because of class conversion from\n%3$s to %4$s"),
398                          name, it->layout()->name(), tclass1.name(), tclass2.name());
399                         // To warn the user that something had to be done.
400                         errorlist.push_back(ErrorItem(_("Changed Layout"), s,
401                                                       it->id(), 0,
402                                                       it->size()));
403                 }
404         }
405
406         // character styles
407         InsetIterator const i_end = inset_iterator_end(in);
408         for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
409                 if (it->lyxCode() == InsetBase::CHARSTYLE_CODE) {
410                         InsetCharStyle & inset =
411                                 static_cast<InsetCharStyle &>(*it);
412                         string const name = inset.params().type;
413                         CharStyles::iterator const found_cs =
414                                 tclass2.charstyle(name);
415                         if (found_cs == tclass2.charstyles().end()) {
416                                 // The character style is undefined in tclass2
417                                 inset.setUndefined();
418                                 string const s = bformat(_(
419                                         "Character style %1$s is "
420                                         "undefined because of class "
421                                         "conversion from\n%2$s to %3$s"),
422                                          name, tclass1.name(), tclass2.name());
423                                 // To warn the user that something had to be done.
424                                 errorlist.push_back(ErrorItem(
425                                                 _("Undefined character style"),
426                                                 s, it.paragraph().id(),
427                                                 it.pos(), it.pos() + 1));
428                         } else if (inset.undefined()) {
429                                 // The character style is undefined in
430                                 // tclass1 and is defined in tclass2
431                                 inset.setDefined(found_cs);
432                         }
433                 }
434         }
435
436         std::swap(in.paragraphs(), pars);
437 }
438
439
440 std::vector<string> const availableSelections(Buffer const & buffer)
441 {
442         vector<string> selList;
443
444         CutStack::const_iterator cit = theCuts.begin();
445         CutStack::const_iterator end = theCuts.end();
446         for (; cit != end; ++cit) {
447                 // we do not use cit-> here because gcc 2.9x does not
448                 // like it (JMarc)
449                 ParagraphList const & pars = (*cit).first;
450                 string asciiSel;
451                 ParagraphList::const_iterator pit = pars.begin();
452                 ParagraphList::const_iterator pend = pars.end();
453                 for (; pit != pend; ++pit) {
454                         asciiSel += pit->asString(buffer, false);
455                         if (asciiSel.size() > 25) {
456                                 asciiSel.replace(22, string::npos, "...");
457                                 break;
458                         }
459                 }
460
461                 selList.push_back(asciiSel);
462         }
463
464         return selList;
465 }
466
467
468 lyx::size_type numberOfSelections()
469 {
470         return theCuts.size();
471 }
472
473
474 void cutSelection(LCursor & cur, bool doclear, bool realcut)
475 {
476         // This doesn't make sense, if there is no selection
477         if (!cur.selection())
478                 return;
479
480         // OK, we have a selection. This is always between cur.selBegin()
481         // and cur.selEnd()
482
483         if (cur.inTexted()) {
484                 LyXText * text = cur.text();
485                 BOOST_ASSERT(text);
486                 // Stuff what we got on the clipboard. Even if there is no selection.
487
488                 // There is a problem with having the stuffing here in that the
489                 // larger the selection the slower LyX will get. This can be
490                 // solved by running the line below only when the selection has
491                 // finished. The solution used currently just works, to make it
492                 // faster we need to be more clever and probably also have more
493                 // calls to stuffClipboard. (Lgb)
494 //              cur.bv().stuffClipboard(cur.selectionAsString(true));
495
496                 // make sure that the depth behind the selection are restored, too
497                 recordUndoSelection(cur);
498                 pit_type begpit = cur.selBegin().pit();
499                 pit_type endpit = cur.selEnd().pit();
500
501                 int endpos = cur.selEnd().pos();
502
503                 BufferParams const & bp = cur.buffer().params();
504                 if (realcut) {
505                         copySelectionHelper(cur.buffer(),
506                                 text->paragraphs(),
507                                 begpit, endpit,
508                                 cur.selBegin().pos(), endpos,
509                                 bp.textclass);
510                 }
511
512                 boost::tie(endpit, endpos) =
513                         eraseSelectionHelper(bp,
514                                 text->paragraphs(),
515                                 begpit, endpit,
516                                 cur.selBegin().pos(), endpos,
517                                 doclear);
518
519                 // sometimes necessary
520                 if (doclear)
521                         text->paragraphs()[begpit].stripLeadingSpaces();
522
523                 // cutSelection can invalidate the cursor so we need to set
524                 // it anew. (Lgb)
525                 // we prefer the end for when tracking changes
526                 cur.pos() = endpos;
527                 cur.pit() = endpit;
528
529                 // need a valid cursor. (Lgb)
530                 cur.clearSelection();
531                 updateLabels(cur.buffer());
532
533                 // tell tabular that a recent copy happened
534                 dirtyTabularStack(false);
535         }
536
537         if (cur.inMathed()) {
538                 if (cur.selBegin().idx() != cur.selEnd().idx()) {
539                         // The current selection spans more than one cell.
540                         // Record all cells
541                         recordUndoInset(cur);
542                 } else {
543                         // Record only the current cell to avoid a jumping
544                         // cursor after undo
545                         recordUndo(cur);
546                 }
547                 if (realcut)
548                         copySelection(cur);
549                 eraseSelection(cur);
550         }
551 }
552
553
554 void copySelection(LCursor & cur)
555 {
556         // stuff the selection onto the X clipboard, from an explicit copy request
557         cur.bv().stuffClipboard(cur.selectionAsString(true));
558
559         // this doesn't make sense, if there is no selection
560         if (!cur.selection())
561                 return;
562
563         if (cur.inTexted()) {
564                 LyXText * text = cur.text();
565                 BOOST_ASSERT(text);
566                 // ok we have a selection. This is always between cur.selBegin()
567                 // and sel_end cursor
568
569                 // copy behind a space if there is one
570                 ParagraphList & pars = text->paragraphs();
571                 pos_type pos = cur.selBegin().pos();
572                 pit_type par = cur.selBegin().pit();
573                 while (pos < pars[par].size()
574                                          && pars[par].isLineSeparator(pos)
575                                          && (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
576                         ++pos;
577
578                 copySelectionHelper(cur.buffer(), pars, par, cur.selEnd().pit(),
579                         pos, cur.selEnd().pos(), cur.buffer().params().textclass);
580         }
581
582         if (cur.inMathed()) {
583                 lyxerr << "copySelection in mathed" << endl;
584                 ParagraphList pars;
585                 pars.push_back(Paragraph());
586                 BufferParams const & bp = cur.buffer().params();
587                 pars.back().layout(bp.getLyXTextClass().defaultLayout());
588                 for_each(pars.begin(), pars.end(), resetParagraph(cur.buffer()));
589                 pars.back().insert(0, grabSelection(cur), LyXFont());
590                 theCuts.push(make_pair(pars, bp.textclass));
591         }
592         // tell tabular that a recent copy happened
593         dirtyTabularStack(false);
594 }
595
596
597 std::string getSelection(Buffer const & buf, size_t sel_index)
598 {
599         return sel_index < theCuts.size()
600                 ? theCuts[sel_index].first.back().asString(buf, false)
601                 : string();
602 }
603
604
605 void pasteParagraphList(LCursor & cur, ParagraphList const & parlist,
606                         textclass_type textclass)
607 {
608         if (cur.inTexted()) {
609                 LyXText * text = cur.text();
610                 BOOST_ASSERT(text);
611
612                 recordUndo(cur);
613
614                 pit_type endpit;
615                 PitPosPair ppp;
616                 ErrorList el;
617
618                 boost::tie(ppp, endpit) =
619                         pasteSelectionHelper(cur.buffer(),
620                                              text->paragraphs(),
621                                              cur.pit(), cur.pos(),
622                                              parlist, textclass,
623                                              el);
624                 bufferErrors(cur.buffer(), el);
625                 updateLabels(cur.buffer());
626                 cur.clearSelection();
627                 text->setCursor(cur, ppp.first, ppp.second);
628         }
629
630         // mathed is handled in MathNestInset/MathGridInset
631         BOOST_ASSERT(!cur.inMathed());
632 }
633
634
635 void pasteSelection(LCursor & cur, size_t sel_index)
636 {
637         // this does not make sense, if there is nothing to paste
638         if (!checkPastePossible(sel_index))
639                 return;
640
641         pasteParagraphList(cur, theCuts[sel_index].first,
642                            theCuts[sel_index].second);
643         cur.bv().showErrorList(_("Paste"));
644         cur.setSelection();
645 }
646
647
648 void setSelectionRange(LCursor & cur, pos_type length)
649 {
650         LyXText * text = cur.text();
651         BOOST_ASSERT(text);
652         if (!length)
653                 return;
654         cur.resetAnchor();
655         while (length--)
656                 text->cursorRight(cur);
657         cur.setSelection();
658 }
659
660
661 // simple replacing. The font of the first selected character is used
662 void replaceSelectionWithString(LCursor & cur, string const & str)
663 {
664         LyXText * text = cur.text();
665         BOOST_ASSERT(text);
666         recordUndo(cur);
667
668         // Get font setting before we cut
669         pos_type pos = cur.selEnd().pos();
670         Paragraph & par = text->getPar(cur.selEnd().pit());
671         LyXFont const font =
672                 par.getFontSettings(cur.buffer().params(), cur.selBegin().pos());
673
674         // Insert the new string
675         string::const_iterator cit = str.begin();
676         string::const_iterator end = str.end();
677         for (; cit != end; ++cit, ++pos)
678                 par.insertChar(pos, (*cit), font);
679
680         // Cut the selection
681         cutSelection(cur, true, false);
682 }
683
684
685 void replaceSelection(LCursor & cur)
686 {
687         if (cur.selection())
688                 cutSelection(cur, true, false);
689 }
690
691
692 // only used by the spellchecker
693 void replaceWord(LCursor & cur, string const & replacestring)
694 {
695         LyXText * text = cur.text();
696         BOOST_ASSERT(text);
697
698         replaceSelectionWithString(cur, replacestring);
699         setSelectionRange(cur, replacestring.length());
700
701         // Go back so that replacement string is also spellchecked
702         for (string::size_type i = 0; i < replacestring.length() + 1; ++i)
703                 text->cursorLeft(cur);
704 }
705
706
707 void eraseSelection(LCursor & cur)
708 {
709         //lyxerr << "LCursor::eraseSelection begin: " << cur << endl;
710         CursorSlice const & i1 = cur.selBegin();
711         CursorSlice const & i2 = cur.selEnd();
712         if (i1.inset().asMathInset()) {
713                 cur.top() = i1;
714                 if (i1.idx() == i2.idx()) {
715                         i1.cell().erase(i1.pos(), i2.pos());
716                         // We may have deleted i1.cell(cur.pos()).
717                         // Make sure that pos is valid.
718                         if (cur.pos() > cur.lastpos())
719                                 cur.pos() = cur.lastpos();
720                 } else {
721                         MathInset * p = i1.asMathInset();
722                         InsetBase::row_type r1, r2;
723                         InsetBase::col_type c1, c2;
724                         region(i1, i2, r1, r2, c1, c2);
725                         for (InsetBase::row_type row = r1; row <= r2; ++row)
726                                 for (InsetBase::col_type col = c1; col <= c2; ++col)
727                                         p->cell(p->index(row, col)).clear();
728                         // We've deleted the whole cell. Only pos 0 is valid.
729                         cur.pos() = 0;
730                 }
731                 // need a valid cursor. (Lgb)
732                 cur.clearSelection();
733         } else {
734                 lyxerr << "can't erase this selection 1" << endl;
735         }
736         //lyxerr << "LCursor::eraseSelection end: " << cur << endl;
737 }
738
739
740 void selDel(LCursor & cur)
741 {
742         //lyxerr << "LCursor::selDel" << endl;
743         if (cur.selection())
744                 eraseSelection(cur);
745 }
746
747
748 void selClearOrDel(LCursor & cur)
749 {
750         //lyxerr << "LCursor::selClearOrDel" << endl;
751         if (lyxrc.auto_region_delete)
752                 selDel(cur);
753         else
754                 cur.selection() = false;
755 }
756
757
758 string grabSelection(LCursor const & cur)
759 {
760         if (!cur.selection())
761                 return string();
762
763         // FIXME: What is wrong with the following?
764 #if 0
765         std::ostringstream os;
766         for (DocIterator dit = cur.selectionBegin();
767              dit != cur.selectionEnd(); dit.forwardPos())
768                 os << asString(dit.cell());
769         return os.str();
770 #endif
771
772         CursorSlice i1 = cur.selBegin();
773         CursorSlice i2 = cur.selEnd();
774
775         if (i1.idx() == i2.idx()) {
776                 if (i1.inset().asMathInset()) {
777                         MathArray::const_iterator it = i1.cell().begin();
778                         return asString(MathArray(it + i1.pos(), it + i2.pos()));
779                 } else {
780                         return "unknown selection 1";
781                 }
782         }
783
784         InsetBase::row_type r1, r2;
785         InsetBase::col_type c1, c2;
786         region(i1, i2, r1, r2, c1, c2);
787
788         string data;
789         if (i1.inset().asMathInset()) {
790                 for (InsetBase::row_type row = r1; row <= r2; ++row) {
791                         if (row > r1)
792                                 data += "\\\\";
793                         for (InsetBase::col_type col = c1; col <= c2; ++col) {
794                                 if (col > c1)
795                                         data += '&';
796                                 data += asString(i1.asMathInset()->
797                                         cell(i1.asMathInset()->index(row, col)));
798                         }
799                 }
800         } else {
801                 data = "unknown selection 2";
802         }
803         return data;
804 }
805
806
807 void dirtyTabularStack(bool b)
808 {
809         dirty_tabular_stack_ = b;
810 }
811
812
813 bool tabularStackDirty()
814 {
815         return dirty_tabular_stack_;
816 }
817
818
819 } // namespace cap
820 } // namespace lyx