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