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