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