]> git.lyx.org Git - lyx.git/blob - src/CutAndPaste.cpp
VCS: Handle one boundary condition.
[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 empty layout if necessary
134         if (cur.inset().usePlainLayout()) {
135                 bool forcePlainLayout = cur.inset().forcePlainLayout();
136                 Layout const & emptyLayout = newDocClass->emptyLayout();
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(emptyLayout);
144                 }
145         } else { // check if we need to reset from empty layout
146                 Layout const & defaultLayout = newDocClass->defaultLayout();
147                 Layout const & emptyLayout = newDocClass->emptyLayout();
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 == emptyLayout)
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 & 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.emptyLayout());
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()
559 {
560         vector<docstring> selList;
561
562         CutStack::const_iterator cit = theCuts.begin();
563         CutStack::const_iterator end = theCuts.end();
564         for (; cit != end; ++cit) {
565                 // we do not use cit-> here because gcc 2.9x does not
566                 // like it (JMarc)
567                 ParagraphList const & pars = (*cit).first;
568                 docstring asciiSel;
569                 ParagraphList::const_iterator pit = pars.begin();
570                 ParagraphList::const_iterator pend = pars.end();
571                 for (; pit != pend; ++pit) {
572                         asciiSel += pit->asString(AS_STR_INSETS);
573                         if (asciiSel.size() > 25) {
574                                 asciiSel.replace(22, docstring::npos,
575                                                  from_ascii("..."));
576                                 break;
577                         }
578                 }
579
580                 selList.push_back(asciiSel);
581         }
582
583         return selList;
584 }
585
586
587 size_type numberOfSelections()
588 {
589         return theCuts.size();
590 }
591
592
593 void cutSelection(Cursor & cur, bool doclear, bool realcut)
594 {
595         // This doesn't make sense, if there is no selection
596         if (!cur.selection())
597                 return;
598
599         // OK, we have a selection. This is always between cur.selBegin()
600         // and cur.selEnd()
601
602         if (cur.inTexted()) {
603                 Text * text = cur.text();
604                 LASSERT(text, /**/);
605
606                 saveSelection(cur);
607
608                 // make sure that the depth behind the selection are restored, too
609                 cur.recordUndoSelection();
610                 pit_type begpit = cur.selBegin().pit();
611                 pit_type endpit = cur.selEnd().pit();
612
613                 int endpos = cur.selEnd().pos();
614
615                 BufferParams const & bp = cur.buffer().params();
616                 if (realcut) {
617                         copySelectionHelper(cur.buffer(),
618                                 text->paragraphs(),
619                                 begpit, endpit,
620                                 cur.selBegin().pos(), endpos,
621                                 bp.documentClassPtr(), theCuts);
622                         // Stuff what we got on the clipboard.
623                         // Even if there is no selection.
624                         putClipboard(theCuts[0].first, theCuts[0].second,
625                                 cur.selectionAsString(true));
626                 }
627
628                 if (begpit != endpit)
629                         cur.updateFlags(Update::Force | Update::FitCursor);
630
631                 boost::tie(endpit, endpos) =
632                         eraseSelectionHelper(bp,
633                                 text->paragraphs(),
634                                 begpit, endpit,
635                                 cur.selBegin().pos(), endpos);
636
637                 // cutSelection can invalidate the cursor so we need to set
638                 // it anew. (Lgb)
639                 // we prefer the end for when tracking changes
640                 cur.pos() = endpos;
641                 cur.pit() = endpit;
642
643                 // sometimes necessary
644                 if (doclear
645                         && text->paragraphs()[begpit].stripLeadingSpaces(bp.trackChanges))
646                         cur.fixIfBroken();
647
648                 // need a valid cursor. (Lgb)
649                 cur.clearSelection();
650                 updateLabels(cur.buffer());
651
652                 // tell tabular that a recent copy happened
653                 dirtyTabularStack(false);
654         }
655
656         if (cur.inMathed()) {
657                 if (cur.selBegin().idx() != cur.selEnd().idx()) {
658                         // The current selection spans more than one cell.
659                         // Record all cells
660                         cur.recordUndoInset();
661                 } else {
662                         // Record only the current cell to avoid a jumping
663                         // cursor after undo
664                         cur.recordUndo();
665                 }
666                 if (realcut)
667                         copySelection(cur);
668                 eraseSelection(cur);
669         }
670 }
671
672
673 void copySelection(Cursor & cur)
674 {
675         copySelection(cur, cur.selectionAsString(true));
676 }
677
678
679 namespace {
680
681 void copySelectionToStack(Cursor & cur, CutStack & cutstack)
682 {
683         // this doesn't make sense, if there is no selection
684         if (!cur.selection())
685                 return;
686
687         // copySelection can not yet handle the case of cross idx selection
688         if (cur.selBegin().idx() != cur.selEnd().idx())
689                 return;
690
691         if (cur.inTexted()) {
692                 Text * text = cur.text();
693                 LASSERT(text, /**/);
694                 // ok we have a selection. This is always between cur.selBegin()
695                 // and sel_end cursor
696
697                 // copy behind a space if there is one
698                 ParagraphList & pars = text->paragraphs();
699                 pos_type pos = cur.selBegin().pos();
700                 pit_type par = cur.selBegin().pit();
701                 while (pos < pars[par].size() &&
702                        pars[par].isLineSeparator(pos) &&
703                        (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
704                         ++pos;
705
706                 copySelectionHelper(cur.buffer(), pars, par, cur.selEnd().pit(),
707                         pos, cur.selEnd().pos(), 
708                         cur.buffer().params().documentClassPtr(), cutstack);
709                 dirtyTabularStack(false);
710         }
711
712         if (cur.inMathed()) {
713                 //lyxerr << "copySelection in mathed" << endl;
714                 ParagraphList pars;
715                 Paragraph par;
716                 BufferParams const & bp = cur.buffer().params();
717                 // FIXME This should be the empty layout...right?
718                 par.setLayout(bp.documentClass().emptyLayout());
719                 par.insert(0, grabSelection(cur), Font(), Change(Change::UNCHANGED));
720                 pars.push_back(par);
721                 cutstack.push(make_pair(pars, bp.documentClassPtr()));
722         }
723 }
724
725 }
726
727
728 void copySelectionToStack()
729 {
730         if (!selectionBuffer.empty())
731                 theCuts.push(selectionBuffer[0]);
732 }
733
734
735 void copySelection(Cursor & cur, docstring const & plaintext)
736 {
737         // In tablemode, because copy and paste actually use special table stack
738         // we do not attempt to get selected paragraphs under cursor. Instead, a
739         // paragraph with the plain text version is generated so that table cells
740         // can be pasted as pure text somewhere else.
741         if (cur.selBegin().idx() != cur.selEnd().idx()) {
742                 ParagraphList pars;
743                 Paragraph par;
744                 BufferParams const & bp = cur.buffer().params();
745                 par.setLayout(bp.documentClass().emptyLayout());
746                 par.insert(0, plaintext, Font(), Change(Change::UNCHANGED));
747                 pars.push_back(par);
748                 theCuts.push(make_pair(pars, bp.documentClassPtr()));
749         } else {
750                 copySelectionToStack(cur, theCuts);
751         }
752
753         // stuff the selection onto the X clipboard, from an explicit copy request
754         putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
755 }
756
757
758 void saveSelection(Cursor & cur)
759 {
760         // This function is called, not when a selection is formed, but when
761         // a selection is cleared. Therefore, multiple keyboard selection
762         // will not repeatively trigger this function (bug 3877).
763         if (cur.selection() 
764             && cur.selBegin() == cur.bv().cursor().selBegin()
765             && cur.selEnd() == cur.bv().cursor().selEnd()) {
766                 LYXERR(Debug::SELECTION, "saveSelection: '" << cur.selectionAsString(true) << "'");
767                 copySelectionToStack(cur, selectionBuffer);
768         }
769 }
770
771
772 bool selection()
773 {
774         return !selectionBuffer.empty();
775 }
776
777
778 void clearSelection()
779 {
780         selectionBuffer.clear();
781 }
782
783
784 void clearCutStack()
785 {
786         theCuts.clear();
787 }
788
789
790 docstring selection(size_t sel_index)
791 {
792         return sel_index < theCuts.size()
793                 ? theCuts[sel_index].first.back().asString(AS_STR_INSETS)
794                 : docstring();
795 }
796
797
798 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
799                         DocumentClass const * const docclass, ErrorList & errorList)
800 {
801         if (cur.inTexted()) {
802                 Text * text = cur.text();
803                 LASSERT(text, /**/);
804
805                 pit_type endpit;
806                 PitPosPair ppp;
807
808                 boost::tie(ppp, endpit) =
809                         pasteSelectionHelper(cur, parlist, docclass, errorList);
810                 updateLabels(cur.buffer());
811                 cur.clearSelection();
812                 text->setCursor(cur, ppp.first, ppp.second);
813         }
814
815         // mathed is handled in InsetMathNest/InsetMathGrid
816         LASSERT(!cur.inMathed(), /**/);
817 }
818
819
820 void pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
821 {
822         // this does not make sense, if there is nothing to paste
823         if (!checkPastePossible(sel_index))
824                 return;
825
826         cur.recordUndo();
827         pasteParagraphList(cur, theCuts[sel_index].first,
828                            theCuts[sel_index].second, errorList);
829         cur.setSelection();
830 }
831
832
833 void pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs)
834 {
835         // Use internal clipboard if it is the most recent one
836         if (theClipboard().isInternal()) {
837                 pasteFromStack(cur, errorList, 0);
838                 return;
839         }
840
841         // First try LyX format
842         if (theClipboard().hasLyXContents()) {
843                 string lyx = theClipboard().getAsLyX();
844                 if (!lyx.empty()) {
845                         // For some strange reason gcc 3.2 and 3.3 do not accept
846                         // Buffer buffer(string(), false);
847                         Buffer buffer("", false);
848                         buffer.setUnnamed(true);
849                         if (buffer.readString(lyx)) {
850                                 cur.recordUndo();
851                                 pasteParagraphList(cur, buffer.paragraphs(),
852                                         buffer.params().documentClassPtr(), errorList);
853                                 cur.setSelection();
854                                 return;
855                         }
856                 }
857         }
858
859         // Then try plain text
860         docstring const text = theClipboard().getAsText();
861         if (text.empty())
862                 return;
863         cur.recordUndo();
864         if (asParagraphs)
865                 cur.text()->insertStringAsParagraphs(cur, text);
866         else
867                 cur.text()->insertStringAsLines(cur, text);
868 }
869
870
871 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
872                             Clipboard::GraphicsType preferedType)
873 {
874         LASSERT(theClipboard().hasGraphicsContents(preferedType), /**/);
875
876         // get picture from clipboard
877         FileName filename = theClipboard().getAsGraphics(cur, preferedType);
878         if (filename.empty())
879                 return;
880
881         // create inset for graphic
882         InsetGraphics * inset = new InsetGraphics(cur.buffer());
883         InsetGraphicsParams params;
884         params.filename = support::DocFileName(filename.absFilename());
885         inset->setParams(params);
886         cur.recordUndo();
887         cur.insert(inset);
888 }
889
890
891 void pasteSelection(Cursor & cur, ErrorList & errorList)
892 {
893         if (selectionBuffer.empty())
894                 return;
895         cur.recordUndo();
896         pasteParagraphList(cur, selectionBuffer[0].first,
897                            selectionBuffer[0].second, errorList);
898 }
899
900
901 void replaceSelectionWithString(Cursor & cur, docstring const & str, bool backwards)
902 {
903         cur.recordUndo();
904         DocIterator selbeg = cur.selectionBegin();
905
906         // Get font setting before we cut
907         Font const font =
908                 selbeg.paragraph().getFontSettings(cur.buffer().params(), selbeg.pos());
909
910         // Insert the new string
911         pos_type pos = cur.selEnd().pos();
912         Paragraph & par = cur.selEnd().paragraph();
913         docstring::const_iterator cit = str.begin();
914         docstring::const_iterator end = str.end();
915         for (; cit != end; ++cit, ++pos)
916                 par.insertChar(pos, *cit, font, cur.buffer().params().trackChanges);
917
918         // Cut the selection
919         cutSelection(cur, true, false);
920
921         // select the replacement
922         if (backwards) {
923                 selbeg.pos() += str.length();
924                 cur.setSelection(selbeg, -int(str.length()));
925         } else
926                 cur.setSelection(selbeg, str.length());
927 }
928
929
930 void replaceSelection(Cursor & cur)
931 {
932         if (cur.selection())
933                 cutSelection(cur, true, false);
934 }
935
936
937 void eraseSelection(Cursor & cur)
938 {
939         //lyxerr << "cap::eraseSelection begin: " << cur << endl;
940         CursorSlice const & i1 = cur.selBegin();
941         CursorSlice const & i2 = cur.selEnd();
942         if (i1.inset().asInsetMath()) {
943                 saveSelection(cur);
944                 cur.top() = i1;
945                 if (i1.idx() == i2.idx()) {
946                         i1.cell().erase(i1.pos(), i2.pos());
947                         // We may have deleted i1.cell(cur.pos()).
948                         // Make sure that pos is valid.
949                         if (cur.pos() > cur.lastpos())
950                                 cur.pos() = cur.lastpos();
951                 } else {
952                         InsetMath * p = i1.asInsetMath();
953                         Inset::row_type r1, r2;
954                         Inset::col_type c1, c2;
955                         region(i1, i2, r1, r2, c1, c2);
956                         for (Inset::row_type row = r1; row <= r2; ++row)
957                                 for (Inset::col_type col = c1; col <= c2; ++col)
958                                         p->cell(p->index(row, col)).clear();
959                         // We've deleted the whole cell. Only pos 0 is valid.
960                         cur.pos() = 0;
961                 }
962                 // need a valid cursor. (Lgb)
963                 cur.clearSelection();
964         } else {
965                 lyxerr << "can't erase this selection 1" << endl;
966         }
967         //lyxerr << "cap::eraseSelection end: " << cur << endl;
968 }
969
970
971 void selDel(Cursor & cur)
972 {
973         //lyxerr << "cap::selDel" << endl;
974         if (cur.selection())
975                 eraseSelection(cur);
976 }
977
978
979 void selClearOrDel(Cursor & cur)
980 {
981         //lyxerr << "cap::selClearOrDel" << endl;
982         if (lyxrc.auto_region_delete)
983                 selDel(cur);
984         else
985                 cur.selection() = false;
986 }
987
988
989 docstring grabSelection(Cursor const & cur)
990 {
991         if (!cur.selection())
992                 return docstring();
993
994 #if 0
995         // grab selection by glueing multiple cells together. This is not what
996         // we want because selections spanning multiple cells will get "&" and "\\"
997         // seperators.
998         ostringstream os;
999         for (DocIterator dit = cur.selectionBegin();
1000              dit != cur.selectionEnd(); dit.forwardPos())
1001                 os << asString(dit.cell());
1002         return os.str();
1003 #endif
1004
1005         CursorSlice i1 = cur.selBegin();
1006         CursorSlice i2 = cur.selEnd();
1007
1008         if (i1.idx() == i2.idx()) {
1009                 if (i1.inset().asInsetMath()) {
1010                         MathData::const_iterator it = i1.cell().begin();
1011                         return asString(MathData(it + i1.pos(), it + i2.pos()));
1012                 } else {
1013                         return from_ascii("unknown selection 1");
1014                 }
1015         }
1016
1017         Inset::row_type r1, r2;
1018         Inset::col_type c1, c2;
1019         region(i1, i2, r1, r2, c1, c2);
1020
1021         docstring data;
1022         if (i1.inset().asInsetMath()) {
1023                 for (Inset::row_type row = r1; row <= r2; ++row) {
1024                         if (row > r1)
1025                                 data += "\\\\";
1026                         for (Inset::col_type col = c1; col <= c2; ++col) {
1027                                 if (col > c1)
1028                                         data += '&';
1029                                 data += asString(i1.asInsetMath()->
1030                                         cell(i1.asInsetMath()->index(row, col)));
1031                         }
1032                 }
1033         } else {
1034                 data = from_ascii("unknown selection 2");
1035         }
1036         return data;
1037 }
1038
1039
1040 void dirtyTabularStack(bool b)
1041 {
1042         dirty_tabular_stack_ = b;
1043 }
1044
1045
1046 bool tabularStackDirty()
1047 {
1048         return dirty_tabular_stack_;
1049 }
1050
1051
1052 } // namespace cap
1053
1054 } // namespace lyx