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