]> git.lyx.org Git - lyx.git/blob - src/CutAndPaste.cpp
eb70bb8e1e89005bfae2a7831e871562fabef7c5
[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         buffer->setUnnamed(true);
371         buffer->paragraphs() = paragraphs;
372         buffer->params().setDocumentClass(docclass);
373         ostringstream lyx;
374         if (buffer->write(lyx))
375                 theClipboard().put(lyx.str(), plaintext);
376         else
377                 theClipboard().put(string(), plaintext);
378         // Save that memory
379         buffer->paragraphs().clear();
380 }
381
382
383 void copySelectionHelper(Buffer const & buf, ParagraphList & pars,
384         pit_type startpit, pit_type endpit,
385         int start, int end, DocumentClass const * const dc, CutStack & cutstack)
386 {
387         LASSERT(0 <= start && start <= pars[startpit].size(), /**/);
388         LASSERT(0 <= end && end <= pars[endpit].size(), /**/);
389         LASSERT(startpit != endpit || start <= end, /**/);
390
391         // Clone the paragraphs within the selection.
392         ParagraphList copy_pars(boost::next(pars.begin(), startpit),
393                                 boost::next(pars.begin(), endpit + 1));
394
395         // Remove the end of the last paragraph; afterwards, remove the
396         // beginning of the first paragraph. Keep this order - there may only
397         // be one paragraph!  Do not track deletions here; this is an internal
398         // action not visible to the user
399
400         Paragraph & back = copy_pars.back();
401         back.eraseChars(end, back.size(), false);
402         Paragraph & front = copy_pars.front();
403         front.eraseChars(0, start, false);
404
405         ParagraphList::iterator it = copy_pars.begin();
406         ParagraphList::iterator it_end = copy_pars.end();
407
408         for (; it != it_end; it++) {
409                 // ERT paragraphs have the Language latex_language.
410                 // This is invalid outside of ERT, so we need to change it
411                 // to the buffer language.
412                 if (it->ownerCode() == ERT_CODE || it->ownerCode() == LISTINGS_CODE) {
413                         it->changeLanguage(buf.params(), latex_language, buf.language());
414                 }
415                 it->setInsetOwner(0);
416         }
417
418         // do not copy text (also nested in insets) which is marked as deleted
419         acceptChanges(copy_pars, buf.params());
420
421         DocumentClass * d = const_cast<DocumentClass *>(dc);
422         cutstack.push(make_pair(copy_pars, d));
423 }
424
425 } // namespace anon
426
427
428
429
430 namespace cap {
431
432 void region(CursorSlice const & i1, CursorSlice const & i2,
433             Inset::row_type & r1, Inset::row_type & r2,
434             Inset::col_type & c1, Inset::col_type & c2)
435 {
436         Inset & p = i1.inset();
437         c1 = p.col(i1.idx());
438         c2 = p.col(i2.idx());
439         if (c1 > c2)
440                 swap(c1, c2);
441         r1 = p.row(i1.idx());
442         r2 = p.row(i2.idx());
443         if (r1 > r2)
444                 swap(r1, r2);
445 }
446
447
448 docstring grabAndEraseSelection(Cursor & cur)
449 {
450         if (!cur.selection())
451                 return docstring();
452         docstring res = grabSelection(cur);
453         eraseSelection(cur);
454         return res;
455 }
456
457
458 bool reduceSelectionToOneCell(Cursor & cur)
459 {
460         if (!cur.selection() || !cur.inMathed())
461                 return false;
462
463         CursorSlice i1 = cur.selBegin();
464         CursorSlice i2 = cur.selEnd();
465         if (!i1.inset().asInsetMath())
466                 return false;
467
468         // the easy case: do nothing if only one cell is selected
469         if (i1.idx() == i2.idx())
470                 return true;
471         
472         cur.top().pos() = 0;
473         cur.resetAnchor();
474         cur.top().pos() = cur.top().lastpos();
475         
476         return true;
477 }
478
479
480 bool multipleCellsSelected(Cursor const & cur)
481 {
482         if (!cur.selection() || !cur.inMathed())
483                 return false;
484         
485         CursorSlice i1 = cur.selBegin();
486         CursorSlice i2 = cur.selEnd();
487         if (!i1.inset().asInsetMath())
488                 return false;
489         
490         if (i1.idx() == i2.idx())
491                 return false;
492         
493         return true;
494 }
495
496
497 void switchBetweenClasses(DocumentClass const * const oldone, 
498                 DocumentClass const * const newone, InsetText & in, ErrorList & errorlist)
499 {
500         errorlist.clear();
501
502         LASSERT(!in.paragraphs().empty(), /**/);
503         if (oldone == newone)
504                 return;
505         
506         DocumentClass const & oldtc = *oldone;
507         DocumentClass const & newtc = *newone;
508
509         // layouts
510         ParIterator end = par_iterator_end(in);
511         for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
512                 docstring const name = it->layout().name();
513
514                 // the pasted text will keep their own layout name. If this layout does
515                 // not exist in the new document, it will behave like a standard layout.
516                 newtc.addLayoutIfNeeded(name);
517
518                 if (in.usePlainLayout())
519                         it->setLayout(newtc.emptyLayout());
520                 else
521                         it->setLayout(newtc[name]);
522         }
523
524         // character styles
525         InsetIterator const i_end = inset_iterator_end(in);
526         for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
527                 InsetCollapsable * inset = it->asInsetCollapsable();
528                 if (!inset)
529                         continue;
530                 if (inset->lyxCode() != FLEX_CODE)
531                         // FIXME: Should we verify all InsetCollapsable?
532                         continue;
533                 inset->setLayout(newone);
534                 if (!inset->undefined())
535                         continue;
536                 // The flex inset is undefined in newtc
537                 docstring const s = bformat(_(
538                         "Flex inset %1$s is "
539                         "undefined because of class "
540                         "conversion from\n%2$s to %3$s"),
541                         inset->name(), from_utf8(oldtc.name()),
542                         from_utf8(newtc.name()));
543                 // To warn the user that something had to be done.
544                 errorlist.push_back(ErrorItem(
545                                 _("Undefined flex inset"),
546                                 s, it.paragraph().id(), it.pos(), it.pos() + 1));
547         }
548 }
549
550
551 vector<docstring> availableSelections()
552 {
553         vector<docstring> selList;
554
555         CutStack::const_iterator cit = theCuts.begin();
556         CutStack::const_iterator end = theCuts.end();
557         for (; cit != end; ++cit) {
558                 // we do not use cit-> here because gcc 2.9x does not
559                 // like it (JMarc)
560                 ParagraphList const & pars = (*cit).first;
561                 docstring asciiSel;
562                 ParagraphList::const_iterator pit = pars.begin();
563                 ParagraphList::const_iterator pend = pars.end();
564                 for (; pit != pend; ++pit) {
565                         asciiSel += pit->asString(AS_STR_INSETS);
566                         if (asciiSel.size() > 25) {
567                                 asciiSel.replace(22, docstring::npos,
568                                                  from_ascii("..."));
569                                 break;
570                         }
571                 }
572
573                 selList.push_back(asciiSel);
574         }
575
576         return selList;
577 }
578
579
580 size_type numberOfSelections()
581 {
582         return theCuts.size();
583 }
584
585
586 void cutSelection(Cursor & cur, bool doclear, bool realcut)
587 {
588         // This doesn't make sense, if there is no selection
589         if (!cur.selection())
590                 return;
591
592         // OK, we have a selection. This is always between cur.selBegin()
593         // and cur.selEnd()
594
595         if (cur.inTexted()) {
596                 Text * text = cur.text();
597                 LASSERT(text, /**/);
598
599                 saveSelection(cur);
600
601                 // make sure that the depth behind the selection are restored, too
602                 cur.recordUndoSelection();
603                 pit_type begpit = cur.selBegin().pit();
604                 pit_type endpit = cur.selEnd().pit();
605
606                 int endpos = cur.selEnd().pos();
607
608                 BufferParams const & bp = cur.buffer().params();
609                 if (realcut) {
610                         copySelectionHelper(cur.buffer(),
611                                 text->paragraphs(),
612                                 begpit, endpit,
613                                 cur.selBegin().pos(), endpos,
614                                 bp.documentClassPtr(), theCuts);
615                         // Stuff what we got on the clipboard.
616                         // Even if there is no selection.
617                         putClipboard(theCuts[0].first, theCuts[0].second,
618                                 cur.selectionAsString(true));
619                 }
620
621                 if (begpit != endpit)
622                         cur.updateFlags(Update::Force | Update::FitCursor);
623
624                 boost::tie(endpit, endpos) =
625                         eraseSelectionHelper(bp,
626                                 text->paragraphs(),
627                                 begpit, endpit,
628                                 cur.selBegin().pos(), endpos);
629
630                 // cutSelection can invalidate the cursor so we need to set
631                 // it anew. (Lgb)
632                 // we prefer the end for when tracking changes
633                 cur.pos() = endpos;
634                 cur.pit() = endpit;
635
636                 // sometimes necessary
637                 if (doclear
638                         && text->paragraphs()[begpit].stripLeadingSpaces(bp.trackChanges))
639                         cur.fixIfBroken();
640
641                 // need a valid cursor. (Lgb)
642                 cur.clearSelection();
643                 updateLabels(cur.buffer());
644
645                 // tell tabular that a recent copy happened
646                 dirtyTabularStack(false);
647         }
648
649         if (cur.inMathed()) {
650                 if (cur.selBegin().idx() != cur.selEnd().idx()) {
651                         // The current selection spans more than one cell.
652                         // Record all cells
653                         cur.recordUndoInset();
654                 } else {
655                         // Record only the current cell to avoid a jumping
656                         // cursor after undo
657                         cur.recordUndo();
658                 }
659                 if (realcut)
660                         copySelection(cur);
661                 eraseSelection(cur);
662         }
663 }
664
665
666 void copySelection(Cursor & cur)
667 {
668         copySelection(cur, cur.selectionAsString(true));
669 }
670
671
672 namespace {
673
674 void copySelectionToStack(Cursor & cur, CutStack & cutstack)
675 {
676         // this doesn't make sense, if there is no selection
677         if (!cur.selection())
678                 return;
679
680         // copySelection can not yet handle the case of cross idx selection
681         if (cur.selBegin().idx() != cur.selEnd().idx())
682                 return;
683
684         if (cur.inTexted()) {
685                 Text * text = cur.text();
686                 LASSERT(text, /**/);
687                 // ok we have a selection. This is always between cur.selBegin()
688                 // and sel_end cursor
689
690                 // copy behind a space if there is one
691                 ParagraphList & pars = text->paragraphs();
692                 pos_type pos = cur.selBegin().pos();
693                 pit_type par = cur.selBegin().pit();
694                 while (pos < pars[par].size() &&
695                        pars[par].isLineSeparator(pos) &&
696                        (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
697                         ++pos;
698
699                 copySelectionHelper(cur.buffer(), pars, par, cur.selEnd().pit(),
700                         pos, cur.selEnd().pos(), 
701                         cur.buffer().params().documentClassPtr(), cutstack);
702                 dirtyTabularStack(false);
703         }
704
705         if (cur.inMathed()) {
706                 //lyxerr << "copySelection in mathed" << endl;
707                 ParagraphList pars;
708                 Paragraph par;
709                 BufferParams const & bp = cur.buffer().params();
710                 // FIXME This should be the empty layout...right?
711                 par.setLayout(bp.documentClass().emptyLayout());
712                 par.insert(0, grabSelection(cur), Font(), Change(Change::UNCHANGED));
713                 pars.push_back(par);
714                 cutstack.push(make_pair(pars, bp.documentClassPtr()));
715         }
716 }
717
718 }
719
720
721 void copySelectionToStack()
722 {
723         if (!selectionBuffer.empty())
724                 theCuts.push(selectionBuffer[0]);
725 }
726
727
728 void copySelection(Cursor & cur, docstring const & plaintext)
729 {
730         // In tablemode, because copy and paste actually use special table stack
731         // we do not attempt to get selected paragraphs under cursor. Instead, a
732         // paragraph with the plain text version is generated so that table cells
733         // can be pasted as pure text somewhere else.
734         if (cur.selBegin().idx() != cur.selEnd().idx()) {
735                 ParagraphList pars;
736                 Paragraph par;
737                 BufferParams const & bp = cur.buffer().params();
738                 par.setLayout(bp.documentClass().emptyLayout());
739                 par.insert(0, plaintext, Font(), Change(Change::UNCHANGED));
740                 pars.push_back(par);
741                 theCuts.push(make_pair(pars, bp.documentClassPtr()));
742         } else {
743                 copySelectionToStack(cur, theCuts);
744         }
745
746         // stuff the selection onto the X clipboard, from an explicit copy request
747         putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
748 }
749
750
751 void saveSelection(Cursor & cur)
752 {
753         // This function is called, not when a selection is formed, but when
754         // a selection is cleared. Therefore, multiple keyboard selection
755         // will not repeatively trigger this function (bug 3877).
756         if (cur.selection() 
757             && cur.selBegin() == cur.bv().cursor().selBegin()
758             && cur.selEnd() == cur.bv().cursor().selEnd()) {
759                 LYXERR(Debug::ACTION, "'" << cur.selectionAsString(true) << "'");
760                 copySelectionToStack(cur, selectionBuffer);
761         }
762 }
763
764
765 bool selection()
766 {
767         return !selectionBuffer.empty();
768 }
769
770
771 void clearSelection()
772 {
773         selectionBuffer.clear();
774 }
775
776
777 void clearCutStack()
778 {
779         theCuts.clear();
780 }
781
782
783 docstring selection(size_t sel_index)
784 {
785         return sel_index < theCuts.size()
786                 ? theCuts[sel_index].first.back().asString(AS_STR_INSETS)
787                 : docstring();
788 }
789
790
791 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
792                         DocumentClass const * const docclass, ErrorList & errorList)
793 {
794         if (cur.inTexted()) {
795                 Text * text = cur.text();
796                 LASSERT(text, /**/);
797
798                 pit_type endpit;
799                 PitPosPair ppp;
800
801                 boost::tie(ppp, endpit) =
802                         pasteSelectionHelper(cur, parlist, docclass, errorList);
803                 updateLabels(cur.buffer());
804                 cur.clearSelection();
805                 text->setCursor(cur, ppp.first, ppp.second);
806         }
807
808         // mathed is handled in InsetMathNest/InsetMathGrid
809         LASSERT(!cur.inMathed(), /**/);
810 }
811
812
813 void pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
814 {
815         // this does not make sense, if there is nothing to paste
816         if (!checkPastePossible(sel_index))
817                 return;
818
819         cur.recordUndo();
820         pasteParagraphList(cur, theCuts[sel_index].first,
821                            theCuts[sel_index].second, errorList);
822         cur.setSelection();
823 }
824
825
826 void pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs)
827 {
828         // Use internal clipboard if it is the most recent one
829         if (theClipboard().isInternal()) {
830                 pasteFromStack(cur, errorList, 0);
831                 return;
832         }
833
834         // First try LyX format
835         if (theClipboard().hasLyXContents()) {
836                 string lyx = theClipboard().getAsLyX();
837                 if (!lyx.empty()) {
838                         // For some strange reason gcc 3.2 and 3.3 do not accept
839                         // Buffer buffer(string(), false);
840                         Buffer buffer("", false);
841                         buffer.setUnnamed(true);
842                         if (buffer.readString(lyx)) {
843                                 cur.recordUndo();
844                                 pasteParagraphList(cur, buffer.paragraphs(),
845                                         buffer.params().documentClassPtr(), errorList);
846                                 cur.setSelection();
847                                 return;
848                         }
849                 }
850         }
851
852         // Then try plain text
853         docstring const text = theClipboard().getAsText();
854         if (text.empty())
855                 return;
856         cur.recordUndo();
857         if (asParagraphs)
858                 cur.text()->insertStringAsParagraphs(cur, text);
859         else
860                 cur.text()->insertStringAsLines(cur, text);
861 }
862
863
864 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
865                             Clipboard::GraphicsType preferedType)
866 {
867         LASSERT(theClipboard().hasGraphicsContents(preferedType), /**/);
868
869         // get picture from clipboard
870         FileName filename = theClipboard().getAsGraphics(cur, preferedType);
871         if (filename.empty())
872                 return;
873
874         // create inset for graphic
875         InsetGraphics * inset = new InsetGraphics(cur.buffer());
876         InsetGraphicsParams params;
877         params.filename = support::DocFileName(filename.absFilename());
878         inset->setParams(params);
879         cur.recordUndo();
880         cur.insert(inset);
881 }
882
883
884 void pasteSelection(Cursor & cur, ErrorList & errorList)
885 {
886         if (selectionBuffer.empty())
887                 return;
888         cur.recordUndo();
889         pasteParagraphList(cur, selectionBuffer[0].first,
890                            selectionBuffer[0].second, errorList);
891 }
892
893
894 void replaceSelectionWithString(Cursor & cur, docstring const & str, bool backwards)
895 {
896         cur.recordUndo();
897         DocIterator selbeg = cur.selectionBegin();
898
899         // Get font setting before we cut
900         Font const font =
901                 selbeg.paragraph().getFontSettings(cur.buffer().params(), selbeg.pos());
902
903         // Insert the new string
904         pos_type pos = cur.selEnd().pos();
905         Paragraph & par = cur.selEnd().paragraph();
906         docstring::const_iterator cit = str.begin();
907         docstring::const_iterator end = str.end();
908         for (; cit != end; ++cit, ++pos)
909                 par.insertChar(pos, *cit, font, cur.buffer().params().trackChanges);
910
911         // Cut the selection
912         cutSelection(cur, true, false);
913
914         // select the replacement
915         if (backwards) {
916                 selbeg.pos() += str.length();
917                 cur.setSelection(selbeg, -int(str.length()));
918         } else
919                 cur.setSelection(selbeg, str.length());
920 }
921
922
923 void replaceSelection(Cursor & cur)
924 {
925         if (cur.selection())
926                 cutSelection(cur, true, false);
927 }
928
929
930 void eraseSelection(Cursor & cur)
931 {
932         //lyxerr << "cap::eraseSelection begin: " << cur << endl;
933         CursorSlice const & i1 = cur.selBegin();
934         CursorSlice const & i2 = cur.selEnd();
935         if (i1.inset().asInsetMath()) {
936                 saveSelection(cur);
937                 cur.top() = i1;
938                 if (i1.idx() == i2.idx()) {
939                         i1.cell().erase(i1.pos(), i2.pos());
940                         // We may have deleted i1.cell(cur.pos()).
941                         // Make sure that pos is valid.
942                         if (cur.pos() > cur.lastpos())
943                                 cur.pos() = cur.lastpos();
944                 } else {
945                         InsetMath * p = i1.asInsetMath();
946                         Inset::row_type r1, r2;
947                         Inset::col_type c1, c2;
948                         region(i1, i2, r1, r2, c1, c2);
949                         for (Inset::row_type row = r1; row <= r2; ++row)
950                                 for (Inset::col_type col = c1; col <= c2; ++col)
951                                         p->cell(p->index(row, col)).clear();
952                         // We've deleted the whole cell. Only pos 0 is valid.
953                         cur.pos() = 0;
954                 }
955                 // need a valid cursor. (Lgb)
956                 cur.clearSelection();
957         } else {
958                 lyxerr << "can't erase this selection 1" << endl;
959         }
960         //lyxerr << "cap::eraseSelection end: " << cur << endl;
961 }
962
963
964 void selDel(Cursor & cur)
965 {
966         //lyxerr << "cap::selDel" << endl;
967         if (cur.selection())
968                 eraseSelection(cur);
969 }
970
971
972 void selClearOrDel(Cursor & cur)
973 {
974         //lyxerr << "cap::selClearOrDel" << endl;
975         if (lyxrc.auto_region_delete)
976                 selDel(cur);
977         else
978                 cur.selection() = false;
979 }
980
981
982 docstring grabSelection(Cursor const & cur)
983 {
984         if (!cur.selection())
985                 return docstring();
986
987 #if 0
988         // grab selection by glueing multiple cells together. This is not what
989         // we want because selections spanning multiple cells will get "&" and "\\"
990         // seperators.
991         ostringstream os;
992         for (DocIterator dit = cur.selectionBegin();
993              dit != cur.selectionEnd(); dit.forwardPos())
994                 os << asString(dit.cell());
995         return os.str();
996 #endif
997
998         CursorSlice i1 = cur.selBegin();
999         CursorSlice i2 = cur.selEnd();
1000
1001         if (i1.idx() == i2.idx()) {
1002                 if (i1.inset().asInsetMath()) {
1003                         MathData::const_iterator it = i1.cell().begin();
1004                         return asString(MathData(it + i1.pos(), it + i2.pos()));
1005                 } else {
1006                         return from_ascii("unknown selection 1");
1007                 }
1008         }
1009
1010         Inset::row_type r1, r2;
1011         Inset::col_type c1, c2;
1012         region(i1, i2, r1, r2, c1, c2);
1013
1014         docstring data;
1015         if (i1.inset().asInsetMath()) {
1016                 for (Inset::row_type row = r1; row <= r2; ++row) {
1017                         if (row > r1)
1018                                 data += "\\\\";
1019                         for (Inset::col_type col = c1; col <= c2; ++col) {
1020                                 if (col > c1)
1021                                         data += '&';
1022                                 data += asString(i1.asInsetMath()->
1023                                         cell(i1.asInsetMath()->index(row, col)));
1024                         }
1025                 }
1026         } else {
1027                 data = from_ascii("unknown selection 2");
1028         }
1029         return data;
1030 }
1031
1032
1033 void dirtyTabularStack(bool b)
1034 {
1035         dirty_tabular_stack_ = b;
1036 }
1037
1038
1039 bool tabularStackDirty()
1040 {
1041         return dirty_tabular_stack_;
1042 }
1043
1044
1045 } // namespace cap
1046
1047 } // namespace lyx