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