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