]> git.lyx.org Git - lyx.git/blob - src/CutAndPaste.C
Fix and document middle mouse button paste. This is probably the last of
[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_ = false;
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::const_iterator lit = fpit->insetlist.begin();
214                 InsetList::const_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                 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.trackChanges);
301
302                 // Logically erase only, including the end-of-paragraph character
303                 pars[pit].eraseChars(left, right, params.trackChanges);
304
305                 // Separate handling of paragraph break:
306                 if (merge && pit != endpit &&
307                     (pit + 1 != endpit || pars[pit].hasSameLayout(pars[pit + 1]))) {
308                         pos_type const thissize = pars[pit].size();
309                         if (doclear)
310                                 pars[pit + 1].stripLeadingSpaces();
311                         mergeParagraph(params, pars, pit);
312                         --endpit;
313                         if (pit == endpit)
314                                 endpos += thissize;
315                 } else
316                         ++pit;
317         }
318
319         // Ensure legal cursor pos:
320         endpit = startpit;
321         endpos = startpos;
322         return PitPosPair(endpit, endpos);
323 }
324
325
326 void copySelectionHelper(Buffer const & buf, ParagraphList & pars,
327         pit_type startpit, pit_type endpit,
328         int start, int end, textclass_type tc)
329 {
330         BOOST_ASSERT(0 <= start && start <= pars[startpit].size());
331         BOOST_ASSERT(0 <= end && end <= pars[endpit].size());
332         BOOST_ASSERT(startpit != endpit || start <= end);
333
334         // Clone the paragraphs within the selection.
335         ParagraphList paragraphs(boost::next(pars.begin(), startpit),
336                                  boost::next(pars.begin(), endpit + 1));
337
338         ParagraphList::iterator it = paragraphs.begin();
339         ParagraphList::iterator it_end = paragraphs.end();
340
341         for (; it != it_end; it++) {
342                 // ERT paragraphs have the Language latex_language.
343                 // This is invalid outside of ERT, so we need to change it
344                 // to the buffer language.
345                 if (it->ownerCode() == InsetBase::ERT_CODE) {
346                         it->changeLanguage(buf.params(), latex_language,
347                                            buf.getLanguage());
348                 }
349                 it->setInsetOwner(0);
350         }
351
352         // Cut out the end of the last paragraph.
353         Paragraph & back = paragraphs.back();
354         // do not track deletion here; it is an internal action not visible to the user
355         back.eraseChars(end, back.size(), false);
356
357         // Cut out the begin of the first paragraph
358         Paragraph & front = paragraphs.front();
359         // again, do not track deletion
360         front.eraseChars(0, start, false);
361
362         theCuts.push(make_pair(paragraphs, tc));
363 }
364
365 } // namespace anon
366
367
368
369
370 namespace cap {
371
372 docstring grabAndEraseSelection(LCursor & cur)
373 {
374         if (!cur.selection())
375                 return docstring();
376         docstring res = grabSelection(cur);
377         eraseSelection(cur);
378         return res;
379 }
380
381
382 void switchBetweenClasses(textclass_type c1, textclass_type c2,
383         InsetText & in, ErrorList & errorlist)
384 {
385         BOOST_ASSERT(!in.paragraphs().empty());
386         if (c1 == c2)
387                 return;
388
389         LyXTextClass const & tclass1 = textclasslist[c1];
390         LyXTextClass const & tclass2 = textclasslist[c2];
391
392         // layouts
393         ParIterator end = par_iterator_end(in);
394         for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
395                 string const name = it->layout()->name();
396                 bool hasLayout = tclass2.hasLayout(name);
397
398                 if (hasLayout)
399                         it->layout(tclass2[name]);
400                 else
401                         it->layout(tclass2.defaultLayout());
402
403                 if (!hasLayout && name != tclass1.defaultLayoutName()) {
404                         docstring const s = bformat(
405                                                  _("Layout had to be changed from\n%1$s to %2$s\n"
406                                                 "because of class conversion from\n%3$s to %4$s"),
407                          from_utf8(name), from_utf8(it->layout()->name()),
408                          from_utf8(tclass1.name()), from_utf8(tclass2.name()));
409                         // To warn the user that something had to be done.
410                         errorlist.push_back(ErrorItem(_("Changed Layout"), s,
411                                                       it->id(), 0,
412                                                       it->size()));
413                 }
414         }
415
416         // character styles
417         InsetIterator const i_end = inset_iterator_end(in);
418         for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
419                 if (it->lyxCode() == InsetBase::CHARSTYLE_CODE) {
420                         InsetCharStyle & inset =
421                                 static_cast<InsetCharStyle &>(*it);
422                         string const name = inset.params().type;
423                         CharStyles::iterator const found_cs =
424                                 tclass2.charstyle(name);
425                         if (found_cs == tclass2.charstyles().end()) {
426                                 // The character style is undefined in tclass2
427                                 inset.setUndefined();
428                                 docstring const s = bformat(_(
429                                         "Character style %1$s is "
430                                         "undefined because of class "
431                                         "conversion from\n%2$s to %3$s"),
432                                          from_utf8(name), from_utf8(tclass1.name()),
433                                          from_utf8(tclass2.name()));
434                                 // To warn the user that something had to be done.
435                                 errorlist.push_back(ErrorItem(
436                                         _("Undefined character style"),
437                                         s, it.paragraph().id(), it.pos(), it.pos() + 1));
438                         } else if (inset.undefined()) {
439                                 // The character style is undefined in
440                                 // tclass1 and is defined in tclass2
441                                 inset.setDefined(found_cs);
442                         }
443                 }
444         }
445 }
446
447
448 std::vector<docstring> const availableSelections(Buffer const & buffer)
449 {
450         vector<docstring> selList;
451
452         CutStack::const_iterator cit = theCuts.begin();
453         CutStack::const_iterator end = theCuts.end();
454         for (; cit != end; ++cit) {
455                 // we do not use cit-> here because gcc 2.9x does not
456                 // like it (JMarc)
457                 ParagraphList const & pars = (*cit).first;
458                 docstring asciiSel;
459                 ParagraphList::const_iterator pit = pars.begin();
460                 ParagraphList::const_iterator pend = pars.end();
461                 for (; pit != pend; ++pit) {
462                         asciiSel += pit->asString(buffer, false);
463                         if (asciiSel.size() > 25) {
464                                 asciiSel.replace(22, docstring::npos,
465                                                  from_ascii("..."));
466                                 break;
467                         }
468                 }
469
470                 selList.push_back(asciiSel);
471         }
472
473         return selList;
474 }
475
476
477 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                 if (realcut)
497                         theClipboard().put(cur.selectionAsString(true));
498
499                 // make sure that the depth behind the selection are restored, too
500                 recordUndoSelection(cur);
501                 pit_type begpit = cur.selBegin().pit();
502                 pit_type endpit = cur.selEnd().pit();
503
504                 int endpos = cur.selEnd().pos();
505
506                 BufferParams const & bp = cur.buffer().params();
507                 if (realcut) {
508                         copySelectionHelper(cur.buffer(),
509                                 text->paragraphs(),
510                                 begpit, endpit,
511                                 cur.selBegin().pos(), endpos,
512                                 bp.textclass);
513                 }
514
515                 boost::tie(endpit, endpos) =
516                         eraseSelectionHelper(bp,
517                                 text->paragraphs(),
518                                 begpit, endpit,
519                                 cur.selBegin().pos(), endpos,
520                                 doclear);
521
522                 // sometimes necessary
523                 if (doclear)
524                         text->paragraphs()[begpit].stripLeadingSpaces();
525
526                 // cutSelection can invalidate the cursor so we need to set
527                 // it anew. (Lgb)
528                 // we prefer the end for when tracking changes
529                 cur.pos() = endpos;
530                 cur.pit() = endpit;
531
532                 // need a valid cursor. (Lgb)
533                 cur.clearSelection();
534                 updateLabels(cur.buffer());
535
536                 // tell tabular that a recent copy happened
537                 dirtyTabularStack(false);
538         }
539
540         if (cur.inMathed()) {
541                 if (cur.selBegin().idx() != cur.selEnd().idx()) {
542                         // The current selection spans more than one cell.
543                         // Record all cells
544                         recordUndoInset(cur);
545                 } else {
546                         // Record only the current cell to avoid a jumping
547                         // cursor after undo
548                         recordUndo(cur);
549                 }
550                 if (realcut)
551                         copySelection(cur);
552                 eraseSelection(cur);
553         }
554 }
555
556
557 void copySelection(LCursor & cur)
558 {
559         // stuff the selection onto the X clipboard, from an explicit copy request
560         theClipboard().put(cur.selectionAsString(true));
561
562         copySelectionToStack(cur);
563 }
564
565
566 void copySelectionToStack(LCursor & cur)
567 {
568         // this doesn't make sense, if there is no selection
569         if (!cur.selection())
570                 return;
571
572         if (cur.inTexted()) {
573                 LyXText * text = cur.text();
574                 BOOST_ASSERT(text);
575                 // ok we have a selection. This is always between cur.selBegin()
576                 // and sel_end cursor
577
578                 // copy behind a space if there is one
579                 ParagraphList & pars = text->paragraphs();
580                 pos_type pos = cur.selBegin().pos();
581                 pit_type par = cur.selBegin().pit();
582                 while (pos < pars[par].size()
583                                          && pars[par].isLineSeparator(pos)
584                                          && (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
585                         ++pos;
586
587                 copySelectionHelper(cur.buffer(), pars, par, cur.selEnd().pit(),
588                         pos, cur.selEnd().pos(), cur.buffer().params().textclass);
589         }
590
591         if (cur.inMathed()) {
592                 //lyxerr << "copySelection in mathed" << endl;
593                 ParagraphList pars;
594                 Paragraph par;
595                 BufferParams const & bp = cur.buffer().params();
596                 par.layout(bp.getLyXTextClass().defaultLayout());
597                 par.insert(0, grabSelection(cur), LyXFont(), Change(Change::UNCHANGED));
598                 pars.push_back(par);
599                 theCuts.push(make_pair(pars, bp.textclass));
600         }
601         // tell tabular that a recent copy happened
602         dirtyTabularStack(false);
603 }
604
605
606 docstring getSelection(Buffer const & buf, size_t sel_index)
607 {
608         return sel_index < theCuts.size()
609                 ? theCuts[sel_index].first.back().asString(buf, false)
610                 : docstring();
611 }
612
613
614 void pasteParagraphList(LCursor & cur, ParagraphList const & parlist,
615                         textclass_type textclass, ErrorList & errorList)
616 {
617         if (cur.inTexted()) {
618                 LyXText * text = cur.text();
619                 BOOST_ASSERT(text);
620
621                 pit_type endpit;
622                 PitPosPair ppp;
623
624                 boost::tie(ppp, endpit) =
625                         pasteSelectionHelper(cur, parlist,
626                                              textclass, errorList);
627                 updateLabels(cur.buffer());
628                 cur.clearSelection();
629                 text->setCursor(cur.top(), ppp.first, ppp.second);
630         }
631
632         // mathed is handled in InsetMathNest/InsetMathGrid
633         BOOST_ASSERT(!cur.inMathed());
634 }
635
636
637 void pasteSelection(LCursor & cur, ErrorList & errorList, size_t sel_index)
638 {
639         // this does not make sense, if there is nothing to paste
640         if (!checkPastePossible(sel_index))
641                 return;
642
643         recordUndo(cur);
644         pasteParagraphList(cur, theCuts[sel_index].first,
645                            theCuts[sel_index].second, errorList);
646         cur.setSelection();
647 }
648
649
650 void replaceSelectionWithString(LCursor & cur, docstring const & str, bool backwards)
651 {
652         recordUndo(cur);
653         DocIterator selbeg = cur.selectionBegin();
654
655         // Get font setting before we cut
656         LyXFont const font =
657                 selbeg.paragraph().getFontSettings(cur.buffer().params(), selbeg.pos());
658
659         // Insert the new string
660         pos_type pos = cur.selEnd().pos();
661         Paragraph & par = cur.selEnd().paragraph();
662         docstring::const_iterator cit = str.begin();
663         docstring::const_iterator end = str.end();
664         for (; cit != end; ++cit, ++pos)
665                 par.insertChar(pos, *cit, font, cur.buffer().params().trackChanges);
666
667         // Cut the selection
668         cutSelection(cur, true, false);
669
670         // select the replacement
671         if (backwards) {
672                 selbeg.pos() += str.length();
673                 cur.setSelection(selbeg, -int(str.length()));
674         } else
675                 cur.setSelection(selbeg, str.length());
676 }
677
678
679 void replaceSelection(LCursor & cur)
680 {
681         if (cur.selection())
682                 cutSelection(cur, true, false);
683 }
684
685
686 void eraseSelection(LCursor & cur)
687 {
688         //lyxerr << "cap::eraseSelection begin: " << cur << endl;
689         CursorSlice const & i1 = cur.selBegin();
690         CursorSlice const & i2 = cur.selEnd();
691         if (i1.inset().asInsetMath()) {
692                 cur.top() = i1;
693                 if (i1.idx() == i2.idx()) {
694                         i1.cell().erase(i1.pos(), i2.pos());
695                         // We may have deleted i1.cell(cur.pos()).
696                         // Make sure that pos is valid.
697                         if (cur.pos() > cur.lastpos())
698                                 cur.pos() = cur.lastpos();
699                 } else {
700                         InsetMath * p = i1.asInsetMath();
701                         InsetBase::row_type r1, r2;
702                         InsetBase::col_type c1, c2;
703                         region(i1, i2, r1, r2, c1, c2);
704                         for (InsetBase::row_type row = r1; row <= r2; ++row)
705                                 for (InsetBase::col_type col = c1; col <= c2; ++col)
706                                         p->cell(p->index(row, col)).clear();
707                         // We've deleted the whole cell. Only pos 0 is valid.
708                         cur.pos() = 0;
709                 }
710                 // need a valid cursor. (Lgb)
711                 cur.clearSelection();
712         } else {
713                 lyxerr << "can't erase this selection 1" << endl;
714         }
715         //lyxerr << "cap::eraseSelection end: " << cur << endl;
716 }
717
718
719 void selDel(LCursor & cur)
720 {
721         //lyxerr << "cap::selDel" << endl;
722         if (cur.selection())
723                 eraseSelection(cur);
724 }
725
726
727 void selClearOrDel(LCursor & cur)
728 {
729         //lyxerr << "cap::selClearOrDel" << endl;
730         if (lyxrc.auto_region_delete)
731                 selDel(cur);
732         else
733                 cur.selection() = false;
734 }
735
736
737 docstring grabSelection(LCursor const & cur)
738 {
739         if (!cur.selection())
740                 return docstring();
741
742         // FIXME: What is wrong with the following?
743 #if 0
744         std::ostringstream os;
745         for (DocIterator dit = cur.selectionBegin();
746              dit != cur.selectionEnd(); dit.forwardPos())
747                 os << asString(dit.cell());
748         return os.str();
749 #endif
750
751         CursorSlice i1 = cur.selBegin();
752         CursorSlice i2 = cur.selEnd();
753
754         if (i1.idx() == i2.idx()) {
755                 if (i1.inset().asInsetMath()) {
756                         MathArray::const_iterator it = i1.cell().begin();
757                         return asString(MathArray(it + i1.pos(), it + i2.pos()));
758                 } else {
759                         return from_ascii("unknown selection 1");
760                 }
761         }
762
763         InsetBase::row_type r1, r2;
764         InsetBase::col_type c1, c2;
765         region(i1, i2, r1, r2, c1, c2);
766
767         docstring data;
768         if (i1.inset().asInsetMath()) {
769                 for (InsetBase::row_type row = r1; row <= r2; ++row) {
770                         if (row > r1)
771                                 data += "\\\\";
772                         for (InsetBase::col_type col = c1; col <= c2; ++col) {
773                                 if (col > c1)
774                                         data += '&';
775                                 data += asString(i1.asInsetMath()->
776                                         cell(i1.asInsetMath()->index(row, col)));
777                         }
778                 }
779         } else {
780                 data = from_ascii("unknown selection 2");
781         }
782         return data;
783 }
784
785
786 void dirtyTabularStack(bool b)
787 {
788         dirty_tabular_stack_ = b;
789 }
790
791
792 bool tabularStackDirty()
793 {
794         return dirty_tabular_stack_;
795 }
796
797
798 } // namespace cap
799
800 } // namespace lyx