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