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