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