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