]> git.lyx.org Git - lyx.git/blob - src/CutAndPaste.C
* src/CutAndPaste.C (pasteSelectionHelper):
[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         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                                 tmpbuf->erase(i--);
213                 }
214
215                 // reset change tracking status
216                 if (buffer.params().tracking_changes)
217                         tmpbuf->cleanChanges(Paragraph::trackingOn);
218                 else
219                         tmpbuf->cleanChanges(Paragraph::trackingOff);
220         }
221
222         bool const empty = pars[pit].empty();
223         if (!empty) {
224                 // Make the buf exactly the same layout as the cursor
225                 // paragraph.
226                 insertion.begin()->makeSameLayout(pars[pit]);
227         }
228
229         // Prepare the paragraphs and insets for insertion.
230         // A couple of insets store buffer references so need updating.
231         insertion.swap(in.paragraphs());
232
233         ParIterator fpit = par_iterator_begin(in);
234         ParIterator fend = par_iterator_end(in);
235
236         for (; fpit != fend; ++fpit) {
237                 InsetList::iterator lit = fpit->insetlist.begin();
238                 InsetList::iterator eit = fpit->insetlist.end();
239
240                 for (; lit != eit; ++lit) {
241                         switch (lit->inset->lyxCode()) {
242                         case InsetBase::TABULAR_CODE: {
243                                 InsetTabular * it = static_cast<InsetTabular*>(lit->inset);
244                                 it->buffer(&buffer);
245                                 break;
246                         }
247
248                         default:
249                                 break; // nothing
250                         }
251                 }
252         }
253         insertion.swap(in.paragraphs());
254
255         // Split the paragraph for inserting the buf if necessary.
256         if (!empty)
257                 breakParagraphConservative(buffer.params(), pars, pit, pos);
258
259         // Paste it!
260         if (empty) {
261                 pars.insert(boost::next(pars.begin(), pit),
262                             insertion.begin(),
263                             insertion.end());
264
265                 // merge the empty par with the last par of the insertion
266                 mergeParagraph(buffer.params(), pars,
267                                pit + insertion.size() - 1);
268         } else {
269                 pars.insert(boost::next(pars.begin(), pit + 1),
270                             insertion.begin(),
271                             insertion.end());
272
273                 // merge the first par of the insertion with the current par
274                 mergeParagraph(buffer.params(), pars, pit);
275         }
276
277         pit_type last_paste = pit + insertion.size() - 1;
278
279         // Store the new cursor position.
280         pit = last_paste;
281         pos = pars[last_paste].size();
282
283         // Join (conditionally) last pasted paragraph with next one, i.e.,
284         // the tail of the spliced document paragraph
285         if (!empty && last_paste + 1 != pit_type(pars.size())) {
286                 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
287                         mergeParagraph(buffer.params(), pars, last_paste);
288                 } else if (pars[last_paste + 1].empty()) {
289                         pars[last_paste + 1].makeSameLayout(pars[last_paste]);
290                         mergeParagraph(buffer.params(), pars, last_paste);
291                 } else if (pars[last_paste].empty()) {
292                         pars[last_paste].makeSameLayout(pars[last_paste + 1]);
293                         mergeParagraph(buffer.params(), pars, last_paste);
294                 } else {
295                         pars[last_paste + 1].stripLeadingSpaces();
296                         ++last_paste;
297                 }
298         }
299
300         return make_pair(PitPosPair(pit, pos), last_paste + 1);
301 }
302
303
304 PitPosPair eraseSelectionHelper(BufferParams const & params,
305         ParagraphList & pars,
306         pit_type startpit, pit_type endpit,
307         int startpos, int endpos, bool doclear)
308 {
309         // Start of selection is really invalid.
310         if (startpit == pit_type(pars.size()) ||
311             (startpos > pars[startpit].size()))
312                 return PitPosPair(endpit, endpos);
313
314         // Start and end is inside same paragraph
315         if (endpit == pit_type(pars.size()) ||
316             startpit == endpit) {
317                 endpos -= pars[startpit].erase(startpos, endpos);
318                 return PitPosPair(endpit, endpos);
319         }
320
321         // A paragraph break has to be physically removed by merging, but
322         // only if either (1) change tracking is off, or (2) the para break
323         // is "blue"
324         for (pit_type pit = startpit; pit != endpit + 1;) {
325                 bool const merge = !params.tracking_changes ||
326                         pars[pit].lookupChange(pars[pit].size()) ==
327                         Change::INSERTED;
328                 pos_type const left  = ( pit == startpit ? startpos : 0 );
329                 pos_type const right = ( pit == endpit ? endpos :
330                                 pars[pit].size() + 1 );
331                 // Logical erase only:
332                 pars[pit].erase(left, right);
333                 // Separate handling of para break:
334                 if (merge && pit != endpit &&
335                    (pit + 1 != endpit || pars[pit].hasSameLayout(pars[pit + 1]))) {
336                         pos_type const thissize = pars[pit].size();
337                         if (doclear)
338                                 pars[pit + 1].stripLeadingSpaces();
339                         mergeParagraph(params, pars, pit);
340                         --endpit;
341                         if (pit == endpit)
342                                 endpos += thissize;
343                 } else
344                         ++pit;
345         }
346
347         // Ensure legal cursor pos:
348         endpit = startpit;
349         endpos = startpos;
350         return PitPosPair(endpit, endpos);
351 }
352
353
354 void copySelectionHelper(Buffer const & buf, ParagraphList & pars,
355         pit_type startpit, pit_type endpit,
356         int start, int end, textclass_type tc)
357 {
358         BOOST_ASSERT(0 <= start && start <= pars[startpit].size());
359         BOOST_ASSERT(0 <= end && end <= pars[endpit].size());
360         BOOST_ASSERT(startpit != endpit || start <= end);
361
362         // Clone the paragraphs within the selection.
363         ParagraphList paragraphs(boost::next(pars.begin(), startpit),
364                                  boost::next(pars.begin(), endpit + 1));
365
366         for_each(paragraphs.begin(), paragraphs.end(), resetParagraph(buf));
367
368         // Cut out the end of the last paragraph.
369         Paragraph & back = paragraphs.back();
370         back.erase(end, back.size());
371
372         // Cut out the begin of the first paragraph
373         Paragraph & front = paragraphs.front();
374         front.erase(0, start);
375
376         theCuts.push(make_pair(paragraphs, tc));
377 }
378
379 } // namespace anon
380
381
382
383
384 namespace lyx {
385 namespace cap {
386
387 string grabAndEraseSelection(LCursor & cur)
388 {
389         if (!cur.selection())
390                 return string();
391         string res = grabSelection(cur);
392         eraseSelection(cur);
393         return res;
394 }
395
396
397 void switchBetweenClasses(textclass_type c1, textclass_type c2,
398         InsetText & in, ErrorList & errorlist)
399 {
400         BOOST_ASSERT(!in.paragraphs().empty());
401         if (c1 == c2)
402                 return;
403
404         LyXTextClass const & tclass1 = textclasslist[c1];
405         LyXTextClass const & tclass2 = textclasslist[c2];
406
407         // layouts
408         ParIterator end = par_iterator_end(in);
409         for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
410                 string const name = it->layout()->name();
411                 bool hasLayout = tclass2.hasLayout(name);
412
413                 if (hasLayout)
414                         it->layout(tclass2[name]);
415                 else
416                         it->layout(tclass2.defaultLayout());
417
418                 if (!hasLayout && name != tclass1.defaultLayoutName()) {
419                         docstring const s = bformat(
420                                                  _("Layout had to be changed from\n%1$s to %2$s\n"
421                                                 "because of class conversion from\n%3$s to %4$s"),
422                          lyx::from_utf8(name), lyx::from_utf8(it->layout()->name()),
423                          lyx::from_utf8(tclass1.name()), lyx::from_utf8(tclass2.name()));
424                         // To warn the user that something had to be done.
425                         errorlist.push_back(ErrorItem(_("Changed Layout"), s,
426                                                       it->id(), 0,
427                                                       it->size()));
428                 }
429         }
430
431         // character styles
432         InsetIterator const i_end = inset_iterator_end(in);
433         for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
434                 if (it->lyxCode() == InsetBase::CHARSTYLE_CODE) {
435                         InsetCharStyle & inset =
436                                 static_cast<InsetCharStyle &>(*it);
437                         string const name = inset.params().type;
438                         CharStyles::iterator const found_cs =
439                                 tclass2.charstyle(name);
440                         if (found_cs == tclass2.charstyles().end()) {
441                                 // The character style is undefined in tclass2
442                                 inset.setUndefined();
443                                 docstring const s = bformat(_(
444                                         "Character style %1$s is "
445                                         "undefined because of class "
446                                         "conversion from\n%2$s to %3$s"),
447                                          lyx::from_utf8(name), lyx::from_utf8(tclass1.name()),
448                                          lyx::from_utf8(tclass2.name()));
449                                 // To warn the user that something had to be done.
450                                 errorlist.push_back(ErrorItem(
451                                         _("Undefined character style"),
452                                         s, it.paragraph().id(), it.pos(), it.pos() + 1));
453                         } else if (inset.undefined()) {
454                                 // The character style is undefined in
455                                 // tclass1 and is defined in tclass2
456                                 inset.setDefined(found_cs);
457                         }
458                 }
459         }
460 }
461
462
463 std::vector<string> const availableSelections(Buffer const & buffer)
464 {
465         vector<string> selList;
466
467         CutStack::const_iterator cit = theCuts.begin();
468         CutStack::const_iterator end = theCuts.end();
469         for (; cit != end; ++cit) {
470                 // we do not use cit-> here because gcc 2.9x does not
471                 // like it (JMarc)
472                 ParagraphList const & pars = (*cit).first;
473                 string asciiSel;
474                 ParagraphList::const_iterator pit = pars.begin();
475                 ParagraphList::const_iterator pend = pars.end();
476                 for (; pit != pend; ++pit) {
477                         asciiSel += pit->asString(buffer, false);
478                         if (asciiSel.size() > 25) {
479                                 asciiSel.replace(22, string::npos, "...");
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 cur.bv().owner()->gui().selection().put. (Lgb)
517 //              cur.bv().owner()->gui().selection().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         cur.bv().owner()->gui().clipboard().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                 pars.back().insert(0, grabSelection(cur), LyXFont());
614                 theCuts.push(make_pair(pars, bp.textclass));
615         }
616         // tell tabular that a recent copy happened
617         dirtyTabularStack(false);
618 }
619
620
621 std::string getSelection(Buffer const & buf, size_t sel_index)
622 {
623         return sel_index < theCuts.size()
624                 ? theCuts[sel_index].first.back().asString(buf, false)
625                 : string();
626 }
627
628
629 void pasteParagraphList(LCursor & cur, ParagraphList const & parlist,
630                         textclass_type textclass, ErrorList & errorList)
631 {
632         if (cur.inTexted()) {
633                 LyXText * text = cur.text();
634                 BOOST_ASSERT(text);
635
636                 recordUndo(cur);
637
638                 pit_type endpit;
639                 PitPosPair ppp;
640
641                 boost::tie(ppp, endpit) =
642                         pasteSelectionHelper(cur, parlist,
643                                              textclass, errorList);
644                 updateLabels(cur.buffer());
645                 cur.clearSelection();
646                 text->setCursor(cur, ppp.first, ppp.second);
647         }
648
649         // mathed is handled in InsetMathNest/InsetMathGrid
650         BOOST_ASSERT(!cur.inMathed());
651 }
652
653
654 void pasteSelection(LCursor & cur, ErrorList & errorList, size_t sel_index)
655 {
656         // this does not make sense, if there is nothing to paste
657         if (!checkPastePossible(sel_index))
658                 return;
659
660         pasteParagraphList(cur, theCuts[sel_index].first,
661                            theCuts[sel_index].second, errorList);
662         cur.setSelection();
663 }
664
665
666 // simple replacing. The font of the first selected character is used
667 void replaceSelectionWithString(LCursor & cur, string const & str, bool backwards)
668 {
669         recordUndo(cur);
670         DocIterator selbeg = cur.selectionBegin();
671
672         // Get font setting before we cut
673         LyXFont const font =
674                 selbeg.paragraph().getFontSettings(cur.buffer().params(), selbeg.pos());
675
676         // Insert the new string
677         pos_type pos = cur.selEnd().pos();
678         Paragraph & par = cur.selEnd().paragraph();
679         string::const_iterator cit = str.begin();
680         string::const_iterator end = str.end();
681         for (; cit != end; ++cit, ++pos)
682                 par.insertChar(pos, (*cit), font);
683
684         // Cut the selection
685         cutSelection(cur, true, false);
686
687         // select the replacement
688         if (backwards) {
689                 selbeg.pos() += str.length();
690                 cur.setSelection(selbeg, -str.length());
691         } else
692                 cur.setSelection(selbeg, str.length());
693 }
694
695
696 void replaceSelection(LCursor & cur)
697 {
698         if (cur.selection())
699                 cutSelection(cur, true, false);
700 }
701
702
703 void eraseSelection(LCursor & cur)
704 {
705         //lyxerr << "LCursor::eraseSelection begin: " << cur << endl;
706         CursorSlice const & i1 = cur.selBegin();
707         CursorSlice const & i2 = cur.selEnd();
708         if (i1.inset().asInsetMath()) {
709                 cur.top() = i1;
710                 if (i1.idx() == i2.idx()) {
711                         i1.cell().erase(i1.pos(), i2.pos());
712                         // We may have deleted i1.cell(cur.pos()).
713                         // Make sure that pos is valid.
714                         if (cur.pos() > cur.lastpos())
715                                 cur.pos() = cur.lastpos();
716                 } else {
717                         InsetMath * p = i1.asInsetMath();
718                         InsetBase::row_type r1, r2;
719                         InsetBase::col_type c1, c2;
720                         region(i1, i2, r1, r2, c1, c2);
721                         for (InsetBase::row_type row = r1; row <= r2; ++row)
722                                 for (InsetBase::col_type col = c1; col <= c2; ++col)
723                                         p->cell(p->index(row, col)).clear();
724                         // We've deleted the whole cell. Only pos 0 is valid.
725                         cur.pos() = 0;
726                 }
727                 // need a valid cursor. (Lgb)
728                 cur.clearSelection();
729         } else {
730                 lyxerr << "can't erase this selection 1" << endl;
731         }
732         //lyxerr << "LCursor::eraseSelection end: " << cur << endl;
733 }
734
735
736 void selDel(LCursor & cur)
737 {
738         //lyxerr << "LCursor::selDel" << endl;
739         if (cur.selection())
740                 eraseSelection(cur);
741 }
742
743
744 void selClearOrDel(LCursor & cur)
745 {
746         //lyxerr << "LCursor::selClearOrDel" << endl;
747         if (lyxrc.auto_region_delete)
748                 selDel(cur);
749         else
750                 cur.selection() = false;
751 }
752
753
754 string grabSelection(LCursor const & cur)
755 {
756         if (!cur.selection())
757                 return string();
758
759         // FIXME: What is wrong with the following?
760 #if 0
761         std::ostringstream os;
762         for (DocIterator dit = cur.selectionBegin();
763              dit != cur.selectionEnd(); dit.forwardPos())
764                 os << asString(dit.cell());
765         return os.str();
766 #endif
767
768         CursorSlice i1 = cur.selBegin();
769         CursorSlice i2 = cur.selEnd();
770
771         if (i1.idx() == i2.idx()) {
772                 if (i1.inset().asInsetMath()) {
773                         MathArray::const_iterator it = i1.cell().begin();
774                         return asString(MathArray(it + i1.pos(), it + i2.pos()));
775                 } else {
776                         return "unknown selection 1";
777                 }
778         }
779
780         InsetBase::row_type r1, r2;
781         InsetBase::col_type c1, c2;
782         region(i1, i2, r1, r2, c1, c2);
783
784         string data;
785         if (i1.inset().asInsetMath()) {
786                 for (InsetBase::row_type row = r1; row <= r2; ++row) {
787                         if (row > r1)
788                                 data += "\\\\";
789                         for (InsetBase::col_type col = c1; col <= c2; ++col) {
790                                 if (col > c1)
791                                         data += '&';
792                                 data += asString(i1.asInsetMath()->
793                                         cell(i1.asInsetMath()->index(row, col)));
794                         }
795                 }
796         } else {
797                 data = "unknown selection 2";
798         }
799         return data;
800 }
801
802
803 void dirtyTabularStack(bool b)
804 {
805         dirty_tabular_stack_ = b;
806 }
807
808
809 bool tabularStackDirty()
810 {
811         return dirty_tabular_stack_;
812 }
813
814
815 } // namespace cap
816 } // namespace lyx