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