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