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