]> git.lyx.org Git - lyx.git/blob - src/CutAndPaste.cpp
eed8123521bbd66d3a0e10b25c5d18cb64c3dfb8
[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, TextClassIndex> > 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                      TextClassIndex const & 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         TextClassIndex tcindex = buffer.params().textClassIndex();
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().textClass().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(textclass, tcindex, 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, TextClassIndex textclass,
321                   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().setTextClass(textclass);
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, TextClassIndex tc, 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         cutstack.push(make_pair(copy_pars, tc));
376 }
377
378 } // namespace anon
379
380
381
382
383 namespace cap {
384
385 docstring grabAndEraseSelection(Cursor & cur)
386 {
387         if (!cur.selection())
388                 return docstring();
389         docstring res = grabSelection(cur);
390         eraseSelection(cur);
391         return res;
392 }
393
394
395 void switchBetweenClasses(TextClassIndex const & oldtcindex,
396         TextClassIndex const & newtcindex, InsetText & in, ErrorList & errorlist)
397 {
398         errorlist.clear();
399
400         BOOST_ASSERT(!in.paragraphs().empty());
401         if (oldtcindex == newtcindex)
402                 return;
403         
404         // layouts
405         ParIterator end = par_iterator_end(in);
406         TextClass const & oldtc = textclasslist[oldtcindex];
407         TextClass const & newtc = textclasslist[newtcindex];
408         for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
409                 docstring const name = it->layout()->name();
410                 bool hasLayout = newtc.hasLayout(name);
411
412                 if (hasLayout)
413                         it->setLayout(newtc[name]);
414                 else
415                         it->setLayout(newtc.defaultLayout());
416
417                 if (!hasLayout && name != oldtc.defaultLayoutName()) {
418                         docstring const s = bformat(
419                                                  _("Layout had to be changed from\n%1$s to %2$s\n"
420                                                 "because of class conversion from\n%3$s to %4$s"),
421                          name, it->layout()->name(),
422                          from_utf8(oldtc.name()), from_utf8(newtc.name()));
423                         // To warn the user that something had to be done.
424                         errorlist.push_back(ErrorItem(_("Changed Layout"), s,
425                                                       it->id(), 0,
426                                                       it->size()));
427                 }
428         }
429
430         // character styles
431         InsetIterator const i_end = inset_iterator_end(in);
432         for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
433                 InsetCollapsable * inset = it->asInsetCollapsable();
434                 if (!inset)
435                         continue;
436                 if (inset->lyxCode() != FLEX_CODE)
437                         // FIXME: Should we verify all InsetCollapsable?
438                         continue;
439                 inset->setLayout(newtcindex);
440                 if (!inset->undefined())
441                         continue;
442                 // The flex inset is undefined in newtc
443                 docstring const s = bformat(_(
444                         "Flex inset %1$s is "
445                         "undefined because of class "
446                         "conversion from\n%2$s to %3$s"),
447                         inset->name(), from_utf8(oldtc.name()),
448                         from_utf8(newtc.name()));
449                 // To warn the user that something had to be done.
450                 errorlist.push_back(ErrorItem(
451                                 _("Undefined flex inset"),
452                                 s, it.paragraph().id(), it.pos(), it.pos() + 1));
453         }
454 }
455
456
457 vector<docstring> const availableSelections(Buffer const & buffer)
458 {
459         vector<docstring> selList;
460
461         CutStack::const_iterator cit = theCuts.begin();
462         CutStack::const_iterator end = theCuts.end();
463         for (; cit != end; ++cit) {
464                 // we do not use cit-> here because gcc 2.9x does not
465                 // like it (JMarc)
466                 ParagraphList const & pars = (*cit).first;
467                 docstring asciiSel;
468                 ParagraphList::const_iterator pit = pars.begin();
469                 ParagraphList::const_iterator pend = pars.end();
470                 for (; pit != pend; ++pit) {
471                         asciiSel += pit->asString(buffer, false);
472                         if (asciiSel.size() > 25) {
473                                 asciiSel.replace(22, docstring::npos,
474                                                  from_ascii("..."));
475                                 break;
476                         }
477                 }
478
479                 selList.push_back(asciiSel);
480         }
481
482         return selList;
483 }
484
485
486 size_type numberOfSelections()
487 {
488         return theCuts.size();
489 }
490
491
492 void cutSelection(Cursor & cur, bool doclear, bool realcut)
493 {
494         // This doesn't make sense, if there is no selection
495         if (!cur.selection())
496                 return;
497
498         // OK, we have a selection. This is always between cur.selBegin()
499         // and cur.selEnd()
500
501         if (cur.inTexted()) {
502                 Text * text = cur.text();
503                 BOOST_ASSERT(text);
504
505                 saveSelection(cur);
506
507                 // make sure that the depth behind the selection are restored, too
508                 cur.recordUndoSelection();
509                 pit_type begpit = cur.selBegin().pit();
510                 pit_type endpit = cur.selEnd().pit();
511
512                 int endpos = cur.selEnd().pos();
513
514                 BufferParams const & bp = cur.buffer().params();
515                 if (realcut) {
516                         copySelectionHelper(cur.buffer(),
517                                 text->paragraphs(),
518                                 begpit, endpit,
519                                 cur.selBegin().pos(), endpos,
520                                 bp.textClassIndex(), theCuts);
521                         // Stuff what we got on the clipboard.
522                         // Even if there is no selection.
523                         putClipboard(theCuts[0].first, theCuts[0].second,
524                                 cur.selectionAsString(true));
525                 }
526
527                 boost::tie(endpit, endpos) =
528                         eraseSelectionHelper(bp,
529                                 text->paragraphs(),
530                                 begpit, endpit,
531                                 cur.selBegin().pos(), endpos);
532
533                 // cutSelection can invalidate the cursor so we need to set
534                 // it anew. (Lgb)
535                 // we prefer the end for when tracking changes
536                 cur.pos() = endpos;
537                 cur.pit() = endpit;
538
539                 // sometimes necessary
540                 if (doclear
541                         && text->paragraphs()[begpit].stripLeadingSpaces(bp.trackChanges))
542                         cur.fixIfBroken();
543
544                 // need a valid cursor. (Lgb)
545                 cur.clearSelection();
546                 updateLabels(cur.buffer());
547
548                 // tell tabular that a recent copy happened
549                 dirtyTabularStack(false);
550         }
551
552         if (cur.inMathed()) {
553                 if (cur.selBegin().idx() != cur.selEnd().idx()) {
554                         // The current selection spans more than one cell.
555                         // Record all cells
556                         cur.recordUndoInset();
557                 } else {
558                         // Record only the current cell to avoid a jumping
559                         // cursor after undo
560                         cur.recordUndo();
561                 }
562                 if (realcut)
563                         copySelection(cur);
564                 eraseSelection(cur);
565         }
566 }
567
568
569 void copySelection(Cursor & cur)
570 {
571         copySelection(cur, cur.selectionAsString(true));
572 }
573
574
575 namespace {
576
577 void copySelectionToStack(Cursor & cur, CutStack & cutstack)
578 {
579         // this doesn't make sense, if there is no selection
580         if (!cur.selection())
581                 return;
582
583         // copySelection can not yet handle the case of cross idx selection
584         if (cur.selBegin().idx() != cur.selEnd().idx())
585                 return;
586
587         if (cur.inTexted()) {
588                 Text * text = cur.text();
589                 BOOST_ASSERT(text);
590                 // ok we have a selection. This is always between cur.selBegin()
591                 // and sel_end cursor
592
593                 // copy behind a space if there is one
594                 ParagraphList & pars = text->paragraphs();
595                 pos_type pos = cur.selBegin().pos();
596                 pit_type par = cur.selBegin().pit();
597                 while (pos < pars[par].size() &&
598                        pars[par].isLineSeparator(pos) &&
599                        (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
600                         ++pos;
601
602                 copySelectionHelper(cur.buffer(), pars, par, cur.selEnd().pit(),
603                         pos, cur.selEnd().pos(), 
604                         cur.buffer().params().textClassIndex(), cutstack);
605                 dirtyTabularStack(false);
606         }
607
608         if (cur.inMathed()) {
609                 //lyxerr << "copySelection in mathed" << endl;
610                 ParagraphList pars;
611                 Paragraph par;
612                 BufferParams const & bp = cur.buffer().params();
613                 par.setLayout(bp.textClass().defaultLayout());
614                 par.insert(0, grabSelection(cur), Font(), Change(Change::UNCHANGED));
615                 pars.push_back(par);
616                 cutstack.push(make_pair(pars, bp.textClassIndex()));
617         }
618 }
619
620 }
621
622
623 void copySelectionToStack()
624 {
625         if (!selectionBuffer.empty())
626                 theCuts.push(selectionBuffer[0]);
627 }
628
629
630 void copySelection(Cursor & cur, docstring const & plaintext)
631 {
632         // In tablemode, because copy and paste actually use special table stack
633         // we do not attempt to get selected paragraphs under cursor. Instead, a
634         // paragraph with the plain text version is generated so that table cells
635         // can be pasted as pure text somewhere else.
636         if (cur.selBegin().idx() != cur.selEnd().idx()) {
637                 ParagraphList pars;
638                 Paragraph par;
639                 BufferParams const & bp = cur.buffer().params();
640                 par.setLayout(bp.textClass().defaultLayout());
641                 par.insert(0, plaintext, Font(), Change(Change::UNCHANGED));
642                 pars.push_back(par);
643                 theCuts.push(make_pair(pars, bp.textClassIndex()));
644         } else {
645                 copySelectionToStack(cur, theCuts);
646         }
647
648         // stuff the selection onto the X clipboard, from an explicit copy request
649         putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
650 }
651
652
653 void saveSelection(Cursor & cur)
654 {
655         // This function is called, not when a selection is formed, but when
656         // a selection is cleared. Therefore, multiple keyboard selection
657         // will not repeatively trigger this function (bug 3877).
658         if (cur.selection() 
659             && cur.selBegin() == cur.bv().cursor().selBegin()
660             && cur.selEnd() == cur.bv().cursor().selEnd()) {
661                 LYXERR(Debug::ACTION, "'" << cur.selectionAsString(true) << "'");
662                 copySelectionToStack(cur, selectionBuffer);
663         }
664 }
665
666
667 bool selection()
668 {
669         return !selectionBuffer.empty();
670 }
671
672
673 void clearSelection()
674 {
675         selectionBuffer.clear();
676 }
677
678
679 void clearCutStack()
680 {
681         theCuts.clear();
682 }
683
684
685 docstring getSelection(Buffer const & buf, size_t sel_index)
686 {
687         return sel_index < theCuts.size()
688                 ? theCuts[sel_index].first.back().asString(buf, false)
689                 : docstring();
690 }
691
692
693 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
694                         TextClassIndex const & textclass, ErrorList & errorList)
695 {
696         if (cur.inTexted()) {
697                 Text * text = cur.text();
698                 BOOST_ASSERT(text);
699
700                 pit_type endpit;
701                 PitPosPair ppp;
702
703                 boost::tie(ppp, endpit) =
704                         pasteSelectionHelper(cur, parlist, textclass, errorList);
705                 updateLabels(cur.buffer());
706                 cur.clearSelection();
707                 text->setCursor(cur, ppp.first, ppp.second);
708         }
709
710         // mathed is handled in InsetMathNest/InsetMathGrid
711         BOOST_ASSERT(!cur.inMathed());
712 }
713
714
715 void pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
716 {
717         // this does not make sense, if there is nothing to paste
718         if (!checkPastePossible(sel_index))
719                 return;
720
721         cur.recordUndo();
722         pasteParagraphList(cur, theCuts[sel_index].first,
723                            theCuts[sel_index].second, errorList);
724         cur.setSelection();
725 }
726
727
728 void pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs)
729 {
730         // Use internal clipboard if it is the most recent one
731         if (theClipboard().isInternal()) {
732                 pasteFromStack(cur, errorList, 0);
733                 return;
734         }
735
736         // First try LyX format
737         if (theClipboard().hasLyXContents()) {
738                 string lyx = theClipboard().getAsLyX();
739                 if (!lyx.empty()) {
740                         // For some strange reason gcc 3.2 and 3.3 do not accept
741                         // Buffer buffer(string(), false);
742                         Buffer buffer("", false);
743                         buffer.setUnnamed(true);
744                         if (buffer.readString(lyx)) {
745                                 cur.recordUndo();
746                                 pasteParagraphList(cur, buffer.paragraphs(),
747                                         buffer.params().textClassIndex(), errorList);
748                                 cur.setSelection();
749                                 return;
750                         }
751                 }
752         }
753
754         // Then try plain text
755         docstring const text = theClipboard().getAsText();
756         if (text.empty())
757                 return;
758         cur.recordUndo();
759         if (asParagraphs)
760                 cur.text()->insertStringAsParagraphs(cur, text);
761         else
762                 cur.text()->insertStringAsLines(cur, text);
763 }
764
765
766 void pasteClipboardGraphics(Cursor & cur, ErrorList & /*errorList*/,
767                             Clipboard::GraphicsType preferedType)
768 {
769         BOOST_ASSERT(theClipboard().hasGraphicsContents(preferedType));
770
771         // get picture from clipboard
772         FileName filename = theClipboard().getAsGraphics(cur, preferedType);
773         if (filename.empty())
774                 return;
775
776         // create inset for graphic
777         InsetGraphics * inset = new InsetGraphics;
778         InsetGraphicsParams params;
779         params.filename = EmbeddedFile(filename.absFilename(), cur.buffer().filePath());
780         inset->setParams(params);
781         cur.recordUndo();
782         cur.insert(inset);
783 }
784
785
786 void pasteSelection(Cursor & cur, ErrorList & errorList)
787 {
788         if (selectionBuffer.empty())
789                 return;
790         cur.recordUndo();
791         pasteParagraphList(cur, selectionBuffer[0].first,
792                            selectionBuffer[0].second, errorList);
793 }
794
795
796 void replaceSelectionWithString(Cursor & cur, docstring const & str, bool backwards)
797 {
798         cur.recordUndo();
799         DocIterator selbeg = cur.selectionBegin();
800
801         // Get font setting before we cut
802         Font const font =
803                 selbeg.paragraph().getFontSettings(cur.buffer().params(), selbeg.pos());
804
805         // Insert the new string
806         pos_type pos = cur.selEnd().pos();
807         Paragraph & par = cur.selEnd().paragraph();
808         docstring::const_iterator cit = str.begin();
809         docstring::const_iterator end = str.end();
810         for (; cit != end; ++cit, ++pos)
811                 par.insertChar(pos, *cit, font, cur.buffer().params().trackChanges);
812
813         // Cut the selection
814         cutSelection(cur, true, false);
815
816         // select the replacement
817         if (backwards) {
818                 selbeg.pos() += str.length();
819                 cur.setSelection(selbeg, -int(str.length()));
820         } else
821                 cur.setSelection(selbeg, str.length());
822 }
823
824
825 void replaceSelection(Cursor & cur)
826 {
827         if (cur.selection())
828                 cutSelection(cur, true, false);
829 }
830
831
832 void eraseSelection(Cursor & cur)
833 {
834         //lyxerr << "cap::eraseSelection begin: " << cur << endl;
835         CursorSlice const & i1 = cur.selBegin();
836         CursorSlice const & i2 = cur.selEnd();
837         if (i1.inset().asInsetMath()) {
838                 saveSelection(cur);
839                 cur.top() = i1;
840                 if (i1.idx() == i2.idx()) {
841                         i1.cell().erase(i1.pos(), i2.pos());
842                         // We may have deleted i1.cell(cur.pos()).
843                         // Make sure that pos is valid.
844                         if (cur.pos() > cur.lastpos())
845                                 cur.pos() = cur.lastpos();
846                 } else {
847                         InsetMath * p = i1.asInsetMath();
848                         Inset::row_type r1, r2;
849                         Inset::col_type c1, c2;
850                         region(i1, i2, r1, r2, c1, c2);
851                         for (Inset::row_type row = r1; row <= r2; ++row)
852                                 for (Inset::col_type col = c1; col <= c2; ++col)
853                                         p->cell(p->index(row, col)).clear();
854                         // We've deleted the whole cell. Only pos 0 is valid.
855                         cur.pos() = 0;
856                 }
857                 // need a valid cursor. (Lgb)
858                 cur.clearSelection();
859         } else {
860                 lyxerr << "can't erase this selection 1" << endl;
861         }
862         //lyxerr << "cap::eraseSelection end: " << cur << endl;
863 }
864
865
866 void selDel(Cursor & cur)
867 {
868         //lyxerr << "cap::selDel" << endl;
869         if (cur.selection())
870                 eraseSelection(cur);
871 }
872
873
874 void selClearOrDel(Cursor & cur)
875 {
876         //lyxerr << "cap::selClearOrDel" << endl;
877         if (lyxrc.auto_region_delete)
878                 selDel(cur);
879         else
880                 cur.selection() = false;
881 }
882
883
884 docstring grabSelection(Cursor const & cur)
885 {
886         if (!cur.selection())
887                 return docstring();
888
889         // FIXME: What is wrong with the following?
890 #if 0
891         ostringstream os;
892         for (DocIterator dit = cur.selectionBegin();
893              dit != cur.selectionEnd(); dit.forwardPos())
894                 os << asString(dit.cell());
895         return os.str();
896 #endif
897
898         CursorSlice i1 = cur.selBegin();
899         CursorSlice i2 = cur.selEnd();
900
901         if (i1.idx() == i2.idx()) {
902                 if (i1.inset().asInsetMath()) {
903                         MathData::const_iterator it = i1.cell().begin();
904                         return asString(MathData(it + i1.pos(), it + i2.pos()));
905                 } else {
906                         return from_ascii("unknown selection 1");
907                 }
908         }
909
910         Inset::row_type r1, r2;
911         Inset::col_type c1, c2;
912         region(i1, i2, r1, r2, c1, c2);
913
914         docstring data;
915         if (i1.inset().asInsetMath()) {
916                 for (Inset::row_type row = r1; row <= r2; ++row) {
917                         if (row > r1)
918                                 data += "\\\\";
919                         for (Inset::col_type col = c1; col <= c2; ++col) {
920                                 if (col > c1)
921                                         data += '&';
922                                 data += asString(i1.asInsetMath()->
923                                         cell(i1.asInsetMath()->index(row, col)));
924                         }
925                 }
926         } else {
927                 data = from_ascii("unknown selection 2");
928         }
929         return data;
930 }
931
932
933 void dirtyTabularStack(bool b)
934 {
935         dirty_tabular_stack_ = b;
936 }
937
938
939 bool tabularStackDirty()
940 {
941         return dirty_tabular_stack_;
942 }
943
944
945 } // namespace cap
946
947 } // namespace lyx