]> git.lyx.org Git - lyx.git/blob - src/CutAndPaste.cpp
Get rid of GridInsetMailer: this is completely useless and unused and consumes a...
[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 "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 "Text.h"
32 #include "TextClassList.h"
33 #include "Paragraph.h"
34 #include "paragraph_funcs.h"
35 #include "ParagraphParameters.h"
36 #include "ParIterator.h"
37 #include "Undo.h"
38
39 #include "insets/InsetCharStyle.h"
40 #include "insets/InsetTabular.h"
41
42 #include "mathed/MathData.h"
43 #include "mathed/InsetMath.h"
44 #include "mathed/MathSupport.h"
45
46 #include "support/lstrings.h"
47
48 #include "frontends/Clipboard.h"
49 #include "frontends/Selection.h"
50
51 #include <boost/current_function.hpp>
52 #include <boost/tuple/tuple.hpp>
53
54 #include <string>
55
56 using std::endl;
57 using std::for_each;
58 using std::make_pair;
59 using std::pair;
60 using std::vector;
61 using std::string;
62
63
64 namespace lyx {
65
66 using support::bformat;
67 using frontend::Clipboard;
68
69 namespace {
70
71 typedef std::pair<pit_type, int> PitPosPair;
72
73 typedef limited_stack<pair<ParagraphList, textclass_type> > CutStack;
74
75 CutStack theCuts(10);
76 // persistent selection, cleared until the next selection
77 CutStack selectionBuffer(1);
78
79 // store whether the tabular stack is newer than the normal copy stack
80 // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
81 // when we (hopefully) have a one-for-all paste mechanism.
82 bool dirty_tabular_stack_ = false;
83
84
85 void region(CursorSlice const & i1, CursorSlice const & i2,
86         Inset::row_type & r1, Inset::row_type & r2,
87         Inset::col_type & c1, Inset::col_type & c2)
88 {
89         Inset & p = i1.inset();
90         c1 = p.col(i1.idx());
91         c2 = p.col(i2.idx());
92         if (c1 > c2)
93                 std::swap(c1, c2);
94         r1 = p.row(i1.idx());
95         r2 = p.row(i2.idx());
96         if (r1 > r2)
97                 std::swap(r1, r2);
98 }
99
100
101 bool checkPastePossible(int index)
102 {
103         return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
104 }
105
106
107 pair<PitPosPair, pit_type>
108 pasteSelectionHelper(Cursor & cur, ParagraphList const & parlist,
109                      textclass_type textclass, ErrorList & errorlist)
110 {
111         Buffer const & buffer = cur.buffer();
112         pit_type pit = cur.pit();
113         pos_type pos = cur.pos();
114         ParagraphList & pars = cur.text()->paragraphs();
115
116         if (parlist.empty())
117                 return make_pair(PitPosPair(pit, pos), pit);
118
119         BOOST_ASSERT (pos <= pars[pit].size());
120
121         // Make a copy of the CaP paragraphs.
122         ParagraphList insertion = parlist;
123         textclass_type const tc = buffer.params().textclass;
124
125         // Now remove all out of the pars which is NOT allowed in the
126         // new environment and set also another font if that is required.
127
128         // Convert newline to paragraph break in ERT inset.
129         // This should not be here!
130         if (pars[pit].inInset() &&
131             pars[pit].inInset()->lyxCode() == Inset::ERT_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                 Layout_ptr 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->getChar(i) == Paragraph::META_INSET &&
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 Inset::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, bool doclear)
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 const right = (pit == endpit ? endpos : pars[pit].size() + 1);
304
305                 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.trackChanges);
306
307                 // Logically erase only, including the end-of-paragraph character
308                 pars[pit].eraseChars(left, right, params.trackChanges);
309
310                 // Separate handling of paragraph break:
311                 if (merge && pit != endpit &&
312                     (pit + 1 != endpit || pars[pit].hasSameLayout(pars[pit + 1]))) {
313                         pos_type const thissize = pars[pit].size();
314                         if (doclear)
315                                 pars[pit + 1].stripLeadingSpaces(params.trackChanges);
316                         mergeParagraph(params, pars, pit);
317                         --endpit;
318                         if (pit == endpit)
319                                 endpos += thissize;
320                 } else
321                         ++pit;
322         }
323
324         // Ensure legal cursor pos:
325         endpit = startpit;
326         endpos = startpos;
327         return PitPosPair(endpit, endpos);
328 }
329
330
331 void putClipboard(ParagraphList const & paragraphs, textclass_type textclass,
332                   docstring const & plaintext)
333 {
334         // For some strange reason gcc 3.2 and 3.3 do not accept
335         // Buffer buffer(string(), false);
336         Buffer buffer("", false);
337         buffer.setUnnamed(true);
338         buffer.paragraphs() = paragraphs;
339         buffer.params().textclass = textclass;
340         std::ostringstream lyx;
341         if (buffer.write(lyx))
342                 theClipboard().put(lyx.str(), plaintext);
343         else
344                 theClipboard().put(string(), plaintext);
345 }
346
347
348 void copySelectionHelper(Buffer const & buf, ParagraphList & pars,
349         pit_type startpit, pit_type endpit,
350         int start, int end, textclass_type tc, CutStack & cutstack)
351 {
352         BOOST_ASSERT(0 <= start && start <= pars[startpit].size());
353         BOOST_ASSERT(0 <= end && end <= pars[endpit].size());
354         BOOST_ASSERT(startpit != endpit || start <= end);
355
356         // Clone the paragraphs within the selection.
357         ParagraphList copy_pars(boost::next(pars.begin(), startpit),
358                                 boost::next(pars.begin(), endpit + 1));
359
360         // Remove the end of the last paragraph; afterwards, remove the
361         // beginning of the first paragraph. Keep this order - there may only
362         // be one paragraph!  Do not track deletions here; this is an internal
363         // action not visible to the user
364
365         Paragraph & back = copy_pars.back();
366         back.eraseChars(end, back.size(), false);
367         Paragraph & front = copy_pars.front();
368         front.eraseChars(0, start, false);
369
370         ParagraphList::iterator it = copy_pars.begin();
371         ParagraphList::iterator it_end = copy_pars.end();
372
373         for (; it != it_end; it++) {
374                 // ERT paragraphs have the Language latex_language.
375                 // This is invalid outside of ERT, so we need to change it
376                 // to the buffer language.
377                 if (it->ownerCode() == Inset::ERT_CODE) {
378                         it->changeLanguage(buf.params(), latex_language,
379                                            buf.getLanguage());
380                 }
381                 it->setInsetOwner(0);
382         }
383
384         // do not copy text (also nested in insets) which is marked as deleted
385         // acceptChanges() is defined for Text rather than ParagraphList
386         // Thus we must wrap copy_pars into a Text object and cross our fingers
387         Text lt;
388         copy_pars.swap(lt.paragraphs());
389         lt.acceptChanges(buf.params());
390         copy_pars.swap(lt.paragraphs());
391
392         cutstack.push(make_pair(copy_pars, tc));
393 }
394
395 } // namespace anon
396
397
398
399
400 namespace cap {
401
402 docstring grabAndEraseSelection(Cursor & cur)
403 {
404         if (!cur.selection())
405                 return docstring();
406         docstring res = grabSelection(cur);
407         eraseSelection(cur);
408         return res;
409 }
410
411
412 void switchBetweenClasses(textclass_type c1, textclass_type c2,
413         InsetText & in, ErrorList & errorlist)
414 {
415         BOOST_ASSERT(!in.paragraphs().empty());
416         if (c1 == c2)
417                 return;
418
419         TextClass const & tclass1 = textclasslist[c1];
420         TextClass const & tclass2 = textclasslist[c2];
421
422         // layouts
423         ParIterator end = par_iterator_end(in);
424         for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
425                 string const name = it->layout()->name();
426                 bool hasLayout = tclass2.hasLayout(name);
427
428                 if (hasLayout)
429                         it->layout(tclass2[name]);
430                 else
431                         it->layout(tclass2.defaultLayout());
432
433                 if (!hasLayout && name != tclass1.defaultLayoutName()) {
434                         docstring const s = bformat(
435                                                  _("Layout had to be changed from\n%1$s to %2$s\n"
436                                                 "because of class conversion from\n%3$s to %4$s"),
437                          from_utf8(name), from_utf8(it->layout()->name()),
438                          from_utf8(tclass1.name()), from_utf8(tclass2.name()));
439                         // To warn the user that something had to be done.
440                         errorlist.push_back(ErrorItem(_("Changed Layout"), s,
441                                                       it->id(), 0,
442                                                       it->size()));
443                 }
444         }
445
446         // character styles
447         InsetIterator const i_end = inset_iterator_end(in);
448         for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
449                 if (it->lyxCode() == Inset::CHARSTYLE_CODE) {
450                         InsetCharStyle & inset =
451                                 static_cast<InsetCharStyle &>(*it);
452                         string const name = inset.params().type;
453                         CharStyles::iterator const found_cs =
454                                 tclass2.charstyle(name);
455                         if (found_cs == tclass2.charstyles().end()) {
456                                 // The character style is undefined in tclass2
457                                 inset.setUndefined();
458                                 docstring const s = bformat(_(
459                                         "Character style %1$s is "
460                                         "undefined because of class "
461                                         "conversion from\n%2$s to %3$s"),
462                                          from_utf8(name), from_utf8(tclass1.name()),
463                                          from_utf8(tclass2.name()));
464                                 // To warn the user that something had to be done.
465                                 errorlist.push_back(ErrorItem(
466                                         _("Undefined character style"),
467                                         s, it.paragraph().id(), it.pos(), it.pos() + 1));
468                         } else if (inset.undefined()) {
469                                 // The character style is undefined in
470                                 // tclass1 and is defined in tclass2
471                                 inset.setDefined(found_cs);
472                         }
473                 }
474         }
475 }
476
477
478 std::vector<docstring> const availableSelections(Buffer const & buffer)
479 {
480         vector<docstring> selList;
481
482         CutStack::const_iterator cit = theCuts.begin();
483         CutStack::const_iterator end = theCuts.end();
484         for (; cit != end; ++cit) {
485                 // we do not use cit-> here because gcc 2.9x does not
486                 // like it (JMarc)
487                 ParagraphList const & pars = (*cit).first;
488                 docstring asciiSel;
489                 ParagraphList::const_iterator pit = pars.begin();
490                 ParagraphList::const_iterator pend = pars.end();
491                 for (; pit != pend; ++pit) {
492                         asciiSel += pit->asString(buffer, false);
493                         if (asciiSel.size() > 25) {
494                                 asciiSel.replace(22, docstring::npos,
495                                                  from_ascii("..."));
496                                 break;
497                         }
498                 }
499
500                 selList.push_back(asciiSel);
501         }
502
503         return selList;
504 }
505
506
507 size_type numberOfSelections()
508 {
509         return theCuts.size();
510 }
511
512
513 void cutSelection(Cursor & cur, bool doclear, bool realcut)
514 {
515         // This doesn't make sense, if there is no selection
516         if (!cur.selection())
517                 return;
518
519         // OK, we have a selection. This is always between cur.selBegin()
520         // and cur.selEnd()
521
522         if (cur.inTexted()) {
523                 Text * text = cur.text();
524                 BOOST_ASSERT(text);
525
526                 // make sure that the depth behind the selection are restored, too
527                 recordUndoSelection(cur);
528                 pit_type begpit = cur.selBegin().pit();
529                 pit_type endpit = cur.selEnd().pit();
530
531                 int endpos = cur.selEnd().pos();
532
533                 BufferParams const & bp = cur.buffer().params();
534                 if (realcut) {
535                         copySelectionHelper(cur.buffer(),
536                                 text->paragraphs(),
537                                 begpit, endpit,
538                                 cur.selBegin().pos(), endpos,
539                                 bp.textclass, theCuts);
540                         // Stuff what we got on the clipboard.
541                         // Even if there is no selection.
542                         putClipboard(theCuts[0].first, theCuts[0].second,
543                                 cur.selectionAsString(true));
544                 }
545
546                 boost::tie(endpit, endpos) =
547                         eraseSelectionHelper(bp,
548                                 text->paragraphs(),
549                                 begpit, endpit,
550                                 cur.selBegin().pos(), endpos,
551                                 doclear);
552
553                 // cutSelection can invalidate the cursor so we need to set
554                 // it anew. (Lgb)
555                 // we prefer the end for when tracking changes
556                 cur.pos() = endpos;
557                 cur.pit() = endpit;
558
559                 // sometimes necessary
560                 if (doclear 
561                         && text->paragraphs()[begpit].stripLeadingSpaces(bp.trackChanges))
562                         cur.fixIfBroken();
563
564                 // need a valid cursor. (Lgb)
565                 cur.clearSelection();
566                 updateLabels(cur.buffer());
567                 theSelection().haveSelection(false);
568
569                 // tell tabular that a recent copy happened
570                 dirtyTabularStack(false);
571         }
572
573         if (cur.inMathed()) {
574                 if (cur.selBegin().idx() != cur.selEnd().idx()) {
575                         // The current selection spans more than one cell.
576                         // Record all cells
577                         recordUndoInset(cur);
578                 } else {
579                         // Record only the current cell to avoid a jumping
580                         // cursor after undo
581                         recordUndo(cur);
582                 }
583                 if (realcut)
584                         copySelection(cur);
585                 eraseSelection(cur);
586         }
587 }
588
589
590 void copySelection(Cursor & cur)
591 {
592         copySelection(cur, cur.selectionAsString(true));
593 }
594
595
596 namespace {
597
598 void copySelectionToStack(Cursor & cur, CutStack & cutstack)
599 {
600         // this doesn't make sense, if there is no selection
601         if (!cur.selection())
602                 return;
603
604         if (cur.inTexted()) {
605                 Text * text = cur.text();
606                 BOOST_ASSERT(text);
607                 // ok we have a selection. This is always between cur.selBegin()
608                 // and sel_end cursor
609
610                 // copy behind a space if there is one
611                 ParagraphList & pars = text->paragraphs();
612                 pos_type pos = cur.selBegin().pos();
613                 pit_type par = cur.selBegin().pit();
614                 while (pos < pars[par].size() &&
615                        pars[par].isLineSeparator(pos) &&
616                        (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
617                         ++pos;
618
619                 copySelectionHelper(cur.buffer(), pars, par, cur.selEnd().pit(),
620                         pos, cur.selEnd().pos(), cur.buffer().params().textclass, cutstack);
621         }
622
623         if (cur.inMathed()) {
624                 //lyxerr << "copySelection in mathed" << endl;
625                 ParagraphList pars;
626                 Paragraph par;
627                 BufferParams const & bp = cur.buffer().params();
628                 par.layout(bp.getTextClass().defaultLayout());
629                 par.insert(0, grabSelection(cur), Font(), Change(Change::UNCHANGED));
630                 pars.push_back(par);
631                 cutstack.push(make_pair(pars, bp.textclass));
632         }
633 }
634
635 }
636
637
638 void copySelectionToStack()
639 {
640         if (!selectionBuffer.empty())
641                 theCuts.push(selectionBuffer[0]);
642 }
643
644
645 void copySelection(Cursor & cur, docstring const & plaintext)
646 {
647         // In tablemode, because copy and paste actually use special table stack
648         // we do not attemp to get selected paragraphs under cursor. Instead, a 
649         // paragraph with the plain text version is generated so that table cells
650         // can be pasted as pure text somewhere else.
651         if (cur.selBegin().idx() != cur.selEnd().idx()) {
652                 ParagraphList pars;
653                 Paragraph par;
654                 BufferParams const & bp = cur.buffer().params();
655                 par.layout(bp.getTextClass().defaultLayout());
656                 par.insert(0, plaintext, Font(), Change(Change::UNCHANGED));
657                 pars.push_back(par);
658                 theCuts.push(make_pair(pars, bp.textclass));
659         } else
660                 copySelectionToStack(cur, theCuts);
661
662         // stuff the selection onto the X clipboard, from an explicit copy request
663         putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
664 }
665
666
667 void saveSelection(Cursor & cur)
668 {
669         LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION << ": `"
670                << to_utf8(cur.selectionAsString(true)) << "'."
671                << endl;
672         
673         if (cur.selection())
674                 copySelectionToStack(cur, selectionBuffer);
675         // tell X whether we now have a valid selection
676         theSelection().haveSelection(cur.selection());
677 }
678
679
680 bool selection()
681 {
682         return !selectionBuffer.empty();
683 }
684
685
686 void clearSelection()
687 {
688         selectionBuffer.clear();
689 }
690
691
692 docstring getSelection(Buffer const & buf, size_t sel_index)
693 {
694         return sel_index < theCuts.size()
695                 ? theCuts[sel_index].first.back().asString(buf, false)
696                 : docstring();
697 }
698
699
700 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
701                         textclass_type textclass, ErrorList & errorList)
702 {
703         if (cur.inTexted()) {
704                 Text * text = cur.text();
705                 BOOST_ASSERT(text);
706
707                 pit_type endpit;
708                 PitPosPair ppp;
709
710                 boost::tie(ppp, endpit) =
711                         pasteSelectionHelper(cur, parlist,
712                                              textclass, errorList);
713                 updateLabels(cur.buffer());
714                 cur.clearSelection();
715                 text->setCursor(cur.top(), ppp.first, ppp.second);
716         }
717
718         // mathed is handled in InsetMathNest/InsetMathGrid
719         BOOST_ASSERT(!cur.inMathed());
720 }
721
722
723 void pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
724 {
725         // this does not make sense, if there is nothing to paste
726         if (!checkPastePossible(sel_index))
727                 return;
728
729         recordUndo(cur);
730         pasteParagraphList(cur, theCuts[sel_index].first,
731                            theCuts[sel_index].second, errorList);
732         cur.setSelection();
733         saveSelection(cur);
734 }
735
736
737 void pasteClipboard(Cursor & cur, ErrorList & errorList, bool asParagraphs)
738 {
739         // Use internal clipboard if it is the most recent one
740         if (theClipboard().isInternal()) {
741                 pasteFromStack(cur, errorList, 0);
742                 return;
743         }
744
745         // First try LyX format
746         if (theClipboard().hasLyXContents()) {
747                 string lyx = theClipboard().getAsLyX();
748                 if (!lyx.empty()) {
749                         // For some strange reason gcc 3.2 and 3.3 do not accept
750                         // Buffer buffer(string(), false);
751                         Buffer buffer("", false);
752                         buffer.setUnnamed(true);
753                         if (buffer.readString(lyx)) {
754                                 recordUndo(cur);
755                                 pasteParagraphList(cur, buffer.paragraphs(),
756                                         buffer.params().textclass, errorList);
757                                 cur.setSelection();
758                                 return;
759                         }
760                 }
761         }
762
763         // Then try plain text
764         docstring const text = theClipboard().getAsText();
765         if (text.empty())
766                 return;
767         recordUndo(cur);
768         if (asParagraphs)
769                 cur.text()->insertStringAsParagraphs(cur, text);
770         else
771                 cur.text()->insertStringAsLines(cur, text);
772 }
773
774
775 void pasteSelection(Cursor & cur, ErrorList & errorList)
776 {
777         if (selectionBuffer.empty())
778                 return;
779         recordUndo(cur);
780         pasteParagraphList(cur, selectionBuffer[0].first,
781                            selectionBuffer[0].second, errorList);
782         cur.setSelection();
783 }
784
785
786 void replaceSelectionWithString(Cursor & cur, docstring const & str, bool backwards)
787 {
788         recordUndo(cur);
789         DocIterator selbeg = cur.selectionBegin();
790
791         // Get font setting before we cut
792         Font const font =
793                 selbeg.paragraph().getFontSettings(cur.buffer().params(), selbeg.pos());
794
795         // Insert the new string
796         pos_type pos = cur.selEnd().pos();
797         Paragraph & par = cur.selEnd().paragraph();
798         docstring::const_iterator cit = str.begin();
799         docstring::const_iterator end = str.end();
800         for (; cit != end; ++cit, ++pos)
801                 par.insertChar(pos, *cit, font, cur.buffer().params().trackChanges);
802
803         // Cut the selection
804         cutSelection(cur, true, false);
805
806         // select the replacement
807         if (backwards) {
808                 selbeg.pos() += str.length();
809                 cur.setSelection(selbeg, -int(str.length()));
810         } else
811                 cur.setSelection(selbeg, str.length());
812         saveSelection(cur);
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                 cur.top() = i1;
830                 if (i1.idx() == i2.idx()) {
831                         i1.cell().erase(i1.pos(), i2.pos());
832                         // We may have deleted i1.cell(cur.pos()).
833                         // Make sure that pos is valid.
834                         if (cur.pos() > cur.lastpos())
835                                 cur.pos() = cur.lastpos();
836                 } else {
837                         InsetMath * p = i1.asInsetMath();
838                         Inset::row_type r1, r2;
839                         Inset::col_type c1, c2;
840                         region(i1, i2, r1, r2, c1, c2);
841                         for (Inset::row_type row = r1; row <= r2; ++row)
842                                 for (Inset::col_type col = c1; col <= c2; ++col)
843                                         p->cell(p->index(row, col)).clear();
844                         // We've deleted the whole cell. Only pos 0 is valid.
845                         cur.pos() = 0;
846                 }
847                 // need a valid cursor. (Lgb)
848                 cur.clearSelection();
849                 theSelection().haveSelection(false);
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