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