]> git.lyx.org Git - lyx.git/blob - src/CutAndPaste.C
* CutAndPaste.C:
[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/Clipboard.h"
48
49 #include <boost/tuple/tuple.hpp>
50
51
52 namespace lyx {
53
54 using support::bformat;
55 using frontend::Clipboard;
56
57 using std::endl;
58 using std::for_each;
59 using std::make_pair;
60 using std::pair;
61 using std::vector;
62 using std::string;
63
64
65 namespace {
66
67 typedef std::pair<pit_type, int> PitPosPair;
68
69 typedef limited_stack<pair<ParagraphList, textclass_type> > CutStack;
70
71 CutStack theCuts(10);
72
73 // store whether the tabular stack is newer than the normal copy stack
74 // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
75 // when we (hopefully) have a one-for-all paste mechanism.
76 bool dirty_tabular_stack_;
77
78 class resetParagraph : public std::unary_function<Paragraph, Buffer const &> {
79 public:
80         resetParagraph(Buffer const & b) : buffer_(b) {}
81         void operator()(Paragraph & p) const {
82                 // FIXME: change tracking (MG)
83                 // set p's text to INSERTED in CT mode; clear CT info otherwise
84
85                 // ERT paragraphs have the Language latex_language.
86                 // This is invalid outside of ERT, so we need to change it
87                 // to the buffer language.
88                 if (p.ownerCode() == InsetBase::ERT_CODE) {
89                         p.changeLanguage(buffer_.params(), latex_language,
90                                          buffer_.getLanguage());
91                 }
92                 p.setInsetOwner(0);
93         }
94 private:
95         Buffer const & buffer_;
96 };
97
98
99 void region(CursorSlice const & i1, CursorSlice const & i2,
100         InsetBase::row_type & r1, InsetBase::row_type & r2,
101         InsetBase::col_type & c1, InsetBase::col_type & c2)
102 {
103         InsetBase & p = i1.inset();
104         c1 = p.col(i1.idx());
105         c2 = p.col(i2.idx());
106         if (c1 > c2)
107                 std::swap(c1, c2);
108         r1 = p.row(i1.idx());
109         r2 = p.row(i2.idx());
110         if (r1 > r2)
111                 std::swap(r1, r2);
112 }
113
114
115 bool checkPastePossible(int index)
116 {
117         return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
118 }
119
120
121 pair<PitPosPair, pit_type>
122 pasteSelectionHelper(LCursor & cur, ParagraphList const & parlist,
123                      textclass_type textclass, ErrorList & errorlist)
124 {
125         Buffer const & buffer = cur.buffer();
126         pit_type pit = cur.pit();
127         pos_type pos = cur.pos();
128         ParagraphList & pars = cur.text()->paragraphs();
129
130         if (parlist.empty())
131                 return make_pair(PitPosPair(pit, pos), pit);
132
133         BOOST_ASSERT (pos <= pars[pit].size());
134
135         // Make a copy of the CaP paragraphs.
136         ParagraphList insertion = parlist;
137         textclass_type const tc = buffer.params().textclass;
138
139         // Now remove all out of the pars which is NOT allowed in the
140         // new environment and set also another font if that is required.
141
142         // Convert newline to paragraph break in ERT inset.
143         // This should not be here!
144         if (pars[pit].inInset() &&
145             pars[pit].inInset()->lyxCode() == InsetBase::ERT_CODE) {
146                 for (ParagraphList::size_type i = 0; i < insertion.size(); ++i) {
147                         for (pos_type j = 0; j < insertion[i].size(); ++j) {
148                                 if (insertion[i].isNewline(j)) {
149                                         // do not track deletion of newline
150                                         insertion[i].eraseChar(j, false);
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         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         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                                 // do not track deletion of invalid insets
210                                 tmpbuf->eraseChar(i--, false);
211                 }
212
213                 // FIXME: Change tracking (MG)
214                 // set tmpbuf's text to INSERTED in CT mode; clear CT info otherwise
215         }
216
217         bool const empty = pars[pit].empty();
218         if (!empty) {
219                 // Make the buf exactly the same layout as the cursor
220                 // paragraph.
221                 insertion.begin()->makeSameLayout(pars[pit]);
222         }
223
224         // Prepare the paragraphs and insets for insertion.
225         // A couple of insets store buffer references so need updating.
226         insertion.swap(in.paragraphs());
227
228         ParIterator fpit = par_iterator_begin(in);
229         ParIterator fend = par_iterator_end(in);
230
231         for (; fpit != fend; ++fpit) {
232                 InsetList::iterator lit = fpit->insetlist.begin();
233                 InsetList::iterator eit = fpit->insetlist.end();
234
235                 for (; lit != eit; ++lit) {
236                         switch (lit->inset->lyxCode()) {
237                         case InsetBase::TABULAR_CODE: {
238                                 InsetTabular * it = static_cast<InsetTabular*>(lit->inset);
239                                 it->buffer(&buffer);
240                                 break;
241                         }
242
243                         default:
244                                 break; // nothing
245                         }
246                 }
247         }
248         insertion.swap(in.paragraphs());
249
250         // Split the paragraph for inserting the buf if necessary.
251         if (!empty)
252                 breakParagraphConservative(buffer.params(), pars, pit, pos);
253
254         // Paste it!
255         if (empty) {
256                 pars.insert(boost::next(pars.begin(), pit),
257                             insertion.begin(),
258                             insertion.end());
259
260                 // merge the empty par with the last par of the insertion
261                 mergeParagraph(buffer.params(), pars,
262                                pit + insertion.size() - 1);
263         } else {
264                 pars.insert(boost::next(pars.begin(), pit + 1),
265                             insertion.begin(),
266                             insertion.end());
267
268                 // merge the first par of the insertion with the current par
269                 mergeParagraph(buffer.params(), pars, pit);
270         }
271
272         pit_type last_paste = pit + insertion.size() - 1;
273
274         // Store the new cursor position.
275         pit = last_paste;
276         pos = pars[last_paste].size();
277
278         // Join (conditionally) last pasted paragraph with next one, i.e.,
279         // the tail of the spliced document paragraph
280         if (!empty && last_paste + 1 != pit_type(pars.size())) {
281                 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
282                         mergeParagraph(buffer.params(), pars, last_paste);
283                 } else if (pars[last_paste + 1].empty()) {
284                         pars[last_paste + 1].makeSameLayout(pars[last_paste]);
285                         mergeParagraph(buffer.params(), pars, last_paste);
286                 } else if (pars[last_paste].empty()) {
287                         pars[last_paste].makeSameLayout(pars[last_paste + 1]);
288                         mergeParagraph(buffer.params(), pars, last_paste);
289                 } else {
290                         pars[last_paste + 1].stripLeadingSpaces();
291                         ++last_paste;
292                 }
293         }
294
295         return make_pair(PitPosPair(pit, pos), last_paste + 1);
296 }
297
298
299 PitPosPair eraseSelectionHelper(BufferParams const & params,
300         ParagraphList & pars,
301         pit_type startpit, pit_type endpit,
302         int startpos, int endpos, bool doclear)
303 {
304         // Start of selection is really invalid.
305         if (startpit == pit_type(pars.size()) ||
306             (startpos > pars[startpit].size()))
307                 return PitPosPair(endpit, endpos);
308
309         // Start and end is inside same paragraph
310         if (endpit == pit_type(pars.size()) ||
311             startpit == endpit) {
312                 endpos -= pars[startpit].eraseChars(startpos, endpos, false);
313                 return PitPosPair(endpit, endpos);
314         }
315
316         // A paragraph break has to be physically removed by merging, but
317         // only if either (1) change tracking is off, or (2) the para break
318         // is "blue"
319         for (pit_type pit = startpit; pit != endpit + 1;) {
320                 // FIXME: Change tracking (MG)
321                 bool const merge = !params.trackChanges ||
322                                    pars[pit].isInserted(pars[pit].size());
323                 pos_type const left  = ( pit == startpit ? startpos : 0 );
324                 pos_type const right = ( pit == endpit ? endpos :
325                                 pars[pit].size() + 1 );
326                 // Logical erase only:
327                 pars[pit].eraseChars(left, right, false);
328                 // Separate handling of para break:
329                 if (merge && pit != endpit &&
330                    (pit + 1 != endpit || pars[pit].hasSameLayout(pars[pit + 1]))) {
331                         pos_type const thissize = pars[pit].size();
332                         if (doclear)
333                                 pars[pit + 1].stripLeadingSpaces();
334                         mergeParagraph(params, pars, pit);
335                         --endpit;
336                         if (pit == endpit)
337                                 endpos += thissize;
338                 } else
339                         ++pit;
340         }
341
342         // Ensure legal cursor pos:
343         endpit = startpit;
344         endpos = startpos;
345         return PitPosPair(endpit, endpos);
346 }
347
348
349 void copySelectionHelper(Buffer const & buf, ParagraphList & pars,
350         pit_type startpit, pit_type endpit,
351         int start, int end, textclass_type tc)
352 {
353         BOOST_ASSERT(0 <= start && start <= pars[startpit].size());
354         BOOST_ASSERT(0 <= end && end <= pars[endpit].size());
355         BOOST_ASSERT(startpit != endpit || start <= end);
356
357         // Clone the paragraphs within the selection.
358         ParagraphList paragraphs(boost::next(pars.begin(), startpit),
359                                  boost::next(pars.begin(), endpit + 1));
360
361         for_each(paragraphs.begin(), paragraphs.end(), resetParagraph(buf));
362
363         // Cut out the end of the last paragraph.
364         Paragraph & back = paragraphs.back();
365         // do not track deletion here; it is an internal action not visible to the user
366         back.eraseChars(end, back.size(), false);
367
368         // Cut out the begin of the first paragraph
369         Paragraph & front = paragraphs.front();
370         // again, do not track deletion
371         front.eraseChars(0, start, false);
372
373         theCuts.push(make_pair(paragraphs, tc));
374 }
375
376 } // namespace anon
377
378
379
380
381 namespace cap {
382
383 docstring grabAndEraseSelection(LCursor & cur)
384 {
385         if (!cur.selection())
386                 return docstring();
387         docstring res = grabSelection(cur);
388         eraseSelection(cur);
389         return res;
390 }
391
392
393 void switchBetweenClasses(textclass_type c1, textclass_type c2,
394         InsetText & in, ErrorList & errorlist)
395 {
396         BOOST_ASSERT(!in.paragraphs().empty());
397         if (c1 == c2)
398                 return;
399
400         LyXTextClass const & tclass1 = textclasslist[c1];
401         LyXTextClass const & tclass2 = textclasslist[c2];
402
403         // layouts
404         ParIterator end = par_iterator_end(in);
405         for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
406                 string const name = it->layout()->name();
407                 bool hasLayout = tclass2.hasLayout(name);
408
409                 if (hasLayout)
410                         it->layout(tclass2[name]);
411                 else
412                         it->layout(tclass2.defaultLayout());
413
414                 if (!hasLayout && name != tclass1.defaultLayoutName()) {
415                         docstring const s = bformat(
416                                                  _("Layout had to be changed from\n%1$s to %2$s\n"
417                                                 "because of class conversion from\n%3$s to %4$s"),
418                          from_utf8(name), from_utf8(it->layout()->name()),
419                          from_utf8(tclass1.name()), from_utf8(tclass2.name()));
420                         // To warn the user that something had to be done.
421                         errorlist.push_back(ErrorItem(_("Changed Layout"), s,
422                                                       it->id(), 0,
423                                                       it->size()));
424                 }
425         }
426
427         // character styles
428         InsetIterator const i_end = inset_iterator_end(in);
429         for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
430                 if (it->lyxCode() == InsetBase::CHARSTYLE_CODE) {
431                         InsetCharStyle & inset =
432                                 static_cast<InsetCharStyle &>(*it);
433                         string const name = inset.params().type;
434                         CharStyles::iterator const found_cs =
435                                 tclass2.charstyle(name);
436                         if (found_cs == tclass2.charstyles().end()) {
437                                 // The character style is undefined in tclass2
438                                 inset.setUndefined();
439                                 docstring const s = bformat(_(
440                                         "Character style %1$s is "
441                                         "undefined because of class "
442                                         "conversion from\n%2$s to %3$s"),
443                                          from_utf8(name), from_utf8(tclass1.name()),
444                                          from_utf8(tclass2.name()));
445                                 // To warn the user that something had to be done.
446                                 errorlist.push_back(ErrorItem(
447                                         _("Undefined character style"),
448                                         s, it.paragraph().id(), it.pos(), it.pos() + 1));
449                         } else if (inset.undefined()) {
450                                 // The character style is undefined in
451                                 // tclass1 and is defined in tclass2
452                                 inset.setDefined(found_cs);
453                         }
454                 }
455         }
456 }
457
458
459 std::vector<docstring> const availableSelections(Buffer const & buffer)
460 {
461         vector<docstring> selList;
462
463         CutStack::const_iterator cit = theCuts.begin();
464         CutStack::const_iterator end = theCuts.end();
465         for (; cit != end; ++cit) {
466                 // we do not use cit-> here because gcc 2.9x does not
467                 // like it (JMarc)
468                 ParagraphList const & pars = (*cit).first;
469                 docstring asciiSel;
470                 ParagraphList::const_iterator pit = pars.begin();
471                 ParagraphList::const_iterator pend = pars.end();
472                 for (; pit != pend; ++pit) {
473                         asciiSel += pit->asString(buffer, false);
474                         if (asciiSel.size() > 25) {
475                                 asciiSel.replace(22, docstring::npos,
476                                                  from_ascii("..."));
477                                 break;
478                         }
479                 }
480
481                 selList.push_back(asciiSel);
482         }
483
484         return selList;
485 }
486
487
488 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 theSelection().put. (Lgb)
514 //              theSelection().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         theClipboard().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                 // FIXME: change tracking (MG)
611                 pars.back().insert(0, grabSelection(cur), LyXFont(), Change(Change::UNCHANGED));
612                 theCuts.push(make_pair(pars, bp.textclass));
613         }
614         // tell tabular that a recent copy happened
615         dirtyTabularStack(false);
616 }
617
618
619 docstring 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                 : docstring();
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, cur.buffer().params().trackChanges);
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, -int(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 docstring grabSelection(LCursor const & cur)
753 {
754         if (!cur.selection())
755                 return docstring();
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 from_ascii("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         docstring 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 = from_ascii("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
815 } // namespace lyx