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