]> git.lyx.org Git - lyx.git/blob - src/CutAndPaste.C
* src/CutAndPaste.C
[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::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         // this doesn't make sense, if there is no selection
563         if (!cur.selection())
564                 return;
565
566         if (cur.inTexted()) {
567                 LyXText * text = cur.text();
568                 BOOST_ASSERT(text);
569                 // ok we have a selection. This is always between cur.selBegin()
570                 // and sel_end cursor
571
572                 // copy behind a space if there is one
573                 ParagraphList & pars = text->paragraphs();
574                 pos_type pos = cur.selBegin().pos();
575                 pit_type par = cur.selBegin().pit();
576                 while (pos < pars[par].size()
577                                          && pars[par].isLineSeparator(pos)
578                                          && (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
579                         ++pos;
580
581                 copySelectionHelper(cur.buffer(), pars, par, cur.selEnd().pit(),
582                         pos, cur.selEnd().pos(), cur.buffer().params().textclass);
583         }
584
585         if (cur.inMathed()) {
586                 //lyxerr << "copySelection in mathed" << endl;
587                 ParagraphList pars;
588                 Paragraph par;
589                 BufferParams const & bp = cur.buffer().params();
590                 par.layout(bp.getLyXTextClass().defaultLayout());
591                 par.insert(0, grabSelection(cur), LyXFont(), Change(Change::UNCHANGED));
592                 pars.push_back(par);
593                 theCuts.push(make_pair(pars, bp.textclass));
594         }
595         // tell tabular that a recent copy happened
596         dirtyTabularStack(false);
597 }
598
599
600 docstring getSelection(Buffer const & buf, size_t sel_index)
601 {
602         return sel_index < theCuts.size()
603                 ? theCuts[sel_index].first.back().asString(buf, false)
604                 : docstring();
605 }
606
607
608 void pasteParagraphList(LCursor & cur, ParagraphList const & parlist,
609                         textclass_type textclass, ErrorList & errorList)
610 {
611         if (cur.inTexted()) {
612                 LyXText * text = cur.text();
613                 BOOST_ASSERT(text);
614
615                 pit_type endpit;
616                 PitPosPair ppp;
617
618                 boost::tie(ppp, endpit) =
619                         pasteSelectionHelper(cur, parlist,
620                                              textclass, errorList);
621                 updateLabels(cur.buffer());
622                 cur.clearSelection();
623                 text->setCursor(cur.top(), ppp.first, ppp.second);
624         }
625
626         // mathed is handled in InsetMathNest/InsetMathGrid
627         BOOST_ASSERT(!cur.inMathed());
628 }
629
630
631 void pasteSelection(LCursor & cur, ErrorList & errorList, size_t sel_index)
632 {
633         // this does not make sense, if there is nothing to paste
634         if (!checkPastePossible(sel_index))
635                 return;
636
637         recordUndo(cur);
638         pasteParagraphList(cur, theCuts[sel_index].first,
639                            theCuts[sel_index].second, errorList);
640         cur.setSelection();
641 }
642
643
644 // simple replacing. The font of the first selected character is used
645 void replaceSelectionWithString(LCursor & cur, docstring const & str, bool backwards)
646 {
647         recordUndo(cur);
648         DocIterator selbeg = cur.selectionBegin();
649
650         // Get font setting before we cut
651         LyXFont const font =
652                 selbeg.paragraph().getFontSettings(cur.buffer().params(), selbeg.pos());
653
654         // Insert the new string
655         pos_type pos = cur.selEnd().pos();
656         Paragraph & par = cur.selEnd().paragraph();
657         docstring::const_iterator cit = str.begin();
658         docstring::const_iterator end = str.end();
659         for (; cit != end; ++cit, ++pos)
660                 par.insertChar(pos, *cit, font, cur.buffer().params().trackChanges);
661
662         // Cut the selection
663         cutSelection(cur, true, false);
664
665         // select the replacement
666         if (backwards) {
667                 selbeg.pos() += str.length();
668                 cur.setSelection(selbeg, -int(str.length()));
669         } else
670                 cur.setSelection(selbeg, str.length());
671 }
672
673
674 void replaceSelection(LCursor & cur)
675 {
676         if (cur.selection())
677                 cutSelection(cur, true, false);
678 }
679
680
681 void eraseSelection(LCursor & cur)
682 {
683         //lyxerr << "LCursor::eraseSelection begin: " << cur << endl;
684         CursorSlice const & i1 = cur.selBegin();
685         CursorSlice const & i2 = cur.selEnd();
686         if (i1.inset().asInsetMath()) {
687                 cur.top() = i1;
688                 if (i1.idx() == i2.idx()) {
689                         i1.cell().erase(i1.pos(), i2.pos());
690                         // We may have deleted i1.cell(cur.pos()).
691                         // Make sure that pos is valid.
692                         if (cur.pos() > cur.lastpos())
693                                 cur.pos() = cur.lastpos();
694                 } else {
695                         InsetMath * p = i1.asInsetMath();
696                         InsetBase::row_type r1, r2;
697                         InsetBase::col_type c1, c2;
698                         region(i1, i2, r1, r2, c1, c2);
699                         for (InsetBase::row_type row = r1; row <= r2; ++row)
700                                 for (InsetBase::col_type col = c1; col <= c2; ++col)
701                                         p->cell(p->index(row, col)).clear();
702                         // We've deleted the whole cell. Only pos 0 is valid.
703                         cur.pos() = 0;
704                 }
705                 // need a valid cursor. (Lgb)
706                 cur.clearSelection();
707         } else {
708                 lyxerr << "can't erase this selection 1" << endl;
709         }
710         //lyxerr << "LCursor::eraseSelection end: " << cur << endl;
711 }
712
713
714 void selDel(LCursor & cur)
715 {
716         //lyxerr << "LCursor::selDel" << endl;
717         if (cur.selection())
718                 eraseSelection(cur);
719 }
720
721
722 void selClearOrDel(LCursor & cur)
723 {
724         //lyxerr << "LCursor::selClearOrDel" << endl;
725         if (lyxrc.auto_region_delete)
726                 selDel(cur);
727         else
728                 cur.selection() = false;
729 }
730
731
732 docstring grabSelection(LCursor const & cur)
733 {
734         if (!cur.selection())
735                 return docstring();
736
737         // FIXME: What is wrong with the following?
738 #if 0
739         std::ostringstream os;
740         for (DocIterator dit = cur.selectionBegin();
741              dit != cur.selectionEnd(); dit.forwardPos())
742                 os << asString(dit.cell());
743         return os.str();
744 #endif
745
746         CursorSlice i1 = cur.selBegin();
747         CursorSlice i2 = cur.selEnd();
748
749         if (i1.idx() == i2.idx()) {
750                 if (i1.inset().asInsetMath()) {
751                         MathArray::const_iterator it = i1.cell().begin();
752                         return asString(MathArray(it + i1.pos(), it + i2.pos()));
753                 } else {
754                         return from_ascii("unknown selection 1");
755                 }
756         }
757
758         InsetBase::row_type r1, r2;
759         InsetBase::col_type c1, c2;
760         region(i1, i2, r1, r2, c1, c2);
761
762         docstring data;
763         if (i1.inset().asInsetMath()) {
764                 for (InsetBase::row_type row = r1; row <= r2; ++row) {
765                         if (row > r1)
766                                 data += "\\\\";
767                         for (InsetBase::col_type col = c1; col <= c2; ++col) {
768                                 if (col > c1)
769                                         data += '&';
770                                 data += asString(i1.asInsetMath()->
771                                         cell(i1.asInsetMath()->index(row, col)));
772                         }
773                 }
774         } else {
775                 data = from_ascii("unknown selection 2");
776         }
777         return data;
778 }
779
780
781 void dirtyTabularStack(bool b)
782 {
783         dirty_tabular_stack_ = b;
784 }
785
786
787 bool tabularStackDirty()
788 {
789         return dirty_tabular_stack_;
790 }
791
792
793 } // namespace cap
794
795 } // namespace lyx