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