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