]> git.lyx.org Git - lyx.git/blob - src/CutAndPaste.cpp
do what the FIXME suggested
[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 "Paragraph.h"
34 #include "paragraph_funcs.h"
35 #include "ParagraphParameters.h"
36 #include "ParIterator.h"
37 #include "Undo.h"
38
39 #include "insets/InsetFlex.h"
40 #include "insets/InsetCommand.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, DocumentClass const *> > 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                      DocumentClass const * const docclass, 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         DocumentClass const * const tc = buffer.params().documentClassPtr();
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         Inset * inset = pars[pit].inInset();
131         if (inset && (inset->lyxCode() == ERT_CODE ||
132                         inset->lyxCode() == LISTINGS_CODE)) {
133                 for (size_t 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().documentClass().emptyLayout();
152                 ParagraphList::iterator const end = insertion.end();
153                 for (ParagraphList::iterator par = insertion.begin();
154                                 par != end; ++par)
155                         par->setLayout(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(docclass, 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         InsetIterator const i_end = inset_iterator_end(in);
217
218         for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
219
220                 it->setBuffer(const_cast<Buffer &>(buffer));
221
222                 switch (it->lyxCode()) {
223  
224                 case LABEL_CODE: {
225                         // check for duplicates
226                         InsetCommand & lab = static_cast<InsetCommand &>(*it);
227                         docstring const oldname = lab.getParam("name");
228                         lab.updateCommand(oldname, false);
229                         docstring const newname = lab.getParam("name");
230                         if (oldname != newname) {
231                                 // adapt the references
232                                 for (InsetIterator itt = inset_iterator_begin(in); itt != i_end; ++itt) {
233                                         if (itt->lyxCode() == REF_CODE) {
234                                                 InsetCommand & ref = dynamic_cast<InsetCommand &>(*itt);
235                                                 if (ref.getParam("reference") == oldname)
236                                                         ref.setParam("reference", newname);
237                                         }
238                                 }
239                         }
240                         break;
241                 }
242
243                 case BIBITEM_CODE: {
244                         // check for duplicates
245                         InsetCommand & bib = static_cast<InsetCommand &>(*it);
246                         docstring const oldkey = bib.getParam("key");
247                         bib.updateCommand(oldkey, false);
248                         docstring const newkey = bib.getParam("key");
249                         if (oldkey != newkey) {
250                                 // adapt the references
251                                 for (InsetIterator itt = inset_iterator_begin(in); itt != i_end; ++itt) {
252                                         if (itt->lyxCode() == CITE_CODE) {
253                                                 InsetCommand & ref = dynamic_cast<InsetCommand &>(*itt);
254                                                 if (ref.getParam("key") == oldkey)
255                                                         ref.setParam("key", newkey);
256                                         }
257                                 }
258                         }
259                         break;
260                 }
261
262                 default:
263                         break; // nothing
264                 }
265         }
266         insertion.swap(in.paragraphs());
267
268         // Split the paragraph for inserting the buf if necessary.
269         if (!empty)
270                 breakParagraphConservative(buffer.params(), pars, pit, pos);
271
272         // Paste it!
273         if (empty) {
274                 pars.insert(boost::next(pars.begin(), pit),
275                             insertion.begin(),
276                             insertion.end());
277
278                 // merge the empty par with the last par of the insertion
279                 mergeParagraph(buffer.params(), pars,
280                                pit + insertion.size() - 1);
281         } else {
282                 pars.insert(boost::next(pars.begin(), pit + 1),
283                             insertion.begin(),
284                             insertion.end());
285
286                 // merge the first par of the insertion with the current par
287                 mergeParagraph(buffer.params(), pars, pit);
288         }
289
290         pit_type last_paste = pit + insertion.size() - 1;
291
292         // Store the new cursor position.
293         pit = last_paste;
294         pos = pars[last_paste].size();
295
296         // Join (conditionally) last pasted paragraph with next one, i.e.,
297         // the tail of the spliced document paragraph
298         if (!empty && last_paste + 1 != pit_type(pars.size())) {
299                 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
300                         mergeParagraph(buffer.params(), pars, last_paste);
301                 } else if (pars[last_paste + 1].empty()) {
302                         pars[last_paste + 1].makeSameLayout(pars[last_paste]);
303                         mergeParagraph(buffer.params(), pars, last_paste);
304                 } else if (pars[last_paste].empty()) {
305                         pars[last_paste].makeSameLayout(pars[last_paste + 1]);
306                         mergeParagraph(buffer.params(), pars, last_paste);
307                 } else {
308                         pars[last_paste + 1].stripLeadingSpaces(buffer.params().trackChanges);
309                         ++last_paste;
310                 }
311         }
312
313         return make_pair(PitPosPair(pit, pos), last_paste + 1);
314 }
315
316
317 PitPosPair eraseSelectionHelper(BufferParams const & params,
318         ParagraphList & pars,
319         pit_type startpit, pit_type endpit,
320         int startpos, int endpos)
321 {
322         // Start of selection is really invalid.
323         if (startpit == pit_type(pars.size()) ||
324             (startpos > pars[startpit].size()))
325                 return PitPosPair(endpit, endpos);
326
327         // Start and end is inside same paragraph
328         if (endpit == pit_type(pars.size()) || startpit == endpit) {
329                 endpos -= pars[startpit].eraseChars(startpos, endpos, params.trackChanges);
330                 return PitPosPair(endpit, endpos);
331         }
332
333         for (pit_type pit = startpit; pit != endpit + 1;) {
334                 pos_type const left  = (pit == startpit ? startpos : 0);
335                 pos_type right = (pit == endpit ? endpos : pars[pit].size() + 1);
336                 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.trackChanges);
337
338                 // Logically erase only, including the end-of-paragraph character
339                 pars[pit].eraseChars(left, right, params.trackChanges);
340
341                 // Separate handling of paragraph break:
342                 if (merge && pit != endpit &&
343                     (pit + 1 != endpit 
344                      || pars[pit].hasSameLayout(pars[endpit])
345                      || pars[endpit].size() == endpos)) {
346                         if (pit + 1 == endpit)
347                                 endpos += pars[pit].size();
348                         mergeParagraph(params, pars, pit);
349                         --endpit;
350                 } else
351                         ++pit;
352         }
353
354         // Ensure legal cursor pos:
355         endpit = startpit;
356         endpos = startpos;
357         return PitPosPair(endpit, endpos);
358 }
359
360
361 void putClipboard(ParagraphList const & paragraphs, 
362         DocumentClass const * const docclass, docstring const & plaintext)
363 {
364         // For some strange reason gcc 3.2 and 3.3 do not accept
365         // Buffer buffer(string(), false);
366         Buffer buffer("", false);
367         buffer.setUnnamed(true);
368         buffer.paragraphs() = paragraphs;
369         buffer.params().setDocumentClass(docclass);
370         ostringstream lyx;
371         if (buffer.write(lyx))
372                 theClipboard().put(lyx.str(), plaintext);
373         else
374                 theClipboard().put(string(), plaintext);
375 }
376
377
378 void copySelectionHelper(Buffer const & buf, ParagraphList & pars,
379         pit_type startpit, pit_type endpit,
380         int start, int end, DocumentClass const * const dc, CutStack & cutstack)
381 {
382         BOOST_ASSERT(0 <= start && start <= pars[startpit].size());
383         BOOST_ASSERT(0 <= end && end <= pars[endpit].size());
384         BOOST_ASSERT(startpit != endpit || start <= end);
385
386         // Clone the paragraphs within the selection.
387         ParagraphList copy_pars(boost::next(pars.begin(), startpit),
388                                 boost::next(pars.begin(), endpit + 1));
389
390         // Remove the end of the last paragraph; afterwards, remove the
391         // beginning of the first paragraph. Keep this order - there may only
392         // be one paragraph!  Do not track deletions here; this is an internal
393         // action not visible to the user
394
395         Paragraph & back = copy_pars.back();
396         back.eraseChars(end, back.size(), false);
397         Paragraph & front = copy_pars.front();
398         front.eraseChars(0, start, false);
399
400         ParagraphList::iterator it = copy_pars.begin();
401         ParagraphList::iterator it_end = copy_pars.end();
402
403         for (; it != it_end; it++) {
404                 // ERT paragraphs have the Language latex_language.
405                 // This is invalid outside of ERT, so we need to change it
406                 // to the buffer language.
407                 if (it->ownerCode() == ERT_CODE || it->ownerCode() == LISTINGS_CODE) {
408                         it->changeLanguage(buf.params(), latex_language, buf.language());
409                 }
410                 it->setInsetOwner(0);
411         }
412
413         // do not copy text (also nested in insets) which is marked as deleted
414         acceptChanges(copy_pars, buf.params());
415
416         DocumentClass * d = const_cast<DocumentClass *>(dc);
417         cutstack.push(make_pair(copy_pars, d));
418 }
419
420 } // namespace anon
421
422
423
424
425 namespace cap {
426
427 docstring grabAndEraseSelection(Cursor & cur)
428 {
429         if (!cur.selection())
430                 return docstring();
431         docstring res = grabSelection(cur);
432         eraseSelection(cur);
433         return res;
434 }
435
436
437 void switchBetweenClasses(DocumentClass const * const oldone, 
438                 DocumentClass const * const newone, InsetText & in, ErrorList & errorlist)
439 {
440         errorlist.clear();
441
442         BOOST_ASSERT(!in.paragraphs().empty());
443         if (oldone == newone)
444                 return;
445         
446         DocumentClass const & oldtc = *oldone;
447         DocumentClass const & newtc = *newone;
448
449         // layouts
450         ParIterator end = par_iterator_end(in);
451         for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
452                 docstring const name = it->layout()->name();
453                 bool hasLayout = newtc.hasLayout(name);
454
455                 if (in.useEmptyLayout())
456                         it->setLayout(newtc.emptyLayout());
457                 else if (hasLayout)
458                         it->setLayout(newtc[name]);
459                 else
460                         it->setLayout(newtc.defaultLayout());
461
462                 if (!hasLayout && name != oldtc.defaultLayoutName()) {
463                         docstring const s = bformat(
464                                                  _("Layout had to be changed from\n%1$s to %2$s\n"
465                                                 "because of class conversion from\n%3$s to %4$s"),
466                          name, it->layout()->name(),
467                          from_utf8(oldtc.name()), from_utf8(newtc.name()));
468                         // To warn the user that something had to be done.
469                         errorlist.push_back(ErrorItem(_("Changed Layout"), s,
470                                                       it->id(), 0,
471                                                       it->size()));
472                 }
473         }
474
475         // character styles
476         InsetIterator const i_end = inset_iterator_end(in);
477         for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
478                 InsetCollapsable * inset = it->asInsetCollapsable();
479                 if (!inset)
480                         continue;
481                 if (inset->lyxCode() != FLEX_CODE)
482                         // FIXME: Should we verify all InsetCollapsable?
483                         continue;
484                 inset->setLayout(newone);
485                 if (!inset->undefined())
486                         continue;
487                 // The flex inset is undefined in newtc
488                 docstring const s = bformat(_(
489                         "Flex inset %1$s is "
490                         "undefined because of class "
491                         "conversion from\n%2$s to %3$s"),
492                         inset->name(), from_utf8(oldtc.name()),
493                         from_utf8(newtc.name()));
494                 // To warn the user that something had to be done.
495                 errorlist.push_back(ErrorItem(
496                                 _("Undefined flex inset"),
497                                 s, it.paragraph().id(), it.pos(), it.pos() + 1));
498         }
499 }
500
501
502 vector<docstring> availableSelections()
503 {
504         vector<docstring> selList;
505
506         CutStack::const_iterator cit = theCuts.begin();
507         CutStack::const_iterator end = theCuts.end();
508         for (; cit != end; ++cit) {
509                 // we do not use cit-> here because gcc 2.9x does not
510                 // like it (JMarc)
511                 ParagraphList const & pars = (*cit).first;
512                 docstring asciiSel;
513                 ParagraphList::const_iterator pit = pars.begin();
514                 ParagraphList::const_iterator pend = pars.end();
515                 for (; pit != pend; ++pit) {
516                         asciiSel += pit->asString(false);
517                         if (asciiSel.size() > 25) {
518                                 asciiSel.replace(22, docstring::npos,
519                                                  from_ascii("..."));
520                                 break;
521                         }
522                 }
523
524                 selList.push_back(asciiSel);
525         }
526
527         return selList;
528 }
529
530
531 size_type numberOfSelections()
532 {
533         return theCuts.size();
534 }
535
536
537 void cutSelection(Cursor & cur, bool doclear, bool realcut)
538 {
539         // This doesn't make sense, if there is no selection
540         if (!cur.selection())
541                 return;
542
543         // OK, we have a selection. This is always between cur.selBegin()
544         // and cur.selEnd()
545
546         if (cur.inTexted()) {
547                 Text * text = cur.text();
548                 BOOST_ASSERT(text);
549
550                 saveSelection(cur);
551
552                 // make sure that the depth behind the selection are restored, too
553                 cur.recordUndoSelection();
554                 pit_type begpit = cur.selBegin().pit();
555                 pit_type endpit = cur.selEnd().pit();
556
557                 int endpos = cur.selEnd().pos();
558
559                 BufferParams const & bp = cur.buffer().params();
560                 if (realcut) {
561                         copySelectionHelper(cur.buffer(),
562                                 text->paragraphs(),
563                                 begpit, endpit,
564                                 cur.selBegin().pos(), endpos,
565                                 bp.documentClassPtr(), theCuts);
566                         // Stuff what we got on the clipboard.
567                         // Even if there is no selection.
568                         putClipboard(theCuts[0].first, theCuts[0].second,
569                                 cur.selectionAsString(true));
570                 }
571
572                 boost::tie(endpit, endpos) =
573                         eraseSelectionHelper(bp,
574                                 text->paragraphs(),
575                                 begpit, endpit,
576                                 cur.selBegin().pos(), endpos);
577
578                 // cutSelection can invalidate the cursor so we need to set
579                 // it anew. (Lgb)
580                 // we prefer the end for when tracking changes
581                 cur.pos() = endpos;
582                 cur.pit() = endpit;
583
584                 // sometimes necessary
585                 if (doclear
586                         && text->paragraphs()[begpit].stripLeadingSpaces(bp.trackChanges))
587                         cur.fixIfBroken();
588
589                 // need a valid cursor. (Lgb)
590                 cur.clearSelection();
591                 updateLabels(cur.buffer());
592
593                 // tell tabular that a recent copy happened
594                 dirtyTabularStack(false);
595         }
596
597         if (cur.inMathed()) {
598                 if (cur.selBegin().idx() != cur.selEnd().idx()) {
599                         // The current selection spans more than one cell.
600                         // Record all cells
601                         cur.recordUndoInset();
602                 } else {
603                         // Record only the current cell to avoid a jumping
604                         // cursor after undo
605                         cur.recordUndo();
606                 }
607                 if (realcut)
608                         copySelection(cur);
609                 eraseSelection(cur);
610         }
611 }
612
613
614 void copySelection(Cursor & cur)
615 {
616         copySelection(cur, cur.selectionAsString(true));
617 }
618
619
620 namespace {
621
622 void copySelectionToStack(Cursor & cur, CutStack & cutstack)
623 {
624         // this doesn't make sense, if there is no selection
625         if (!cur.selection())
626                 return;
627
628         // copySelection can not yet handle the case of cross idx selection
629         if (cur.selBegin().idx() != cur.selEnd().idx())
630                 return;
631
632         if (cur.inTexted()) {
633                 Text * text = cur.text();
634                 BOOST_ASSERT(text);
635                 // ok we have a selection. This is always between cur.selBegin()
636                 // and sel_end cursor
637
638                 // copy behind a space if there is one
639                 ParagraphList & pars = text->paragraphs();
640                 pos_type pos = cur.selBegin().pos();
641                 pit_type par = cur.selBegin().pit();
642                 while (pos < pars[par].size() &&
643                        pars[par].isLineSeparator(pos) &&
644                        (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
645                         ++pos;
646
647                 copySelectionHelper(cur.buffer(), pars, par, cur.selEnd().pit(),
648                         pos, cur.selEnd().pos(), 
649                         cur.buffer().params().documentClassPtr(), cutstack);
650                 dirtyTabularStack(false);
651         }
652
653         if (cur.inMathed()) {
654                 //lyxerr << "copySelection in mathed" << endl;
655                 ParagraphList pars;
656                 Paragraph par;
657                 BufferParams const & bp = cur.buffer().params();
658                 // FIXME This should be the empty layout...right?
659                 par.setLayout(bp.documentClass().emptyLayout());
660                 par.insert(0, grabSelection(cur), Font(), Change(Change::UNCHANGED));
661                 pars.push_back(par);
662                 cutstack.push(make_pair(pars, bp.documentClassPtr()));
663         }
664 }
665
666 }
667
668
669 void copySelectionToStack()
670 {
671         if (!selectionBuffer.empty())
672                 theCuts.push(selectionBuffer[0]);
673 }
674
675
676 void copySelection(Cursor & cur, docstring const & plaintext)
677 {
678         // In tablemode, because copy and paste actually use special table stack
679         // we do not attempt to get selected paragraphs under cursor. Instead, a
680         // paragraph with the plain text version is generated so that table cells
681         // can be pasted as pure text somewhere else.
682         if (cur.selBegin().idx() != cur.selEnd().idx()) {
683                 ParagraphList pars;
684                 Paragraph par;
685                 BufferParams const & bp = cur.buffer().params();
686                 par.setLayout(bp.documentClass().emptyLayout());
687                 par.insert(0, plaintext, Font(), Change(Change::UNCHANGED));
688                 pars.push_back(par);
689                 theCuts.push(make_pair(pars, bp.documentClassPtr()));
690         } else {
691                 copySelectionToStack(cur, theCuts);
692         }
693
694         // stuff the selection onto the X clipboard, from an explicit copy request
695         putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
696 }
697
698
699 void saveSelection(Cursor & cur)
700 {
701         // This function is called, not when a selection is formed, but when
702         // a selection is cleared. Therefore, multiple keyboard selection
703         // will not repeatively trigger this function (bug 3877).
704         if (cur.selection() 
705             && cur.selBegin() == cur.bv().cursor().selBegin()
706             && cur.selEnd() == cur.bv().cursor().selEnd()) {
707                 LYXERR(Debug::ACTION, "'" << cur.selectionAsString(true) << "'");
708                 copySelectionToStack(cur, selectionBuffer);
709         }
710 }
711
712
713 bool selection()
714 {
715         return !selectionBuffer.empty();
716 }
717
718
719 void clearSelection()
720 {
721         selectionBuffer.clear();
722 }
723
724
725 void clearCutStack()
726 {
727         theCuts.clear();
728 }
729
730
731 docstring selection(size_t sel_index)
732 {
733         return sel_index < theCuts.size()
734                 ? theCuts[sel_index].first.back().asString(false)
735                 : docstring();
736 }
737
738
739 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
740                         DocumentClass const * const docclass, ErrorList & errorList)
741 {
742         if (cur.inTexted()) {
743                 Text * text = cur.text();
744                 BOOST_ASSERT(text);
745
746                 pit_type endpit;
747                 PitPosPair ppp;
748
749                 boost::tie(ppp, endpit) =
750                         pasteSelectionHelper(cur, parlist, docclass, errorList);
751                 updateLabels(cur.buffer());
752                 cur.clearSelection();
753                 text->setCursor(cur, ppp.first, ppp.second);
754         }
755
756         // mathed is handled in InsetMathNest/InsetMathGrid
757         BOOST_ASSERT(!cur.inMathed());
758 }
759
760
761 void pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
762 {
763         // this does not make sense, if there is nothing to paste
764         if (!checkPastePossible(sel_index))
765                 return;
766
767         cur.recordUndo();
768         pasteParagraphList(cur, theCuts[sel_index].first,
769                            theCuts[sel_index].second, errorList);
770         cur.setSelection();
771 }
772
773
774 void pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs)
775 {
776         // Use internal clipboard if it is the most recent one
777         if (theClipboard().isInternal()) {
778                 pasteFromStack(cur, errorList, 0);
779                 return;
780         }
781
782         // First try LyX format
783         if (theClipboard().hasLyXContents()) {
784                 string lyx = theClipboard().getAsLyX();
785                 if (!lyx.empty()) {
786                         // For some strange reason gcc 3.2 and 3.3 do not accept
787                         // Buffer buffer(string(), false);
788                         Buffer buffer("", false);
789                         buffer.setUnnamed(true);
790                         if (buffer.readString(lyx)) {
791                                 cur.recordUndo();
792                                 pasteParagraphList(cur, buffer.paragraphs(),
793                                         buffer.params().documentClassPtr(), errorList);
794                                 cur.setSelection();
795                                 return;
796                         }
797                 }
798         }
799
800         // Then try plain text
801         docstring const text = theClipboard().getAsText();
802         if (text.empty())
803                 return;
804         cur.recordUndo();
805         if (asParagraphs)
806                 cur.text()->insertStringAsParagraphs(cur, text);
807         else
808                 cur.text()->insertStringAsLines(cur, text);
809 }
810
811
812 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
813                             Clipboard::GraphicsType preferedType)
814 {
815         BOOST_ASSERT(theClipboard().hasGraphicsContents(preferedType));
816
817         // get picture from clipboard
818         FileName filename = theClipboard().getAsGraphics(cur, preferedType);
819         if (filename.empty())
820                 return;
821
822         // create inset for graphic
823         InsetGraphics * inset = new InsetGraphics;
824         InsetGraphicsParams params;
825         params.filename = EmbeddedFile(filename.absFilename(), cur.buffer().filePath());
826         inset->setParams(params);
827         cur.recordUndo();
828         cur.insert(inset);
829 }
830
831
832 void pasteSelection(Cursor & cur, ErrorList & errorList)
833 {
834         if (selectionBuffer.empty())
835                 return;
836         cur.recordUndo();
837         pasteParagraphList(cur, selectionBuffer[0].first,
838                            selectionBuffer[0].second, errorList);
839 }
840
841
842 void replaceSelectionWithString(Cursor & cur, docstring const & str, bool backwards)
843 {
844         cur.recordUndo();
845         DocIterator selbeg = cur.selectionBegin();
846
847         // Get font setting before we cut
848         Font const font =
849                 selbeg.paragraph().getFontSettings(cur.buffer().params(), selbeg.pos());
850
851         // Insert the new string
852         pos_type pos = cur.selEnd().pos();
853         Paragraph & par = cur.selEnd().paragraph();
854         docstring::const_iterator cit = str.begin();
855         docstring::const_iterator end = str.end();
856         for (; cit != end; ++cit, ++pos)
857                 par.insertChar(pos, *cit, font, cur.buffer().params().trackChanges);
858
859         // Cut the selection
860         cutSelection(cur, true, false);
861
862         // select the replacement
863         if (backwards) {
864                 selbeg.pos() += str.length();
865                 cur.setSelection(selbeg, -int(str.length()));
866         } else
867                 cur.setSelection(selbeg, str.length());
868 }
869
870
871 void replaceSelection(Cursor & cur)
872 {
873         if (cur.selection())
874                 cutSelection(cur, true, false);
875 }
876
877
878 void eraseSelection(Cursor & cur)
879 {
880         //lyxerr << "cap::eraseSelection begin: " << cur << endl;
881         CursorSlice const & i1 = cur.selBegin();
882         CursorSlice const & i2 = cur.selEnd();
883         if (i1.inset().asInsetMath()) {
884                 saveSelection(cur);
885                 cur.top() = i1;
886                 if (i1.idx() == i2.idx()) {
887                         i1.cell().erase(i1.pos(), i2.pos());
888                         // We may have deleted i1.cell(cur.pos()).
889                         // Make sure that pos is valid.
890                         if (cur.pos() > cur.lastpos())
891                                 cur.pos() = cur.lastpos();
892                 } else {
893                         InsetMath * p = i1.asInsetMath();
894                         Inset::row_type r1, r2;
895                         Inset::col_type c1, c2;
896                         region(i1, i2, r1, r2, c1, c2);
897                         for (Inset::row_type row = r1; row <= r2; ++row)
898                                 for (Inset::col_type col = c1; col <= c2; ++col)
899                                         p->cell(p->index(row, col)).clear();
900                         // We've deleted the whole cell. Only pos 0 is valid.
901                         cur.pos() = 0;
902                 }
903                 // need a valid cursor. (Lgb)
904                 cur.clearSelection();
905         } else {
906                 lyxerr << "can't erase this selection 1" << endl;
907         }
908         //lyxerr << "cap::eraseSelection end: " << cur << endl;
909 }
910
911
912 void selDel(Cursor & cur)
913 {
914         //lyxerr << "cap::selDel" << endl;
915         if (cur.selection())
916                 eraseSelection(cur);
917 }
918
919
920 void selClearOrDel(Cursor & cur)
921 {
922         //lyxerr << "cap::selClearOrDel" << endl;
923         if (lyxrc.auto_region_delete)
924                 selDel(cur);
925         else
926                 cur.selection() = false;
927 }
928
929
930 docstring grabSelection(Cursor const & cur)
931 {
932         if (!cur.selection())
933                 return docstring();
934
935         // FIXME: What is wrong with the following?
936 #if 0
937         ostringstream os;
938         for (DocIterator dit = cur.selectionBegin();
939              dit != cur.selectionEnd(); dit.forwardPos())
940                 os << asString(dit.cell());
941         return os.str();
942 #endif
943
944         CursorSlice i1 = cur.selBegin();
945         CursorSlice i2 = cur.selEnd();
946
947         if (i1.idx() == i2.idx()) {
948                 if (i1.inset().asInsetMath()) {
949                         MathData::const_iterator it = i1.cell().begin();
950                         return asString(MathData(it + i1.pos(), it + i2.pos()));
951                 } else {
952                         return from_ascii("unknown selection 1");
953                 }
954         }
955
956         Inset::row_type r1, r2;
957         Inset::col_type c1, c2;
958         region(i1, i2, r1, r2, c1, c2);
959
960         docstring data;
961         if (i1.inset().asInsetMath()) {
962                 for (Inset::row_type row = r1; row <= r2; ++row) {
963                         if (row > r1)
964                                 data += "\\\\";
965                         for (Inset::col_type col = c1; col <= c2; ++col) {
966                                 if (col > c1)
967                                         data += '&';
968                                 data += asString(i1.asInsetMath()->
969                                         cell(i1.asInsetMath()->index(row, col)));
970                         }
971                 }
972         } else {
973                 data = from_ascii("unknown selection 2");
974         }
975         return data;
976 }
977
978
979 void dirtyTabularStack(bool b)
980 {
981         dirty_tabular_stack_ = b;
982 }
983
984
985 bool tabularStackDirty()
986 {
987         return dirty_tabular_stack_;
988 }
989
990
991 } // namespace cap
992
993 } // namespace lyx