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