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