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