]> git.lyx.org Git - lyx.git/blob - src/CutAndPaste.cpp
BufferParams.cpp: change the package loading to:
[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 "Cursor.h"
23 #include "debug.h"
24 #include "ErrorList.h"
25 #include "FuncRequest.h"
26 #include "gettext.h"
27 #include "InsetIterator.h"
28 #include "Language.h"
29 #include "lfuns.h"
30 #include "LyXFunc.h"
31 #include "LyXRC.h"
32 #include "Text.h"
33 #include "TextClassList.h"
34 #include "Paragraph.h"
35 #include "paragraph_funcs.h"
36 #include "ParagraphParameters.h"
37 #include "ParIterator.h"
38 #include "Undo.h"
39
40 #include "insets/InsetFlex.h"
41 #include "insets/InsetTabular.h"
42
43 #include "mathed/MathData.h"
44 #include "mathed/InsetMath.h"
45 #include "mathed/MathSupport.h"
46
47 #include "support/lstrings.h"
48
49 #include "frontends/Clipboard.h"
50 #include "frontends/Selection.h"
51
52 #include <boost/current_function.hpp>
53 #include <boost/tuple/tuple.hpp>
54
55 #include <string>
56
57 using std::endl;
58 using std::for_each;
59 using std::make_pair;
60 using std::pair;
61 using std::vector;
62 using std::string;
63
64
65 namespace lyx {
66
67 using support::bformat;
68 using frontend::Clipboard;
69
70 namespace {
71
72 typedef std::pair<pit_type, int> PitPosPair;
73
74 typedef limited_stack<pair<ParagraphList, TextClassPtr> > CutStack;
75
76 CutStack theCuts(10);
77 // persistent selection, cleared until the next selection
78 CutStack selectionBuffer(1);
79
80 // store whether the tabular stack is newer than the normal copy stack
81 // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
82 // when we (hopefully) have a one-for-all paste mechanism.
83 bool dirty_tabular_stack_ = false;
84
85
86 void region(CursorSlice const & i1, CursorSlice const & i2,
87         Inset::row_type & r1, Inset::row_type & r2,
88         Inset::col_type & c1, Inset::col_type & c2)
89 {
90         Inset & p = i1.inset();
91         c1 = p.col(i1.idx());
92         c2 = p.col(i2.idx());
93         if (c1 > c2)
94                 std::swap(c1, c2);
95         r1 = p.row(i1.idx());
96         r2 = p.row(i2.idx());
97         if (r1 > r2)
98                 std::swap(r1, r2);
99 }
100
101
102 bool checkPastePossible(int index)
103 {
104         return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
105 }
106
107
108 pair<PitPosPair, pit_type>
109 pasteSelectionHelper(Cursor & cur, ParagraphList const & parlist,
110                      TextClassPtr textclass, ErrorList & errorlist)
111 {
112         Buffer const & buffer = cur.buffer();
113         pit_type pit = cur.pit();
114         pos_type pos = cur.pos();
115         ParagraphList & pars = cur.text()->paragraphs();
116
117         if (parlist.empty())
118                 return make_pair(PitPosPair(pit, pos), pit);
119
120         BOOST_ASSERT (pos <= pars[pit].size());
121
122         // Make a copy of the CaP paragraphs.
123         ParagraphList insertion = parlist;
124         TextClassPtr const tc = buffer.params().getTextClassPtr();
125
126         // Now remove all out of the pars which is NOT allowed in the
127         // new environment and set also another font if that is required.
128
129         // Convert newline to paragraph break in ERT inset.
130         // This should not be here!
131         if (pars[pit].inInset() &&
132             (pars[pit].inInset()->lyxCode() == Inset::ERT_CODE ||
133                 pars[pit].inInset()->lyxCode() == Inset::LISTINGS_CODE)) {
134                 for (ParagraphList::size_type i = 0; i < insertion.size(); ++i) {
135                         for (pos_type j = 0; j < insertion[i].size(); ++j) {
136                                 if (insertion[i].isNewline(j)) {
137                                         // do not track deletion of newline
138                                         insertion[i].eraseChar(j, false);
139                                         breakParagraphConservative(
140                                                         buffer.params(),
141                                                         insertion, i, j);
142                                 }
143                         }
144                 }
145         }
146
147         // If we are in an inset which returns forceDefaultParagraphs,
148         // set the paragraphs to default
149         if (cur.inset().forceDefaultParagraphs(cur.idx())) {
150                 LayoutPtr const layout =
151                         buffer.params().getTextClass().defaultLayout();
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                         if (tmpbuf->getChar(i) == Paragraph::META_INSET &&
196                             !pars[pit].insetAllowed(tmpbuf->getInset(i)->lyxCode()))
197                                 // do not track deletion of invalid insets
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 Inset::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 || pars[pit].hasSameLayout(pars[endpit]))) {
314                         if (pit + 1 == endpit)
315                                 endpos += pars[pit].size();
316                         mergeParagraph(params, pars, pit);
317                         --endpit;
318                 } else
319                         ++pit;
320         }
321
322         // Ensure legal cursor pos:
323         endpit = startpit;
324         endpos = startpos;
325         return PitPosPair(endpit, endpos);
326 }
327
328
329 void putClipboard(ParagraphList const & paragraphs, TextClassPtr textclass,
330                   docstring const & plaintext)
331 {
332         // For some strange reason gcc 3.2 and 3.3 do not accept
333         // Buffer buffer(string(), false);
334         Buffer buffer("", false);
335         buffer.setUnnamed(true);
336         buffer.paragraphs() = paragraphs;
337         buffer.params().setTextClass(textclass);
338         std::ostringstream lyx;
339         if (buffer.write(lyx))
340                 theClipboard().put(lyx.str(), plaintext);
341         else
342                 theClipboard().put(string(), plaintext);
343 }
344
345
346 void copySelectionHelper(Buffer const & buf, ParagraphList & pars,
347         pit_type startpit, pit_type endpit,
348         int start, int end, TextClassPtr tc, CutStack & cutstack)
349 {
350         BOOST_ASSERT(0 <= start && start <= pars[startpit].size());
351         BOOST_ASSERT(0 <= end && end <= pars[endpit].size());
352         BOOST_ASSERT(startpit != endpit || start <= end);
353
354         // Clone the paragraphs within the selection.
355         ParagraphList copy_pars(boost::next(pars.begin(), startpit),
356                                 boost::next(pars.begin(), endpit + 1));
357
358         // Remove the end of the last paragraph; afterwards, remove the
359         // beginning of the first paragraph. Keep this order - there may only
360         // be one paragraph!  Do not track deletions here; this is an internal
361         // action not visible to the user
362
363         Paragraph & back = copy_pars.back();
364         back.eraseChars(end, back.size(), false);
365         Paragraph & front = copy_pars.front();
366         front.eraseChars(0, start, false);
367
368         ParagraphList::iterator it = copy_pars.begin();
369         ParagraphList::iterator it_end = copy_pars.end();
370
371         for (; it != it_end; it++) {
372                 // ERT paragraphs have the Language latex_language.
373                 // This is invalid outside of ERT, so we need to change it
374                 // to the buffer language.
375                 if (it->ownerCode() == Inset::ERT_CODE || it->ownerCode() == Inset::LISTINGS_CODE) {
376                         it->changeLanguage(buf.params(), latex_language,
377                                            buf.getLanguage());
378                 }
379                 it->setInsetOwner(0);
380         }
381
382         // do not copy text (also nested in insets) which is marked as deleted
383         acceptChanges(copy_pars, buf.params());
384
385         cutstack.push(make_pair(copy_pars, tc));
386 }
387
388 } // namespace anon
389
390
391
392
393 namespace cap {
394
395 docstring grabAndEraseSelection(Cursor & cur)
396 {
397         if (!cur.selection())
398                 return docstring();
399         docstring res = grabSelection(cur);
400         eraseSelection(cur);
401         return res;
402 }
403
404
405 void switchBetweenClasses(TextClassPtr const & c1, 
406         TextClassPtr const & c2, InsetText & in, ErrorList & errorlist)
407 {
408         errorlist.clear();
409
410         BOOST_ASSERT(!in.paragraphs().empty());
411         if (c1 == c2)
412                 return;
413         
414         TextClass const & tclass1 = *c1;
415         TextClass const & tclass2 = *c2;
416
417         // layouts
418         ParIterator end = par_iterator_end(in);
419         for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
420                 docstring const name = it->layout()->name();
421                 bool hasLayout = tclass2.hasLayout(name);
422
423                 if (hasLayout)
424                         it->layout(tclass2[name]);
425                 else
426                         it->layout(tclass2.defaultLayout());
427
428                 if (!hasLayout && name != tclass1.defaultLayoutName()) {
429                         docstring const s = bformat(
430                                                  _("Layout had to be changed from\n%1$s to %2$s\n"
431                                                 "because of class conversion from\n%3$s to %4$s"),
432                          name, it->layout()->name(),
433                          from_utf8(tclass1.name()), from_utf8(tclass2.name()));
434                         // To warn the user that something had to be done.
435                         errorlist.push_back(ErrorItem(_("Changed Layout"), s,
436                                                       it->id(), 0,
437                                                       it->size()));
438                 }
439         }
440
441         // character styles
442         InsetIterator const i_end = inset_iterator_end(in);
443         for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
444                 if (it->lyxCode() == Inset::FLEX_CODE) {
445                         InsetFlex & inset =
446                                 static_cast<InsetFlex &>(*it);
447                         string const name = inset.params().name;
448                         InsetLayout const il = 
449                                 tclass2.insetlayout(from_utf8(name));
450                         inset.setLayout(il);
451                         if (il.labelstring == from_utf8("UNDEFINED")) {
452                                 // The flex inset is undefined in tclass2
453                                 docstring const s = bformat(_(
454                                         "Flex inset %1$s is "
455                                         "undefined because of class "
456                                         "conversion from\n%2$s to %3$s"),
457                                          from_utf8(name), from_utf8(tclass1.name()),
458                                          from_utf8(tclass2.name()));
459                                 // To warn the user that something had to be done.
460                                 errorlist.push_back(ErrorItem(
461                                         _("Undefined flex inset"),
462                                         s, it.paragraph().id(), it.pos(), it.pos() + 1));
463                         } 
464                 }
465         }
466 }
467
468
469 std::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                 recordUndoSelection(cur);
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                         recordUndoInset(cur);
569                 } else {
570                         // Record only the current cell to avoid a jumping
571                         // cursor after undo
572                         recordUndo(cur);
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 attemp 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         // stuff the selection onto the X clipboard, from an explicit copy request
660         putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
661 }
662
663
664 void saveSelection(Cursor & cur)
665 {
666         // This function is called, not when a selection is formed, but when
667         // a selection is cleared. Therefore, multiple keyboard selection
668         // will not repeatively trigger this function (bug 3877).
669         if (cur.selection() 
670             && cur.selBegin() == cur.bv().cursor().selBegin()
671             && cur.selEnd() == cur.bv().cursor().selEnd()) {
672                 LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION << ": `"
673                            << to_utf8(cur.selectionAsString(true)) << "'."
674                            << endl;
675                 copySelectionToStack(cur, selectionBuffer);
676         }
677 }
678
679
680 bool selection()
681 {
682         return !selectionBuffer.empty();
683 }
684
685
686 void clearSelection()
687 {
688         selectionBuffer.clear();
689 }
690
691
692 void clearCutStack()
693 {
694         theCuts.clear();
695 }
696
697
698 docstring getSelection(Buffer const & buf, size_t sel_index)
699 {
700         return sel_index < theCuts.size()
701                 ? theCuts[sel_index].first.back().asString(buf, false)
702                 : docstring();
703 }
704
705
706 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
707                         TextClassPtr textclass, ErrorList & errorList)
708 {
709         if (cur.inTexted()) {
710                 Text * text = cur.text();
711                 BOOST_ASSERT(text);
712
713                 pit_type endpit;
714                 PitPosPair ppp;
715
716                 boost::tie(ppp, endpit) =
717                         pasteSelectionHelper(cur, parlist,
718                                              textclass, errorList);
719                 updateLabels(cur.buffer());
720                 cur.clearSelection();
721                 text->setCursor(cur, ppp.first, ppp.second);
722         }
723
724         // mathed is handled in InsetMathNest/InsetMathGrid
725         BOOST_ASSERT(!cur.inMathed());
726 }
727
728
729 void pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
730 {
731         // this does not make sense, if there is nothing to paste
732         if (!checkPastePossible(sel_index))
733                 return;
734
735         recordUndo(cur);
736         pasteParagraphList(cur, theCuts[sel_index].first,
737                            theCuts[sel_index].second, errorList);
738         cur.setSelection();
739 }
740
741
742 void pasteClipboard(Cursor & cur, ErrorList & errorList, bool asParagraphs)
743 {
744         // Use internal clipboard if it is the most recent one
745         if (theClipboard().isInternal()) {
746                 pasteFromStack(cur, errorList, 0);
747                 return;
748         }
749
750         // First try LyX format
751         if (theClipboard().hasLyXContents()) {
752                 string lyx = theClipboard().getAsLyX();
753                 if (!lyx.empty()) {
754                         // For some strange reason gcc 3.2 and 3.3 do not accept
755                         // Buffer buffer(string(), false);
756                         Buffer buffer("", false);
757                         buffer.setUnnamed(true);
758                         if (buffer.readString(lyx)) {
759                                 recordUndo(cur);
760                                 pasteParagraphList(cur, buffer.paragraphs(),
761                                         buffer.params().getTextClassPtr(), errorList);
762                                 cur.setSelection();
763                                 return;
764                         }
765                 }
766         }
767
768         // Then try plain text
769         docstring const text = theClipboard().getAsText();
770         if (text.empty())
771                 return;
772         recordUndo(cur);
773         if (asParagraphs)
774                 cur.text()->insertStringAsParagraphs(cur, text);
775         else
776                 cur.text()->insertStringAsLines(cur, text);
777 }
778
779
780 void pasteSelection(Cursor & cur, ErrorList & errorList)
781 {
782         if (selectionBuffer.empty())
783                 return;
784         recordUndo(cur);
785         pasteParagraphList(cur, selectionBuffer[0].first,
786                            selectionBuffer[0].second, errorList);
787 }
788
789
790 void replaceSelectionWithString(Cursor & cur, docstring const & str, bool backwards)
791 {
792         recordUndo(cur);
793         DocIterator selbeg = cur.selectionBegin();
794
795         // Get font setting before we cut
796         Font const font =
797                 selbeg.paragraph().getFontSettings(cur.buffer().params(), selbeg.pos());
798
799         // Insert the new string
800         pos_type pos = cur.selEnd().pos();
801         Paragraph & par = cur.selEnd().paragraph();
802         docstring::const_iterator cit = str.begin();
803         docstring::const_iterator end = str.end();
804         for (; cit != end; ++cit, ++pos)
805                 par.insertChar(pos, *cit, font, cur.buffer().params().trackChanges);
806
807         // Cut the selection
808         cutSelection(cur, true, false);
809
810         // select the replacement
811         if (backwards) {
812                 selbeg.pos() += str.length();
813                 cur.setSelection(selbeg, -int(str.length()));
814         } else
815                 cur.setSelection(selbeg, str.length());
816 }
817
818
819 void replaceSelection(Cursor & cur)
820 {
821         if (cur.selection())
822                 cutSelection(cur, true, false);
823 }
824
825
826 void eraseSelection(Cursor & cur)
827 {
828         //lyxerr << "cap::eraseSelection begin: " << cur << endl;
829         CursorSlice const & i1 = cur.selBegin();
830         CursorSlice const & i2 = cur.selEnd();
831         if (i1.inset().asInsetMath()) {
832                 saveSelection(cur);
833                 cur.top() = i1;
834                 if (i1.idx() == i2.idx()) {
835                         i1.cell().erase(i1.pos(), i2.pos());
836                         // We may have deleted i1.cell(cur.pos()).
837                         // Make sure that pos is valid.
838                         if (cur.pos() > cur.lastpos())
839                                 cur.pos() = cur.lastpos();
840                 } else {
841                         InsetMath * p = i1.asInsetMath();
842                         Inset::row_type r1, r2;
843                         Inset::col_type c1, c2;
844                         region(i1, i2, r1, r2, c1, c2);
845                         for (Inset::row_type row = r1; row <= r2; ++row)
846                                 for (Inset::col_type col = c1; col <= c2; ++col)
847                                         p->cell(p->index(row, col)).clear();
848                         // We've deleted the whole cell. Only pos 0 is valid.
849                         cur.pos() = 0;
850                 }
851                 // need a valid cursor. (Lgb)
852                 cur.clearSelection();
853         } else {
854                 lyxerr << "can't erase this selection 1" << endl;
855         }
856         //lyxerr << "cap::eraseSelection end: " << cur << endl;
857 }
858
859
860 void selDel(Cursor & cur)
861 {
862         //lyxerr << "cap::selDel" << endl;
863         if (cur.selection())
864                 eraseSelection(cur);
865 }
866
867
868 void selClearOrDel(Cursor & cur)
869 {
870         //lyxerr << "cap::selClearOrDel" << endl;
871         if (lyxrc.auto_region_delete)
872                 selDel(cur);
873         else
874                 cur.selection() = false;
875 }
876
877
878 docstring grabSelection(Cursor const & cur)
879 {
880         if (!cur.selection())
881                 return docstring();
882
883         // FIXME: What is wrong with the following?
884 #if 0
885         std::ostringstream os;
886         for (DocIterator dit = cur.selectionBegin();
887              dit != cur.selectionEnd(); dit.forwardPos())
888                 os << asString(dit.cell());
889         return os.str();
890 #endif
891
892         CursorSlice i1 = cur.selBegin();
893         CursorSlice i2 = cur.selEnd();
894
895         if (i1.idx() == i2.idx()) {
896                 if (i1.inset().asInsetMath()) {
897                         MathData::const_iterator it = i1.cell().begin();
898                         return asString(MathData(it + i1.pos(), it + i2.pos()));
899                 } else {
900                         return from_ascii("unknown selection 1");
901                 }
902         }
903
904         Inset::row_type r1, r2;
905         Inset::col_type c1, c2;
906         region(i1, i2, r1, r2, c1, c2);
907
908         docstring data;
909         if (i1.inset().asInsetMath()) {
910                 for (Inset::row_type row = r1; row <= r2; ++row) {
911                         if (row > r1)
912                                 data += "\\\\";
913                         for (Inset::col_type col = c1; col <= c2; ++col) {
914                                 if (col > c1)
915                                         data += '&';
916                                 data += asString(i1.asInsetMath()->
917                                         cell(i1.asInsetMath()->index(row, col)));
918                         }
919                 }
920         } else {
921                 data = from_ascii("unknown selection 2");
922         }
923         return data;
924 }
925
926
927 void dirtyTabularStack(bool b)
928 {
929         dirty_tabular_stack_ = b;
930 }
931
932
933 bool tabularStackDirty()
934 {
935         return dirty_tabular_stack_;
936 }
937
938
939 } // namespace cap
940
941 } // namespace lyx