]> git.lyx.org Git - lyx.git/blob - src/CutAndPaste.cpp
'using namespace std' instead of 'using std::xxx'
[lyx.git] / src / CutAndPaste.cpp
1 /*
2  * \file CutAndPaste.cpp
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 "BufferView.h"
22 #include "Changes.h"
23 #include "Cursor.h"
24 #include "ErrorList.h"
25 #include "FuncRequest.h"
26 #include "InsetIterator.h"
27 #include "InsetList.h"
28 #include "Language.h"
29 #include "lfuns.h"
30 #include "LyXFunc.h"
31 #include "LyXRC.h"
32 #include "Text.h"
33 #include "TextClassList.h"
34 #include "Paragraph.h"
35 #include "paragraph_funcs.h"
36 #include "ParagraphParameters.h"
37 #include "ParIterator.h"
38 #include "Undo.h"
39
40 #include "insets/InsetFlex.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/debug.h"
48 #include "support/docstream.h"
49 #include "support/gettext.h"
50 #include "support/limited_stack.h"
51 #include "support/lstrings.h"
52
53 #include "frontends/Clipboard.h"
54 #include "frontends/Selection.h"
55
56 #include <boost/tuple/tuple.hpp>
57 #include <boost/next_prior.hpp>
58
59 #include <string>
60
61 using namespace std;
62
63 namespace lyx {
64
65 using support::bformat;
66 using frontend::Clipboard;
67
68 namespace {
69
70 typedef std::pair<pit_type, int> PitPosPair;
71
72 typedef limited_stack<pair<ParagraphList, TextClassPtr> > CutStack;
73
74 CutStack theCuts(10);
75 // persistent selection, cleared until the next selection
76 CutStack selectionBuffer(1);
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         Inset::row_type & r1, Inset::row_type & r2,
86         Inset::col_type & c1, Inset::col_type & c2)
87 {
88         Inset & 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(Cursor & cur, ParagraphList const & parlist,
108                      TextClassPtr 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         TextClassPtr const tc = buffer.params().getTextClassPtr();
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() == ERT_CODE ||
131                 pars[pit].inInset()->lyxCode() == LISTINGS_CODE)) {
132                 for (ParagraphList::size_type i = 0; i < insertion.size(); ++i) {
133                         for (pos_type j = 0; j < insertion[i].size(); ++j) {
134                                 if (insertion[i].isNewline(j)) {
135                                         // do not track deletion of newline
136                                         insertion[i].eraseChar(j, false);
137                                         breakParagraphConservative(
138                                                         buffer.params(),
139                                                         insertion, i, j);
140                                 }
141                         }
142                 }
143         }
144
145         // If we are in an inset which returns forceDefaultParagraphs,
146         // set the paragraphs to default
147         if (cur.inset().forceDefaultParagraphs(cur.idx())) {
148                 LayoutPtr const layout =
149                         buffer.params().getTextClass().defaultLayout();
150                 ParagraphList::iterator const end = insertion.end();
151                 for (ParagraphList::iterator par = insertion.begin();
152                                 par != end; ++par)
153                         par->layout(layout);
154         }
155
156         // Make sure there is no class difference.
157         InsetText in;
158         // This works without copying any paragraph data because we have
159         // a specialized swap method for ParagraphList. This is important
160         // since we store pointers to insets at some places and we don't
161         // want to invalidate them.
162         insertion.swap(in.paragraphs());
163         cap::switchBetweenClasses(textclass, tc, in, errorlist);
164         insertion.swap(in.paragraphs());
165
166         ParagraphList::iterator tmpbuf = insertion.begin();
167         int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
168
169         depth_type max_depth = pars[pit].getMaxDepthAfter();
170
171         for (; tmpbuf != insertion.end(); ++tmpbuf) {
172                 // If we have a negative jump so that the depth would
173                 // go below 0 depth then we have to redo the delta to
174                 // this new max depth level so that subsequent
175                 // paragraphs are aligned correctly to this paragraph
176                 // at level 0.
177                 if (int(tmpbuf->params().depth()) + depth_delta < 0)
178                         depth_delta = 0;
179
180                 // Set the right depth so that we are not too deep or shallow.
181                 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
182                 if (tmpbuf->params().depth() > max_depth)
183                         tmpbuf->params().depth(max_depth);
184
185                 // Only set this from the 2nd on as the 2nd depends
186                 // for maxDepth still on pit.
187                 if (tmpbuf != insertion.begin())
188                         max_depth = tmpbuf->getMaxDepthAfter();
189
190                 // Set the inset owner of this paragraph.
191                 tmpbuf->setInsetOwner(pars[pit].inInset());
192                 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
193                         if (tmpbuf->isInset(i) &&
194                             !pars[pit].insetAllowed(tmpbuf->getInset(i)->lyxCode()))
195                                 // do not track deletion of invalid insets
196                                 tmpbuf->eraseChar(i--, false);
197                 }
198
199                 tmpbuf->setChange(Change(buffer.params().trackChanges ?
200                                          Change::INSERTED : Change::UNCHANGED));
201         }
202
203         bool const empty = pars[pit].empty();
204         if (!empty) {
205                 // Make the buf exactly the same layout as the cursor
206                 // paragraph.
207                 insertion.begin()->makeSameLayout(pars[pit]);
208         }
209
210         // Prepare the paragraphs and insets for insertion.
211         // A couple of insets store buffer references so need updating.
212         insertion.swap(in.paragraphs());
213
214         ParIterator fpit = par_iterator_begin(in);
215         ParIterator fend = par_iterator_end(in);
216
217         for (; fpit != fend; ++fpit) {
218                 InsetList::const_iterator lit = fpit->insetList().begin();
219                 InsetList::const_iterator eit = fpit->insetList().end();
220
221                 for (; lit != eit; ++lit) {
222                         switch (lit->inset->lyxCode()) {
223                         case TABULAR_CODE: {
224                                 InsetTabular * it = static_cast<InsetTabular*>(lit->inset);
225                                 it->buffer(&buffer);
226                                 break;
227                         }
228
229                         default:
230                                 break; // nothing
231                         }
232                 }
233         }
234         insertion.swap(in.paragraphs());
235
236         // Split the paragraph for inserting the buf if necessary.
237         if (!empty)
238                 breakParagraphConservative(buffer.params(), pars, pit, pos);
239
240         // Paste it!
241         if (empty) {
242                 pars.insert(boost::next(pars.begin(), pit),
243                             insertion.begin(),
244                             insertion.end());
245
246                 // merge the empty par with the last par of the insertion
247                 mergeParagraph(buffer.params(), pars,
248                                pit + insertion.size() - 1);
249         } else {
250                 pars.insert(boost::next(pars.begin(), pit + 1),
251                             insertion.begin(),
252                             insertion.end());
253
254                 // merge the first par of the insertion with the current par
255                 mergeParagraph(buffer.params(), pars, pit);
256         }
257
258         pit_type last_paste = pit + insertion.size() - 1;
259
260         // Store the new cursor position.
261         pit = last_paste;
262         pos = pars[last_paste].size();
263
264         // Join (conditionally) last pasted paragraph with next one, i.e.,
265         // the tail of the spliced document paragraph
266         if (!empty && last_paste + 1 != pit_type(pars.size())) {
267                 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
268                         mergeParagraph(buffer.params(), pars, last_paste);
269                 } else if (pars[last_paste + 1].empty()) {
270                         pars[last_paste + 1].makeSameLayout(pars[last_paste]);
271                         mergeParagraph(buffer.params(), pars, last_paste);
272                 } else if (pars[last_paste].empty()) {
273                         pars[last_paste].makeSameLayout(pars[last_paste + 1]);
274                         mergeParagraph(buffer.params(), pars, last_paste);
275                 } else {
276                         pars[last_paste + 1].stripLeadingSpaces(buffer.params().trackChanges);
277                         ++last_paste;
278                 }
279         }
280
281         return make_pair(PitPosPair(pit, pos), last_paste + 1);
282 }
283
284
285 PitPosPair eraseSelectionHelper(BufferParams const & params,
286         ParagraphList & pars,
287         pit_type startpit, pit_type endpit,
288         int startpos, int endpos)
289 {
290         // Start of selection is really invalid.
291         if (startpit == pit_type(pars.size()) ||
292             (startpos > pars[startpit].size()))
293                 return PitPosPair(endpit, endpos);
294
295         // Start and end is inside same paragraph
296         if (endpit == pit_type(pars.size()) || startpit == endpit) {
297                 endpos -= pars[startpit].eraseChars(startpos, endpos, params.trackChanges);
298                 return PitPosPair(endpit, endpos);
299         }
300
301         for (pit_type pit = startpit; pit != endpit + 1;) {
302                 pos_type const left  = (pit == startpit ? startpos : 0);
303                 pos_type right = (pit == endpit ? endpos : pars[pit].size() + 1);
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[endpit]))) {
312                         if (pit + 1 == endpit)
313                                 endpos += pars[pit].size();
314                         mergeParagraph(params, pars, pit);
315                         --endpit;
316                 } else
317                         ++pit;
318         }
319
320         // Ensure legal cursor pos:
321         endpit = startpit;
322         endpos = startpos;
323         return PitPosPair(endpit, endpos);
324 }
325
326
327 void putClipboard(ParagraphList const & paragraphs, TextClassPtr textclass,
328                   docstring const & plaintext)
329 {
330         // For some strange reason gcc 3.2 and 3.3 do not accept
331         // Buffer buffer(string(), false);
332         Buffer buffer("", false);
333         buffer.setUnnamed(true);
334         buffer.paragraphs() = paragraphs;
335         buffer.params().setTextClass(textclass);
336         std::ostringstream lyx;
337         if (buffer.write(lyx))
338                 theClipboard().put(lyx.str(), plaintext);
339         else
340                 theClipboard().put(string(), plaintext);
341 }
342
343
344 void copySelectionHelper(Buffer const & buf, ParagraphList & pars,
345         pit_type startpit, pit_type endpit,
346         int start, int end, TextClassPtr tc, CutStack & cutstack)
347 {
348         BOOST_ASSERT(0 <= start && start <= pars[startpit].size());
349         BOOST_ASSERT(0 <= end && end <= pars[endpit].size());
350         BOOST_ASSERT(startpit != endpit || start <= end);
351
352         // Clone the paragraphs within the selection.
353         ParagraphList copy_pars(boost::next(pars.begin(), startpit),
354                                 boost::next(pars.begin(), endpit + 1));
355
356         // Remove the end of the last paragraph; afterwards, remove the
357         // beginning of the first paragraph. Keep this order - there may only
358         // be one paragraph!  Do not track deletions here; this is an internal
359         // action not visible to the user
360
361         Paragraph & back = copy_pars.back();
362         back.eraseChars(end, back.size(), false);
363         Paragraph & front = copy_pars.front();
364         front.eraseChars(0, start, false);
365
366         ParagraphList::iterator it = copy_pars.begin();
367         ParagraphList::iterator it_end = copy_pars.end();
368
369         for (; it != it_end; it++) {
370                 // ERT paragraphs have the Language latex_language.
371                 // This is invalid outside of ERT, so we need to change it
372                 // to the buffer language.
373                 if (it->ownerCode() == ERT_CODE || it->ownerCode() == LISTINGS_CODE) {
374                         it->changeLanguage(buf.params(), latex_language, buf.language());
375                 }
376                 it->setInsetOwner(0);
377         }
378
379         // do not copy text (also nested in insets) which is marked as deleted
380         acceptChanges(copy_pars, buf.params());
381
382         cutstack.push(make_pair(copy_pars, tc));
383 }
384
385 } // namespace anon
386
387
388
389
390 namespace cap {
391
392 docstring grabAndEraseSelection(Cursor & cur)
393 {
394         if (!cur.selection())
395                 return docstring();
396         docstring res = grabSelection(cur);
397         eraseSelection(cur);
398         return res;
399 }
400
401
402 void switchBetweenClasses(TextClassPtr const & c1, 
403         TextClassPtr const & c2, InsetText & in, ErrorList & errorlist)
404 {
405         errorlist.clear();
406
407         BOOST_ASSERT(!in.paragraphs().empty());
408         if (c1 == c2)
409                 return;
410         
411         TextClass const & tclass1 = *c1;
412         TextClass const & tclass2 = *c2;
413
414         // layouts
415         ParIterator end = par_iterator_end(in);
416         for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
417                 docstring const name = it->layout()->name();
418                 bool hasLayout = tclass2.hasLayout(name);
419
420                 if (hasLayout)
421                         it->layout(tclass2[name]);
422                 else
423                         it->layout(tclass2.defaultLayout());
424
425                 if (!hasLayout && name != tclass1.defaultLayoutName()) {
426                         docstring const s = bformat(
427                                                  _("Layout had to be changed from\n%1$s to %2$s\n"
428                                                 "because of class conversion from\n%3$s to %4$s"),
429                          name, it->layout()->name(),
430                          from_utf8(tclass1.name()), from_utf8(tclass2.name()));
431                         // To warn the user that something had to be done.
432                         errorlist.push_back(ErrorItem(_("Changed Layout"), s,
433                                                       it->id(), 0,
434                                                       it->size()));
435                 }
436         }
437
438         // character styles
439         InsetIterator const i_end = inset_iterator_end(in);
440         for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
441                 InsetCollapsable * inset = it->asInsetCollapsable();
442                 if (!inset)
443                         continue;
444                 if (inset->lyxCode() != FLEX_CODE)
445                         // FIXME: Should we verify all InsetCollapsable?
446                         continue;
447                 docstring const name = inset->name();
448                 InsetLayout const & il = tclass2.insetlayout(name);
449                 inset->setLayout(il);
450                 if (il.labelstring != from_utf8("UNDEFINED"))
451                         continue;
452                 // The flex inset is undefined in tclass2
453                 docstring const s = bformat(_(
454                         "Flex inset %1$s is "
455                         "undefined because of class "
456                         "conversion from\n%2$s to %3$s"),
457                         name, from_utf8(tclass1.name()),
458                         from_utf8(tclass2.name()));
459                 // To warn the user that something had to be done.
460                 errorlist.push_back(ErrorItem(
461                                 _("Undefined flex inset"),
462                                 s, it.paragraph().id(), it.pos(), it.pos() + 1));
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(Cursor & 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                 Text * text = cur.text();
513                 BOOST_ASSERT(text);
514
515                 saveSelection(cur);
516
517                 // make sure that the depth behind the selection are restored, too
518                 cur.recordUndoSelection();
519                 pit_type begpit = cur.selBegin().pit();
520                 pit_type endpit = cur.selEnd().pit();
521
522                 int endpos = cur.selEnd().pos();
523
524                 BufferParams const & bp = cur.buffer().params();
525                 if (realcut) {
526                         copySelectionHelper(cur.buffer(),
527                                 text->paragraphs(),
528                                 begpit, endpit,
529                                 cur.selBegin().pos(), endpos,
530                                 bp.getTextClassPtr(), theCuts);
531                         // Stuff what we got on the clipboard.
532                         // Even if there is no selection.
533                         putClipboard(theCuts[0].first, theCuts[0].second,
534                                 cur.selectionAsString(true));
535                 }
536
537                 boost::tie(endpit, endpos) =
538                         eraseSelectionHelper(bp,
539                                 text->paragraphs(),
540                                 begpit, endpit,
541                                 cur.selBegin().pos(), endpos);
542
543                 // cutSelection can invalidate the cursor so we need to set
544                 // it anew. (Lgb)
545                 // we prefer the end for when tracking changes
546                 cur.pos() = endpos;
547                 cur.pit() = endpit;
548
549                 // sometimes necessary
550                 if (doclear
551                         && text->paragraphs()[begpit].stripLeadingSpaces(bp.trackChanges))
552                         cur.fixIfBroken();
553
554                 // need a valid cursor. (Lgb)
555                 cur.clearSelection();
556                 updateLabels(cur.buffer());
557
558                 // tell tabular that a recent copy happened
559                 dirtyTabularStack(false);
560         }
561
562         if (cur.inMathed()) {
563                 if (cur.selBegin().idx() != cur.selEnd().idx()) {
564                         // The current selection spans more than one cell.
565                         // Record all cells
566                         cur.recordUndoInset();
567                 } else {
568                         // Record only the current cell to avoid a jumping
569                         // cursor after undo
570                         cur.recordUndo();
571                 }
572                 if (realcut)
573                         copySelection(cur);
574                 eraseSelection(cur);
575         }
576 }
577
578
579 void copySelection(Cursor & cur)
580 {
581         copySelection(cur, cur.selectionAsString(true));
582 }
583
584
585 namespace {
586
587 void copySelectionToStack(Cursor & cur, CutStack & cutstack)
588 {
589         // this doesn't make sense, if there is no selection
590         if (!cur.selection())
591                 return;
592
593         // copySelection can not yet handle the case of cross idx selection
594         if (cur.selBegin().idx() != cur.selEnd().idx())
595                 return;
596
597         if (cur.inTexted()) {
598                 Text * 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(), 
614                         cur.buffer().params().getTextClassPtr(), cutstack);
615                 dirtyTabularStack(false);
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.getTextClass().defaultLayout());
624                 par.insert(0, grabSelection(cur), Font(), Change(Change::UNCHANGED));
625                 pars.push_back(par);
626                 cutstack.push(make_pair(pars, bp.getTextClassPtr()));
627         }
628 }
629
630 }
631
632
633 void copySelectionToStack()
634 {
635         if (!selectionBuffer.empty())
636                 theCuts.push(selectionBuffer[0]);
637 }
638
639
640 void copySelection(Cursor & cur, docstring const & plaintext)
641 {
642         // In tablemode, because copy and paste actually use special table stack
643         // we do not attempt to get selected paragraphs under cursor. Instead, a
644         // paragraph with the plain text version is generated so that table cells
645         // can be pasted as pure text somewhere else.
646         if (cur.selBegin().idx() != cur.selEnd().idx()) {
647                 ParagraphList pars;
648                 Paragraph par;
649                 BufferParams const & bp = cur.buffer().params();
650                 par.layout(bp.getTextClass().defaultLayout());
651                 par.insert(0, plaintext, Font(), Change(Change::UNCHANGED));
652                 pars.push_back(par);
653                 theCuts.push(make_pair(pars, bp.getTextClassPtr()));
654         } else {
655                 copySelectionToStack(cur, theCuts);
656         }
657
658         // stuff the selection onto the X clipboard, from an explicit copy request
659         putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
660 }
661
662
663 void saveSelection(Cursor & cur)
664 {
665         // This function is called, not when a selection is formed, but when
666         // a selection is cleared. Therefore, multiple keyboard selection
667         // will not repeatively trigger this function (bug 3877).
668         if (cur.selection() 
669             && cur.selBegin() == cur.bv().cursor().selBegin()
670             && cur.selEnd() == cur.bv().cursor().selEnd()) {
671                 LYXERR(Debug::ACTION, "'" << cur.selectionAsString(true) << "'");
672                 copySelectionToStack(cur, selectionBuffer);
673         }
674 }
675
676
677 bool selection()
678 {
679         return !selectionBuffer.empty();
680 }
681
682
683 void clearSelection()
684 {
685         selectionBuffer.clear();
686 }
687
688
689 void clearCutStack()
690 {
691         theCuts.clear();
692 }
693
694
695 docstring getSelection(Buffer const & buf, size_t sel_index)
696 {
697         return sel_index < theCuts.size()
698                 ? theCuts[sel_index].first.back().asString(buf, false)
699                 : docstring();
700 }
701
702
703 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
704                         TextClassPtr textclass, ErrorList & errorList)
705 {
706         if (cur.inTexted()) {
707                 Text * text = cur.text();
708                 BOOST_ASSERT(text);
709
710                 pit_type endpit;
711                 PitPosPair ppp;
712
713                 boost::tie(ppp, endpit) =
714                         pasteSelectionHelper(cur, parlist,
715                                              textclass, errorList);
716                 updateLabels(cur.buffer());
717                 cur.clearSelection();
718                 text->setCursor(cur, ppp.first, ppp.second);
719         }
720
721         // mathed is handled in InsetMathNest/InsetMathGrid
722         BOOST_ASSERT(!cur.inMathed());
723 }
724
725
726 void pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
727 {
728         // this does not make sense, if there is nothing to paste
729         if (!checkPastePossible(sel_index))
730                 return;
731
732         cur.recordUndo();
733         pasteParagraphList(cur, theCuts[sel_index].first,
734                            theCuts[sel_index].second, errorList);
735         cur.setSelection();
736 }
737
738
739 void pasteClipboard(Cursor & cur, ErrorList & errorList, bool asParagraphs)
740 {
741         // Use internal clipboard if it is the most recent one
742         if (theClipboard().isInternal()) {
743                 pasteFromStack(cur, errorList, 0);
744                 return;
745         }
746
747         // First try LyX format
748         if (theClipboard().hasLyXContents()) {
749                 string lyx = theClipboard().getAsLyX();
750                 if (!lyx.empty()) {
751                         // For some strange reason gcc 3.2 and 3.3 do not accept
752                         // Buffer buffer(string(), false);
753                         Buffer buffer("", false);
754                         buffer.setUnnamed(true);
755                         if (buffer.readString(lyx)) {
756                                 cur.recordUndo();
757                                 pasteParagraphList(cur, buffer.paragraphs(),
758                                         buffer.params().getTextClassPtr(), errorList);
759                                 cur.setSelection();
760                                 return;
761                         }
762                 }
763         }
764
765         // Then try plain text
766         docstring const text = theClipboard().getAsText();
767         if (text.empty())
768                 return;
769         cur.recordUndo();
770         if (asParagraphs)
771                 cur.text()->insertStringAsParagraphs(cur, text);
772         else
773                 cur.text()->insertStringAsLines(cur, text);
774 }
775
776
777 void pasteSelection(Cursor & cur, ErrorList & errorList)
778 {
779         if (selectionBuffer.empty())
780                 return;
781         cur.recordUndo();
782         pasteParagraphList(cur, selectionBuffer[0].first,
783                            selectionBuffer[0].second, errorList);
784 }
785
786
787 void replaceSelectionWithString(Cursor & cur, docstring const & str, bool backwards)
788 {
789         cur.recordUndo();
790         DocIterator selbeg = cur.selectionBegin();
791
792         // Get font setting before we cut
793         Font const font =
794                 selbeg.paragraph().getFontSettings(cur.buffer().params(), selbeg.pos());
795
796         // Insert the new string
797         pos_type pos = cur.selEnd().pos();
798         Paragraph & par = cur.selEnd().paragraph();
799         docstring::const_iterator cit = str.begin();
800         docstring::const_iterator end = str.end();
801         for (; cit != end; ++cit, ++pos)
802                 par.insertChar(pos, *cit, font, cur.buffer().params().trackChanges);
803
804         // Cut the selection
805         cutSelection(cur, true, false);
806
807         // select the replacement
808         if (backwards) {
809                 selbeg.pos() += str.length();
810                 cur.setSelection(selbeg, -int(str.length()));
811         } else
812                 cur.setSelection(selbeg, str.length());
813 }
814
815
816 void replaceSelection(Cursor & cur)
817 {
818         if (cur.selection())
819                 cutSelection(cur, true, false);
820 }
821
822
823 void eraseSelection(Cursor & cur)
824 {
825         //lyxerr << "cap::eraseSelection begin: " << cur << endl;
826         CursorSlice const & i1 = cur.selBegin();
827         CursorSlice const & i2 = cur.selEnd();
828         if (i1.inset().asInsetMath()) {
829                 saveSelection(cur);
830                 cur.top() = i1;
831                 if (i1.idx() == i2.idx()) {
832                         i1.cell().erase(i1.pos(), i2.pos());
833                         // We may have deleted i1.cell(cur.pos()).
834                         // Make sure that pos is valid.
835                         if (cur.pos() > cur.lastpos())
836                                 cur.pos() = cur.lastpos();
837                 } else {
838                         InsetMath * p = i1.asInsetMath();
839                         Inset::row_type r1, r2;
840                         Inset::col_type c1, c2;
841                         region(i1, i2, r1, r2, c1, c2);
842                         for (Inset::row_type row = r1; row <= r2; ++row)
843                                 for (Inset::col_type col = c1; col <= c2; ++col)
844                                         p->cell(p->index(row, col)).clear();
845                         // We've deleted the whole cell. Only pos 0 is valid.
846                         cur.pos() = 0;
847                 }
848                 // need a valid cursor. (Lgb)
849                 cur.clearSelection();
850         } else {
851                 lyxerr << "can't erase this selection 1" << endl;
852         }
853         //lyxerr << "cap::eraseSelection end: " << cur << endl;
854 }
855
856
857 void selDel(Cursor & cur)
858 {
859         //lyxerr << "cap::selDel" << endl;
860         if (cur.selection())
861                 eraseSelection(cur);
862 }
863
864
865 void selClearOrDel(Cursor & cur)
866 {
867         //lyxerr << "cap::selClearOrDel" << endl;
868         if (lyxrc.auto_region_delete)
869                 selDel(cur);
870         else
871                 cur.selection() = false;
872 }
873
874
875 docstring grabSelection(Cursor const & cur)
876 {
877         if (!cur.selection())
878                 return docstring();
879
880         // FIXME: What is wrong with the following?
881 #if 0
882         std::ostringstream os;
883         for (DocIterator dit = cur.selectionBegin();
884              dit != cur.selectionEnd(); dit.forwardPos())
885                 os << asString(dit.cell());
886         return os.str();
887 #endif
888
889         CursorSlice i1 = cur.selBegin();
890         CursorSlice i2 = cur.selEnd();
891
892         if (i1.idx() == i2.idx()) {
893                 if (i1.inset().asInsetMath()) {
894                         MathData::const_iterator it = i1.cell().begin();
895                         return asString(MathData(it + i1.pos(), it + i2.pos()));
896                 } else {
897                         return from_ascii("unknown selection 1");
898                 }
899         }
900
901         Inset::row_type r1, r2;
902         Inset::col_type c1, c2;
903         region(i1, i2, r1, r2, c1, c2);
904
905         docstring data;
906         if (i1.inset().asInsetMath()) {
907                 for (Inset::row_type row = r1; row <= r2; ++row) {
908                         if (row > r1)
909                                 data += "\\\\";
910                         for (Inset::col_type col = c1; col <= c2; ++col) {
911                                 if (col > c1)
912                                         data += '&';
913                                 data += asString(i1.asInsetMath()->
914                                         cell(i1.asInsetMath()->index(row, col)));
915                         }
916                 }
917         } else {
918                 data = from_ascii("unknown selection 2");
919         }
920         return data;
921 }
922
923
924 void dirtyTabularStack(bool b)
925 {
926         dirty_tabular_stack_ = b;
927 }
928
929
930 bool tabularStackDirty()
931 {
932         return dirty_tabular_stack_;
933 }
934
935
936 } // namespace cap
937
938 } // namespace lyx