]> git.lyx.org Git - lyx.git/blob - src/CutAndPaste.C
Change tracking:
[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 using lyx::docstring;
52 using lyx::pos_type;
53 using lyx::pit_type;
54 using lyx::textclass_type;
55
56 using lyx::support::bformat;
57
58 using lyx::frontend::Clipboard;
59
60 using std::endl;
61 using std::for_each;
62 using std::make_pair;
63 using std::pair;
64 using std::vector;
65 using std::string;
66
67
68 namespace {
69
70 typedef std::pair<lyx::pit_type, int> PitPosPair;
71
72 typedef limited_stack<pair<ParagraphList, textclass_type> > CutStack;
73
74 CutStack theCuts(10);
75
76 // store whether the tabular stack is newer than the normal copy stack
77 // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
78 // when we (hopefully) have a one-for-all paste mechanism.
79 bool dirty_tabular_stack_;
80
81 class resetParagraph : public std::unary_function<Paragraph, Buffer const &> {
82 public:
83         resetParagraph(Buffer const & b) : buffer_(b) {}
84         void operator()(Paragraph & p) const {
85                 // FIXME: change tracking (MG)
86                 // set p's text to INSERTED in CT mode; clear CT info otherwise
87
88                 // ERT paragraphs have the Language latex_language.
89                 // This is invalid outside of ERT, so we need to change it
90                 // to the buffer language.
91                 if (p.ownerCode() == InsetBase::ERT_CODE) {
92                         p.changeLanguage(buffer_.params(), latex_language,
93                                          buffer_.getLanguage());
94                 }
95                 p.setInsetOwner(0);
96         }
97 private:
98         Buffer const & buffer_;
99 };
100
101
102 void region(CursorSlice const & i1, CursorSlice const & i2,
103         InsetBase::row_type & r1, InsetBase::row_type & r2,
104         InsetBase::col_type & c1, InsetBase::col_type & c2)
105 {
106         InsetBase & p = i1.inset();
107         c1 = p.col(i1.idx());
108         c2 = p.col(i2.idx());
109         if (c1 > c2)
110                 std::swap(c1, c2);
111         r1 = p.row(i1.idx());
112         r2 = p.row(i2.idx());
113         if (r1 > r2)
114                 std::swap(r1, r2);
115 }
116
117
118 bool checkPastePossible(int index)
119 {
120         return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
121 }
122
123
124 pair<PitPosPair, pit_type>
125 pasteSelectionHelper(LCursor & cur, ParagraphList const & parlist,
126                      textclass_type textclass, ErrorList & errorlist)
127 {
128         Buffer const & buffer = cur.buffer();
129         pit_type pit = cur.pit();
130         pos_type pos = cur.pos();
131         ParagraphList & pars = cur.text()->paragraphs();
132
133         if (parlist.empty())
134                 return make_pair(PitPosPair(pit, pos), pit);
135
136         BOOST_ASSERT (pos <= pars[pit].size());
137
138         // Make a copy of the CaP paragraphs.
139         ParagraphList insertion = parlist;
140         textclass_type const tc = buffer.params().textclass;
141
142         // Now remove all out of the pars which is NOT allowed in the
143         // new environment and set also another font if that is required.
144
145         // Convert newline to paragraph break in ERT inset.
146         // This should not be here!
147         if (pars[pit].inInset() &&
148             pars[pit].inInset()->lyxCode() == InsetBase::ERT_CODE) {
149                 for (ParagraphList::size_type i = 0; i < insertion.size(); ++i) {
150                         for (pos_type j = 0; j < insertion[i].size(); ++j) {
151                                 if (insertion[i].isNewline(j)) {
152                                         insertion[i].erase(j);
153                                         breakParagraphConservative(
154                                                         buffer.params(),
155                                                         insertion, i, j);
156                                 }
157                         }
158                 }
159         }
160
161         // If we are in an inset which returns forceDefaultParagraphs,
162         // set the paragraphs to default
163         if (cur.inset().forceDefaultParagraphs(cur.idx())) {
164                 LyXLayout_ptr const layout = 
165                         buffer.params().getLyXTextClass().defaultLayout();
166                 ParagraphList::iterator const end = insertion.end();
167                 for (ParagraphList::iterator par = insertion.begin(); 
168                                 par != end; ++par)
169                         par->layout(layout);
170         }
171
172         // Make sure there is no class difference.
173         InsetText in;
174         // This works without copying any paragraph data because we have
175         // a specialized swap method for ParagraphList. This is important
176         // since we store pointers to insets at some places and we don't
177         // want to invalidate them.
178         insertion.swap(in.paragraphs());
179         lyx::cap::switchBetweenClasses(textclass, tc, in, errorlist);
180         insertion.swap(in.paragraphs());
181
182         ParagraphList::iterator tmpbuf = insertion.begin();
183         int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
184
185         Paragraph::depth_type max_depth = pars[pit].getMaxDepthAfter();
186
187         for (; tmpbuf != insertion.end(); ++tmpbuf) {
188                 // If we have a negative jump so that the depth would
189                 // go below 0 depth then we have to redo the delta to
190                 // this new max depth level so that subsequent
191                 // paragraphs are aligned correctly to this paragraph
192                 // at level 0.
193                 if (int(tmpbuf->params().depth()) + depth_delta < 0)
194                         depth_delta = 0;
195
196                 // Set the right depth so that we are not too deep or shallow.
197                 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
198                 if (tmpbuf->params().depth() > max_depth)
199                         tmpbuf->params().depth(max_depth);
200
201                 // Only set this from the 2nd on as the 2nd depends
202                 // for maxDepth still on pit.
203                 if (tmpbuf != insertion.begin())
204                         max_depth = tmpbuf->getMaxDepthAfter();
205
206                 // Set the inset owner of this paragraph.
207                 tmpbuf->setInsetOwner(pars[pit].inInset());
208                 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
209                         if (tmpbuf->getChar(i) == Paragraph::META_INSET &&
210                             !pars[pit].insetAllowed(tmpbuf->getInset(i)->lyxCode()))
211                                 tmpbuf->erase(i--);
212                 }
213
214                 // FIXME: Change tracking (MG)
215                 // set tmpbuf's text to INSERTED in CT mode; clear CT info otherwise
216         }
217
218         bool const empty = pars[pit].empty();
219         if (!empty) {
220                 // Make the buf exactly the same layout as the cursor
221                 // paragraph.
222                 insertion.begin()->makeSameLayout(pars[pit]);
223         }
224
225         // Prepare the paragraphs and insets for insertion.
226         // A couple of insets store buffer references so need updating.
227         insertion.swap(in.paragraphs());
228
229         ParIterator fpit = par_iterator_begin(in);
230         ParIterator fend = par_iterator_end(in);
231
232         for (; fpit != fend; ++fpit) {
233                 InsetList::iterator lit = fpit->insetlist.begin();
234                 InsetList::iterator eit = fpit->insetlist.end();
235
236                 for (; lit != eit; ++lit) {
237                         switch (lit->inset->lyxCode()) {
238                         case InsetBase::TABULAR_CODE: {
239                                 InsetTabular * it = static_cast<InsetTabular*>(lit->inset);
240                                 it->buffer(&buffer);
241                                 break;
242                         }
243
244                         default:
245                                 break; // nothing
246                         }
247                 }
248         }
249         insertion.swap(in.paragraphs());
250
251         // Split the paragraph for inserting the buf if necessary.
252         if (!empty)
253                 breakParagraphConservative(buffer.params(), pars, pit, pos);
254
255         // Paste it!
256         if (empty) {
257                 pars.insert(boost::next(pars.begin(), pit),
258                             insertion.begin(),
259                             insertion.end());
260
261                 // merge the empty par with the last par of the insertion
262                 mergeParagraph(buffer.params(), pars,
263                                pit + insertion.size() - 1);
264         } else {
265                 pars.insert(boost::next(pars.begin(), pit + 1),
266                             insertion.begin(),
267                             insertion.end());
268
269                 // merge the first par of the insertion with the current par
270                 mergeParagraph(buffer.params(), pars, pit);
271         }
272
273         pit_type last_paste = pit + insertion.size() - 1;
274
275         // Store the new cursor position.
276         pit = last_paste;
277         pos = pars[last_paste].size();
278
279         // Join (conditionally) last pasted paragraph with next one, i.e.,
280         // the tail of the spliced document paragraph
281         if (!empty && last_paste + 1 != pit_type(pars.size())) {
282                 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
283                         mergeParagraph(buffer.params(), pars, last_paste);
284                 } else if (pars[last_paste + 1].empty()) {
285                         pars[last_paste + 1].makeSameLayout(pars[last_paste]);
286                         mergeParagraph(buffer.params(), pars, last_paste);
287                 } else if (pars[last_paste].empty()) {
288                         pars[last_paste].makeSameLayout(pars[last_paste + 1]);
289                         mergeParagraph(buffer.params(), pars, last_paste);
290                 } else {
291                         pars[last_paste + 1].stripLeadingSpaces();
292                         ++last_paste;
293                 }
294         }
295
296         return make_pair(PitPosPair(pit, pos), last_paste + 1);
297 }
298
299
300 PitPosPair eraseSelectionHelper(BufferParams const & params,
301         ParagraphList & pars,
302         pit_type startpit, pit_type endpit,
303         int startpos, int endpos, bool doclear)
304 {
305         // Start of selection is really invalid.
306         if (startpit == pit_type(pars.size()) ||
307             (startpos > pars[startpit].size()))
308                 return PitPosPair(endpit, endpos);
309
310         // Start and end is inside same paragraph
311         if (endpit == pit_type(pars.size()) ||
312             startpit == endpit) {
313                 endpos -= pars[startpit].erase(startpos, endpos);
314                 return PitPosPair(endpit, endpos);
315         }
316
317         // A paragraph break has to be physically removed by merging, but
318         // only if either (1) change tracking is off, or (2) the para break
319         // is "blue"
320         for (pit_type pit = startpit; pit != endpit + 1;) {
321                 // FIXME: Change tracking (MG)
322                 bool const merge = !params.trackChanges ||
323                         pars[pit].lookupChange(pars[pit].size()) ==
324                         Change(Change::INSERTED);
325                 pos_type const left  = ( pit == startpit ? startpos : 0 );
326                 pos_type const right = ( pit == endpit ? endpos :
327                                 pars[pit].size() + 1 );
328                 // Logical erase only:
329                 pars[pit].erase(left, right);
330                 // Separate handling of para break:
331                 if (merge && pit != endpit &&
332                    (pit + 1 != endpit || pars[pit].hasSameLayout(pars[pit + 1]))) {
333                         pos_type const thissize = pars[pit].size();
334                         if (doclear)
335                                 pars[pit + 1].stripLeadingSpaces();
336                         mergeParagraph(params, pars, pit);
337                         --endpit;
338                         if (pit == endpit)
339                                 endpos += thissize;
340                 } else
341                         ++pit;
342         }
343
344         // Ensure legal cursor pos:
345         endpit = startpit;
346         endpos = startpos;
347         return PitPosPair(endpit, endpos);
348 }
349
350
351 void copySelectionHelper(Buffer const & buf, ParagraphList & pars,
352         pit_type startpit, pit_type endpit,
353         int start, int end, textclass_type tc)
354 {
355         BOOST_ASSERT(0 <= start && start <= pars[startpit].size());
356         BOOST_ASSERT(0 <= end && end <= pars[endpit].size());
357         BOOST_ASSERT(startpit != endpit || start <= end);
358
359         // Clone the paragraphs within the selection.
360         ParagraphList paragraphs(boost::next(pars.begin(), startpit),
361                                  boost::next(pars.begin(), endpit + 1));
362
363         for_each(paragraphs.begin(), paragraphs.end(), resetParagraph(buf));
364
365         // Cut out the end of the last paragraph.
366         Paragraph & back = paragraphs.back();
367         back.erase(end, back.size());
368
369         // Cut out the begin of the first paragraph
370         Paragraph & front = paragraphs.front();
371         front.erase(0, start);
372
373         theCuts.push(make_pair(paragraphs, tc));
374 }
375
376 } // namespace anon
377
378
379
380
381 namespace lyx {
382 namespace cap {
383
384 string grabAndEraseSelection(LCursor & cur)
385 {
386         if (!cur.selection())
387                 return string();
388         string res = grabSelection(cur);
389         eraseSelection(cur);
390         return res;
391 }
392
393
394 void switchBetweenClasses(textclass_type c1, textclass_type c2,
395         InsetText & in, ErrorList & errorlist)
396 {
397         BOOST_ASSERT(!in.paragraphs().empty());
398         if (c1 == c2)
399                 return;
400
401         LyXTextClass const & tclass1 = textclasslist[c1];
402         LyXTextClass const & tclass2 = textclasslist[c2];
403
404         // layouts
405         ParIterator end = par_iterator_end(in);
406         for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
407                 string const name = it->layout()->name();
408                 bool hasLayout = tclass2.hasLayout(name);
409
410                 if (hasLayout)
411                         it->layout(tclass2[name]);
412                 else
413                         it->layout(tclass2.defaultLayout());
414
415                 if (!hasLayout && name != tclass1.defaultLayoutName()) {
416                         docstring const s = bformat(
417                                                  _("Layout had to be changed from\n%1$s to %2$s\n"
418                                                 "because of class conversion from\n%3$s to %4$s"),
419                          lyx::from_utf8(name), lyx::from_utf8(it->layout()->name()),
420                          lyx::from_utf8(tclass1.name()), lyx::from_utf8(tclass2.name()));
421                         // To warn the user that something had to be done.
422                         errorlist.push_back(ErrorItem(_("Changed Layout"), s,
423                                                       it->id(), 0,
424                                                       it->size()));
425                 }
426         }
427
428         // character styles
429         InsetIterator const i_end = inset_iterator_end(in);
430         for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
431                 if (it->lyxCode() == InsetBase::CHARSTYLE_CODE) {
432                         InsetCharStyle & inset =
433                                 static_cast<InsetCharStyle &>(*it);
434                         string const name = inset.params().type;
435                         CharStyles::iterator const found_cs =
436                                 tclass2.charstyle(name);
437                         if (found_cs == tclass2.charstyles().end()) {
438                                 // The character style is undefined in tclass2
439                                 inset.setUndefined();
440                                 docstring const s = bformat(_(
441                                         "Character style %1$s is "
442                                         "undefined because of class "
443                                         "conversion from\n%2$s to %3$s"),
444                                          lyx::from_utf8(name), lyx::from_utf8(tclass1.name()),
445                                          lyx::from_utf8(tclass2.name()));
446                                 // To warn the user that something had to be done.
447                                 errorlist.push_back(ErrorItem(
448                                         _("Undefined character style"),
449                                         s, it.paragraph().id(), it.pos(), it.pos() + 1));
450                         } else if (inset.undefined()) {
451                                 // The character style is undefined in
452                                 // tclass1 and is defined in tclass2
453                                 inset.setDefined(found_cs);
454                         }
455                 }
456         }
457 }
458
459
460 std::vector<docstring> const availableSelections(Buffer const & buffer)
461 {
462         vector<docstring> selList;
463
464         CutStack::const_iterator cit = theCuts.begin();
465         CutStack::const_iterator end = theCuts.end();
466         for (; cit != end; ++cit) {
467                 // we do not use cit-> here because gcc 2.9x does not
468                 // like it (JMarc)
469                 ParagraphList const & pars = (*cit).first;
470                 docstring asciiSel;
471                 ParagraphList::const_iterator pit = pars.begin();
472                 ParagraphList::const_iterator pend = pars.end();
473                 for (; pit != pend; ++pit) {
474                         asciiSel += pit->asString(buffer, false);
475                         if (asciiSel.size() > 25) {
476                                 asciiSel.replace(22, docstring::npos,
477                                                  lyx::from_ascii("..."));
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 theSelection().put. (Lgb)
515 //              theSelection().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         theClipboard().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 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                 // FIXME: change tracking (MG)
681                 par.insertChar(pos, (*cit), font, Change(Change::INSERTED));
682
683         // Cut the selection
684         cutSelection(cur, true, false);
685
686         // select the replacement
687         if (backwards) {
688                 selbeg.pos() += str.length();
689                 cur.setSelection(selbeg, -str.length());
690         } else
691                 cur.setSelection(selbeg, str.length());
692 }
693
694
695 void replaceSelection(LCursor & cur)
696 {
697         if (cur.selection())
698                 cutSelection(cur, true, false);
699 }
700
701
702 void eraseSelection(LCursor & cur)
703 {
704         //lyxerr << "LCursor::eraseSelection begin: " << cur << endl;
705         CursorSlice const & i1 = cur.selBegin();
706         CursorSlice const & i2 = cur.selEnd();
707         if (i1.inset().asInsetMath()) {
708                 cur.top() = i1;
709                 if (i1.idx() == i2.idx()) {
710                         i1.cell().erase(i1.pos(), i2.pos());
711                         // We may have deleted i1.cell(cur.pos()).
712                         // Make sure that pos is valid.
713                         if (cur.pos() > cur.lastpos())
714                                 cur.pos() = cur.lastpos();
715                 } else {
716                         InsetMath * p = i1.asInsetMath();
717                         InsetBase::row_type r1, r2;
718                         InsetBase::col_type c1, c2;
719                         region(i1, i2, r1, r2, c1, c2);
720                         for (InsetBase::row_type row = r1; row <= r2; ++row)
721                                 for (InsetBase::col_type col = c1; col <= c2; ++col)
722                                         p->cell(p->index(row, col)).clear();
723                         // We've deleted the whole cell. Only pos 0 is valid.
724                         cur.pos() = 0;
725                 }
726                 // need a valid cursor. (Lgb)
727                 cur.clearSelection();
728         } else {
729                 lyxerr << "can't erase this selection 1" << endl;
730         }
731         //lyxerr << "LCursor::eraseSelection end: " << cur << endl;
732 }
733
734
735 void selDel(LCursor & cur)
736 {
737         //lyxerr << "LCursor::selDel" << endl;
738         if (cur.selection())
739                 eraseSelection(cur);
740 }
741
742
743 void selClearOrDel(LCursor & cur)
744 {
745         //lyxerr << "LCursor::selClearOrDel" << endl;
746         if (lyxrc.auto_region_delete)
747                 selDel(cur);
748         else
749                 cur.selection() = false;
750 }
751
752
753 string grabSelection(LCursor const & cur)
754 {
755         if (!cur.selection())
756                 return string();
757
758         // FIXME: What is wrong with the following?
759 #if 0
760         std::ostringstream os;
761         for (DocIterator dit = cur.selectionBegin();
762              dit != cur.selectionEnd(); dit.forwardPos())
763                 os << asString(dit.cell());
764         return os.str();
765 #endif
766
767         CursorSlice i1 = cur.selBegin();
768         CursorSlice i2 = cur.selEnd();
769
770         if (i1.idx() == i2.idx()) {
771                 if (i1.inset().asInsetMath()) {
772                         MathArray::const_iterator it = i1.cell().begin();
773                         return asString(MathArray(it + i1.pos(), it + i2.pos()));
774                 } else {
775                         return "unknown selection 1";
776                 }
777         }
778
779         InsetBase::row_type r1, r2;
780         InsetBase::col_type c1, c2;
781         region(i1, i2, r1, r2, c1, c2);
782
783         string data;
784         if (i1.inset().asInsetMath()) {
785                 for (InsetBase::row_type row = r1; row <= r2; ++row) {
786                         if (row > r1)
787                                 data += "\\\\";
788                         for (InsetBase::col_type col = c1; col <= c2; ++col) {
789                                 if (col > c1)
790                                         data += '&';
791                                 data += asString(i1.asInsetMath()->
792                                         cell(i1.asInsetMath()->index(row, col)));
793                         }
794                 }
795         } else {
796                 data = "unknown selection 2";
797         }
798         return data;
799 }
800
801
802 void dirtyTabularStack(bool b)
803 {
804         dirty_tabular_stack_ = b;
805 }
806
807
808 bool tabularStackDirty()
809 {
810         return dirty_tabular_stack_;
811 }
812
813
814 } // namespace cap
815 } // namespace lyx