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