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