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