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