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