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