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