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