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