]> git.lyx.org Git - lyx.git/blob - src/CutAndPaste.C
28f6061a3a7eff0af2d076a4074f7fe9e8c093c2
[lyx.git] / src / CutAndPaste.C
1 /*
2  * \file CutAndPaste.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Jürgen Vigna
7  * \author Lars Gullik Bjønnes
8  * \author Alfredo Braunstein
9  * \author Michael Gerz
10  *
11  * Full author contact details are available in file CREDITS.
12  */
13
14 #include <config.h>
15
16 #include "CutAndPaste.h"
17
18 #include "buffer.h"
19 #include "buffer_funcs.h"
20 #include "bufferparams.h"
21 #include "cursor.h"
22 #include "debug.h"
23 #include "errorlist.h"
24 #include "funcrequest.h"
25 #include "gettext.h"
26 #include "insetiterator.h"
27 #include "language.h"
28 #include "lfuns.h"
29 #include "lyxrc.h"
30 #include "lyxtext.h"
31 #include "lyxtextclasslist.h"
32 #include "paragraph.h"
33 #include "paragraph_funcs.h"
34 #include "ParagraphParameters.h"
35 #include "ParagraphList_fwd.h"
36 #include "pariterator.h"
37 #include "undo.h"
38
39 #include "insets/insetcharstyle.h"
40 #include "insets/insettabular.h"
41
42 #include "mathed/MathData.h"
43 #include "mathed/InsetMath.h"
44 #include "mathed/MathSupport.h"
45
46 #include "support/lstrings.h"
47
48 #include "frontends/Clipboard.h"
49
50 #include <boost/tuple/tuple.hpp>
51
52
53 namespace lyx {
54
55 using support::bformat;
56 using frontend::Clipboard;
57
58 using std::endl;
59 using std::for_each;
60 using std::make_pair;
61 using std::pair;
62 using std::vector;
63 using std::string;
64
65
66 namespace {
67
68 typedef std::pair<pit_type, int> PitPosPair;
69
70 typedef limited_stack<pair<ParagraphList, textclass_type> > CutStack;
71
72 CutStack theCuts(10);
73
74 // store whether the tabular stack is newer than the normal copy stack
75 // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
76 // when we (hopefully) have a one-for-all paste mechanism.
77 bool dirty_tabular_stack_;
78
79
80 void region(CursorSlice const & i1, CursorSlice const & i2,
81         InsetBase::row_type & r1, InsetBase::row_type & r2,
82         InsetBase::col_type & c1, InsetBase::col_type & c2)
83 {
84         InsetBase & p = i1.inset();
85         c1 = p.col(i1.idx());
86         c2 = p.col(i2.idx());
87         if (c1 > c2)
88                 std::swap(c1, c2);
89         r1 = p.row(i1.idx());
90         r2 = p.row(i2.idx());
91         if (r1 > r2)
92                 std::swap(r1, r2);
93 }
94
95
96 bool checkPastePossible(int index)
97 {
98         return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
99 }
100
101
102 pair<PitPosPair, pit_type>
103 pasteSelectionHelper(LCursor & cur, ParagraphList const & parlist,
104                      textclass_type textclass, ErrorList & errorlist)
105 {
106         Buffer const & buffer = cur.buffer();
107         pit_type pit = cur.pit();
108         pos_type pos = cur.pos();
109         ParagraphList & pars = cur.text()->paragraphs();
110
111         if (parlist.empty())
112                 return make_pair(PitPosPair(pit, pos), pit);
113
114         BOOST_ASSERT (pos <= pars[pit].size());
115
116         // Make a copy of the CaP paragraphs.
117         ParagraphList insertion = parlist;
118         textclass_type const tc = buffer.params().textclass;
119
120         // Now remove all out of the pars which is NOT allowed in the
121         // new environment and set also another font if that is required.
122
123         // Convert newline to paragraph break in ERT inset.
124         // This should not be here!
125         if (pars[pit].inInset() &&
126             pars[pit].inInset()->lyxCode() == InsetBase::ERT_CODE) {
127                 for (ParagraphList::size_type i = 0; i < insertion.size(); ++i) {
128                         for (pos_type j = 0; j < insertion[i].size(); ++j) {
129                                 if (insertion[i].isNewline(j)) {
130                                         // do not track deletion of newline
131                                         insertion[i].eraseChar(j, false);
132                                         breakParagraphConservative(
133                                                         buffer.params(),
134                                                         insertion, i, j);
135                                 }
136                         }
137                 }
138         }
139
140         // If we are in an inset which returns forceDefaultParagraphs,
141         // set the paragraphs to default
142         if (cur.inset().forceDefaultParagraphs(cur.idx())) {
143                 LyXLayout_ptr const layout = 
144                         buffer.params().getLyXTextClass().defaultLayout();
145                 ParagraphList::iterator const end = insertion.end();
146                 for (ParagraphList::iterator par = insertion.begin(); 
147                                 par != end; ++par)
148                         par->layout(layout);
149         }
150
151         // Make sure there is no class difference.
152         InsetText in;
153         // This works without copying any paragraph data because we have
154         // a specialized swap method for ParagraphList. This is important
155         // since we store pointers to insets at some places and we don't
156         // want to invalidate them.
157         insertion.swap(in.paragraphs());
158         cap::switchBetweenClasses(textclass, tc, in, errorlist);
159         insertion.swap(in.paragraphs());
160
161         ParagraphList::iterator tmpbuf = insertion.begin();
162         int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
163
164         depth_type max_depth = pars[pit].getMaxDepthAfter();
165
166         for (; tmpbuf != insertion.end(); ++tmpbuf) {
167                 // If we have a negative jump so that the depth would
168                 // go below 0 depth then we have to redo the delta to
169                 // this new max depth level so that subsequent
170                 // paragraphs are aligned correctly to this paragraph
171                 // at level 0.
172                 if (int(tmpbuf->params().depth()) + depth_delta < 0)
173                         depth_delta = 0;
174
175                 // Set the right depth so that we are not too deep or shallow.
176                 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
177                 if (tmpbuf->params().depth() > max_depth)
178                         tmpbuf->params().depth(max_depth);
179
180                 // Only set this from the 2nd on as the 2nd depends
181                 // for maxDepth still on pit.
182                 if (tmpbuf != insertion.begin())
183                         max_depth = tmpbuf->getMaxDepthAfter();
184
185                 // Set the inset owner of this paragraph.
186                 tmpbuf->setInsetOwner(pars[pit].inInset());
187                 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
188                         if (tmpbuf->getChar(i) == Paragraph::META_INSET &&
189                             !pars[pit].insetAllowed(tmpbuf->getInset(i)->lyxCode()))
190                                 // do not track deletion of invalid insets
191                                 tmpbuf->eraseChar(i--, false);
192                 }
193
194                 tmpbuf->setChange(Change(buffer.params().trackChanges ?
195                                          Change::INSERTED : Change::UNCHANGED));
196         }
197
198         bool const empty = pars[pit].empty();
199         if (!empty) {
200                 // Make the buf exactly the same layout as the cursor
201                 // paragraph.
202                 insertion.begin()->makeSameLayout(pars[pit]);
203         }
204
205         // Prepare the paragraphs and insets for insertion.
206         // A couple of insets store buffer references so need updating.
207         insertion.swap(in.paragraphs());
208
209         ParIterator fpit = par_iterator_begin(in);
210         ParIterator fend = par_iterator_end(in);
211
212         for (; fpit != fend; ++fpit) {
213                 InsetList::iterator lit = fpit->insetlist.begin();
214                 InsetList::iterator eit = fpit->insetlist.end();
215
216                 for (; lit != eit; ++lit) {
217                         switch (lit->inset->lyxCode()) {
218                         case InsetBase::TABULAR_CODE: {
219                                 InsetTabular * it = static_cast<InsetTabular*>(lit->inset);
220                                 it->buffer(&buffer);
221                                 break;
222                         }
223
224                         default:
225                                 break; // nothing
226                         }
227                 }
228         }
229         insertion.swap(in.paragraphs());
230
231         // Split the paragraph for inserting the buf if necessary.
232         if (!empty)
233                 breakParagraphConservative(buffer.params(), pars, pit, pos);
234
235         // Paste it!
236         if (empty) {
237                 pars.insert(boost::next(pars.begin(), pit),
238                             insertion.begin(),
239                             insertion.end());
240
241                 // merge the empty par with the last par of the insertion
242                 mergeParagraph(buffer.params(), pars,
243                                pit + insertion.size() - 1);
244         } else {
245                 pars.insert(boost::next(pars.begin(), pit + 1),
246                             insertion.begin(),
247                             insertion.end());
248
249                 // merge the first par of the insertion with the current par
250                 mergeParagraph(buffer.params(), pars, pit);
251         }
252
253         pit_type last_paste = pit + insertion.size() - 1;
254
255         // Store the new cursor position.
256         pit = last_paste;
257         pos = pars[last_paste].size();
258
259         // Join (conditionally) last pasted paragraph with next one, i.e.,
260         // the tail of the spliced document paragraph
261         if (!empty && last_paste + 1 != pit_type(pars.size())) {
262                 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
263                         mergeParagraph(buffer.params(), pars, last_paste);
264                 } else if (pars[last_paste + 1].empty()) {
265                         pars[last_paste + 1].makeSameLayout(pars[last_paste]);
266                         mergeParagraph(buffer.params(), pars, last_paste);
267                 } else if (pars[last_paste].empty()) {
268                         pars[last_paste].makeSameLayout(pars[last_paste + 1]);
269                         mergeParagraph(buffer.params(), pars, last_paste);
270                 } else {
271                         pars[last_paste + 1].stripLeadingSpaces();
272                         ++last_paste;
273                 }
274         }
275
276         return make_pair(PitPosPair(pit, pos), last_paste + 1);
277 }
278
279
280 PitPosPair eraseSelectionHelper(BufferParams const & params,
281         ParagraphList & pars,
282         pit_type startpit, pit_type endpit,
283         int startpos, int endpos, bool doclear)
284 {
285         // Start of selection is really invalid.
286         if (startpit == pit_type(pars.size()) ||
287             (startpos > pars[startpit].size()))
288                 return PitPosPair(endpit, endpos);
289
290         // Start and end is inside same paragraph
291         if (endpit == pit_type(pars.size()) || startpit == endpit) {
292                 endpos -= pars[startpit].eraseChars(startpos, endpos, params.trackChanges);
293                 return PitPosPair(endpit, endpos);
294         }
295
296         for (pit_type pit = startpit; pit != endpit + 1;) {
297                 pos_type const left  = (pit == startpit ? startpos : 0);
298                 pos_type const right = (pit == endpit ? endpos : pars[pit].size() + 1);
299
300                 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
497                 // There is a problem with having the stuffing here in that the
498                 // larger the selection the slower LyX will get. This can be
499                 // solved by running the line below only when the selection has
500                 // finished. The solution used currently just works, to make it
501                 // faster we need to be more clever and probably also have more
502                 // calls to theSelection().put. (Lgb)
503 //              theSelection().put(cur.selectionAsString(true));
504
505
506                 // make sure that the depth behind the selection are restored, too
507                 recordUndoSelection(cur);
508                 pit_type begpit = cur.selBegin().pit();
509                 pit_type endpit = cur.selEnd().pit();
510
511                 int endpos = cur.selEnd().pos();
512
513                 BufferParams const & bp = cur.buffer().params();
514                 if (realcut) {
515                         copySelectionHelper(cur.buffer(),
516                                 text->paragraphs(),
517                                 begpit, endpit,
518                                 cur.selBegin().pos(), endpos,
519                                 bp.textclass);
520                 }
521
522                 boost::tie(endpit, endpos) =
523                         eraseSelectionHelper(bp,
524                                 text->paragraphs(),
525                                 begpit, endpit,
526                                 cur.selBegin().pos(), endpos,
527                                 doclear);
528
529                 // sometimes necessary
530                 if (doclear)
531                         text->paragraphs()[begpit].stripLeadingSpaces();
532
533                 // cutSelection can invalidate the cursor so we need to set
534                 // it anew. (Lgb)
535                 // we prefer the end for when tracking changes
536                 cur.pos() = endpos;
537                 cur.pit() = endpit;
538
539                 // need a valid cursor. (Lgb)
540                 cur.clearSelection();
541                 updateLabels(cur.buffer());
542
543                 // tell tabular that a recent copy happened
544                 dirtyTabularStack(false);
545         }
546
547         if (cur.inMathed()) {
548                 if (cur.selBegin().idx() != cur.selEnd().idx()) {
549                         // The current selection spans more than one cell.
550                         // Record all cells
551                         recordUndoInset(cur);
552                 } else {
553                         // Record only the current cell to avoid a jumping
554                         // cursor after undo
555                         recordUndo(cur);
556                 }
557                 if (realcut)
558                         copySelection(cur);
559                 eraseSelection(cur);
560         }
561 }
562
563
564 void copySelection(LCursor & cur)
565 {
566         // stuff the selection onto the X clipboard, from an explicit copy request
567         theClipboard().put(cur.selectionAsString(true));
568
569         // this doesn't make sense, if there is no selection
570         if (!cur.selection())
571                 return;
572
573         if (cur.inTexted()) {
574                 LyXText * text = cur.text();
575                 BOOST_ASSERT(text);
576                 // ok we have a selection. This is always between cur.selBegin()
577                 // and sel_end cursor
578
579                 // copy behind a space if there is one
580                 ParagraphList & pars = text->paragraphs();
581                 pos_type pos = cur.selBegin().pos();
582                 pit_type par = cur.selBegin().pit();
583                 while (pos < pars[par].size()
584                                          && pars[par].isLineSeparator(pos)
585                                          && (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
586                         ++pos;
587
588                 copySelectionHelper(cur.buffer(), pars, par, cur.selEnd().pit(),
589                         pos, cur.selEnd().pos(), cur.buffer().params().textclass);
590         }
591
592         if (cur.inMathed()) {
593                 //lyxerr << "copySelection in mathed" << endl;
594                 ParagraphList pars;
595                 Paragraph par;
596                 BufferParams const & bp = cur.buffer().params();
597                 par.layout(bp.getLyXTextClass().defaultLayout());
598                 par.insert(0, grabSelection(cur), LyXFont(), Change(Change::UNCHANGED));
599                 pars.push_back(par);
600                 theCuts.push(make_pair(pars, bp.textclass));
601         }
602         // tell tabular that a recent copy happened
603         dirtyTabularStack(false);
604 }
605
606
607 docstring getSelection(Buffer const & buf, size_t sel_index)
608 {
609         return sel_index < theCuts.size()
610                 ? theCuts[sel_index].first.back().asString(buf, false)
611                 : docstring();
612 }
613
614
615 void pasteParagraphList(LCursor & cur, ParagraphList const & parlist,
616                         textclass_type textclass, ErrorList & errorList)
617 {
618         if (cur.inTexted()) {
619                 LyXText * text = cur.text();
620                 BOOST_ASSERT(text);
621
622                 pit_type endpit;
623                 PitPosPair ppp;
624
625                 boost::tie(ppp, endpit) =
626                         pasteSelectionHelper(cur, parlist,
627                                              textclass, errorList);
628                 updateLabels(cur.buffer());
629                 cur.clearSelection();
630                 text->setCursor(cur, ppp.first, ppp.second);
631         }
632
633         // mathed is handled in InsetMathNest/InsetMathGrid
634         BOOST_ASSERT(!cur.inMathed());
635 }
636
637
638 void pasteSelection(LCursor & cur, ErrorList & errorList, size_t sel_index)
639 {
640         // this does not make sense, if there is nothing to paste
641         if (!checkPastePossible(sel_index))
642                 return;
643
644         recordUndo(cur);
645         pasteParagraphList(cur, theCuts[sel_index].first,
646                            theCuts[sel_index].second, errorList);
647         cur.setSelection();
648 }
649
650
651 // simple replacing. The font of the first selected character is used
652 void replaceSelectionWithString(LCursor & cur, string 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         string::const_iterator cit = str.begin();
665         string::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 << "LCursor::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         } else {
715                 lyxerr << "can't erase this selection 1" << endl;
716         }
717         //lyxerr << "LCursor::eraseSelection end: " << cur << endl;
718 }
719
720
721 void selDel(LCursor & cur)
722 {
723         //lyxerr << "LCursor::selDel" << endl;
724         if (cur.selection())
725                 eraseSelection(cur);
726 }
727
728
729 void selClearOrDel(LCursor & cur)
730 {
731         //lyxerr << "LCursor::selClearOrDel" << endl;
732         if (lyxrc.auto_region_delete)
733                 selDel(cur);
734         else
735                 cur.selection() = false;
736 }
737
738
739 docstring grabSelection(LCursor const & cur)
740 {
741         if (!cur.selection())
742                 return docstring();
743
744         // FIXME: What is wrong with the following?
745 #if 0
746         std::ostringstream os;
747         for (DocIterator dit = cur.selectionBegin();
748              dit != cur.selectionEnd(); dit.forwardPos())
749                 os << asString(dit.cell());
750         return os.str();
751 #endif
752
753         CursorSlice i1 = cur.selBegin();
754         CursorSlice i2 = cur.selEnd();
755
756         if (i1.idx() == i2.idx()) {
757                 if (i1.inset().asInsetMath()) {
758                         MathArray::const_iterator it = i1.cell().begin();
759                         return asString(MathArray(it + i1.pos(), it + i2.pos()));
760                 } else {
761                         return from_ascii("unknown selection 1");
762                 }
763         }
764
765         InsetBase::row_type r1, r2;
766         InsetBase::col_type c1, c2;
767         region(i1, i2, r1, r2, c1, c2);
768
769         docstring data;
770         if (i1.inset().asInsetMath()) {
771                 for (InsetBase::row_type row = r1; row <= r2; ++row) {
772                         if (row > r1)
773                                 data += "\\\\";
774                         for (InsetBase::col_type col = c1; col <= c2; ++col) {
775                                 if (col > c1)
776                                         data += '&';
777                                 data += asString(i1.asInsetMath()->
778                                         cell(i1.asInsetMath()->index(row, col)));
779                         }
780                 }
781         } else {
782                 data = from_ascii("unknown selection 2");
783         }
784         return data;
785 }
786
787
788 void dirtyTabularStack(bool b)
789 {
790         dirty_tabular_stack_ = b;
791 }
792
793
794 bool tabularStackDirty()
795 {
796         return dirty_tabular_stack_;
797 }
798
799
800 } // namespace cap
801
802 } // namespace lyx