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