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