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