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