]> git.lyx.org Git - lyx.git/blob - src/CutAndPaste.cpp
Fixed some lines that were too long. It compiled afterwards.
[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 "Cursor.h"
23 #include "debug.h"
24 #include "ErrorList.h"
25 #include "FuncRequest.h"
26 #include "gettext.h"
27 #include "InsetIterator.h"
28 #include "Language.h"
29 #include "lfuns.h"
30 #include "LyXFunc.h"
31 #include "LyXRC.h"
32 #include "Text.h"
33 #include "TextClassList.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/InsetCharStyle.h"
41 #include "insets/InsetTabular.h"
42
43 #include "mathed/MathData.h"
44 #include "mathed/InsetMath.h"
45 #include "mathed/MathSupport.h"
46
47 #include "support/lstrings.h"
48
49 #include "frontends/Clipboard.h"
50 #include "frontends/Selection.h"
51
52 #include <boost/current_function.hpp>
53 #include <boost/tuple/tuple.hpp>
54
55 #include <string>
56
57 using std::endl;
58 using std::for_each;
59 using std::make_pair;
60 using std::pair;
61 using std::vector;
62 using std::string;
63
64
65 namespace lyx {
66
67 using support::bformat;
68 using frontend::Clipboard;
69
70 namespace {
71
72 typedef std::pair<pit_type, int> PitPosPair;
73
74 typedef limited_stack<pair<ParagraphList, textclass_type> > 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 void region(CursorSlice const & i1, CursorSlice const & i2,
87         Inset::row_type & r1, Inset::row_type & r2,
88         Inset::col_type & c1, Inset::col_type & c2)
89 {
90         Inset & p = i1.inset();
91         c1 = p.col(i1.idx());
92         c2 = p.col(i2.idx());
93         if (c1 > c2)
94                 std::swap(c1, c2);
95         r1 = p.row(i1.idx());
96         r2 = p.row(i2.idx());
97         if (r1 > r2)
98                 std::swap(r1, r2);
99 }
100
101
102 bool checkPastePossible(int index)
103 {
104         return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
105 }
106
107
108 pair<PitPosPair, pit_type>
109 pasteSelectionHelper(Cursor & cur, ParagraphList const & parlist,
110                      textclass_type textclass, ErrorList & errorlist)
111 {
112         Buffer const & buffer = cur.buffer();
113         pit_type pit = cur.pit();
114         pos_type pos = cur.pos();
115         ParagraphList & pars = cur.text()->paragraphs();
116
117         if (parlist.empty())
118                 return make_pair(PitPosPair(pit, pos), pit);
119
120         BOOST_ASSERT (pos <= pars[pit].size());
121
122         // Make a copy of the CaP paragraphs.
123         ParagraphList insertion = parlist;
124         textclass_type const tc = buffer.params().textclass;
125
126         // Now remove all out of the pars which is NOT allowed in the
127         // new environment and set also another font if that is required.
128
129         // Convert newline to paragraph break in ERT inset.
130         // This should not be here!
131         if (pars[pit].inInset() &&
132             (pars[pit].inInset()->lyxCode() == Inset::ERT_CODE ||
133                 pars[pit].inInset()->lyxCode() == Inset::LISTINGS_CODE)) {
134                 for (ParagraphList::size_type i = 0; i < insertion.size(); ++i) {
135                         for (pos_type j = 0; j < insertion[i].size(); ++j) {
136                                 if (insertion[i].isNewline(j)) {
137                                         // do not track deletion of newline
138                                         insertion[i].eraseChar(j, false);
139                                         breakParagraphConservative(
140                                                         buffer.params(),
141                                                         insertion, i, j);
142                                 }
143                         }
144                 }
145         }
146
147         // If we are in an inset which returns forceDefaultParagraphs,
148         // set the paragraphs to default
149         if (cur.inset().forceDefaultParagraphs(cur.idx())) {
150                 Layout_ptr const layout =
151                         buffer.params().getTextClass().defaultLayout();
152                 ParagraphList::iterator const end = insertion.end();
153                 for (ParagraphList::iterator par = insertion.begin();
154                                 par != end; ++par)
155                         par->layout(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(textclass, 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                         if (tmpbuf->getChar(i) == Paragraph::META_INSET &&
196                             !pars[pit].insetAllowed(tmpbuf->getInset(i)->lyxCode()))
197                                 // do not track deletion of invalid insets
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         ParIterator fpit = par_iterator_begin(in);
217         ParIterator fend = par_iterator_end(in);
218
219         for (; fpit != fend; ++fpit) {
220                 InsetList::const_iterator lit = fpit->insetlist.begin();
221                 InsetList::const_iterator eit = fpit->insetlist.end();
222
223                 for (; lit != eit; ++lit) {
224                         switch (lit->inset->lyxCode()) {
225                         case Inset::TABULAR_CODE: {
226                                 InsetTabular * it = static_cast<InsetTabular*>(lit->inset);
227                                 it->buffer(&buffer);
228                                 break;
229                         }
230
231                         default:
232                                 break; // nothing
233                         }
234                 }
235         }
236         insertion.swap(in.paragraphs());
237
238         // Split the paragraph for inserting the buf if necessary.
239         if (!empty)
240                 breakParagraphConservative(buffer.params(), pars, pit, pos);
241
242         // Paste it!
243         if (empty) {
244                 pars.insert(boost::next(pars.begin(), pit),
245                             insertion.begin(),
246                             insertion.end());
247
248                 // merge the empty par with the last par of the insertion
249                 mergeParagraph(buffer.params(), pars,
250                                pit + insertion.size() - 1);
251         } else {
252                 pars.insert(boost::next(pars.begin(), pit + 1),
253                             insertion.begin(),
254                             insertion.end());
255
256                 // merge the first par of the insertion with the current par
257                 mergeParagraph(buffer.params(), pars, pit);
258         }
259
260         pit_type last_paste = pit + insertion.size() - 1;
261
262         // Store the new cursor position.
263         pit = last_paste;
264         pos = pars[last_paste].size();
265
266         // Join (conditionally) last pasted paragraph with next one, i.e.,
267         // the tail of the spliced document paragraph
268         if (!empty && last_paste + 1 != pit_type(pars.size())) {
269                 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
270                         mergeParagraph(buffer.params(), pars, last_paste);
271                 } else if (pars[last_paste + 1].empty()) {
272                         pars[last_paste + 1].makeSameLayout(pars[last_paste]);
273                         mergeParagraph(buffer.params(), pars, last_paste);
274                 } else if (pars[last_paste].empty()) {
275                         pars[last_paste].makeSameLayout(pars[last_paste + 1]);
276                         mergeParagraph(buffer.params(), pars, last_paste);
277                 } else {
278                         pars[last_paste + 1].stripLeadingSpaces(buffer.params().trackChanges);
279                         ++last_paste;
280                 }
281         }
282
283         return make_pair(PitPosPair(pit, pos), last_paste + 1);
284 }
285
286
287 PitPosPair eraseSelectionHelper(BufferParams const & params,
288         ParagraphList & pars,
289         pit_type startpit, pit_type endpit,
290         int startpos, int endpos, bool doclear)
291 {
292         // Start of selection is really invalid.
293         if (startpit == pit_type(pars.size()) ||
294             (startpos > pars[startpit].size()))
295                 return PitPosPair(endpit, endpos);
296
297         // Start and end is inside same paragraph
298         if (endpit == pit_type(pars.size()) || startpit == endpit) {
299                 endpos -= pars[startpit].eraseChars(startpos, endpos, params.trackChanges);
300                 return PitPosPair(endpit, endpos);
301         }
302
303         for (pit_type pit = startpit; pit != endpit + 1;) {
304                 pos_type const left  = (pit == startpit ? startpos : 0);
305                 pos_type right = (pit == endpit ? endpos : pars[pit].size() + 1);
306                 // FIXME: this is a quick fix for bug 3600. It stops a crash but the problem
307                 // still remains unsolved (e.g. the second example in the bug report).
308                 // c.f. http://bugzilla.lyx.org/show_bug.cgi?id=3600
309                 if (right > pars[pit].size() + 1)
310                         right = pars[pit].size() + 1;
311
312                 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.trackChanges);
313
314                 // Logically erase only, including the end-of-paragraph character
315                 pars[pit].eraseChars(left, right, params.trackChanges);
316
317                 // Separate handling of paragraph break:
318                 if (merge && pit != endpit &&
319                     (pit + 1 != endpit || pars[pit].hasSameLayout(pars[pit + 1]))) {
320                         pos_type const thissize = pars[pit].size();
321                         if (doclear)
322                                 pars[pit + 1].stripLeadingSpaces(params.trackChanges);
323                         mergeParagraph(params, pars, pit);
324                         --endpit;
325                         if (pit == endpit)
326                                 endpos += thissize;
327                 } else
328                         ++pit;
329         }
330
331         // Ensure legal cursor pos:
332         endpit = startpit;
333         endpos = startpos;
334         return PitPosPair(endpit, endpos);
335 }
336
337
338 void putClipboard(ParagraphList const & paragraphs, textclass_type textclass,
339                   docstring const & plaintext)
340 {
341         // For some strange reason gcc 3.2 and 3.3 do not accept
342         // Buffer buffer(string(), false);
343         Buffer buffer("", false);
344         buffer.setUnnamed(true);
345         buffer.paragraphs() = paragraphs;
346         buffer.params().textclass = textclass;
347         std::ostringstream lyx;
348         if (buffer.write(lyx))
349                 theClipboard().put(lyx.str(), plaintext);
350         else
351                 theClipboard().put(string(), plaintext);
352 }
353
354
355 void copySelectionHelper(Buffer const & buf, ParagraphList & pars,
356         pit_type startpit, pit_type endpit,
357         int start, int end, textclass_type tc, CutStack & cutstack)
358 {
359         BOOST_ASSERT(0 <= start && start <= pars[startpit].size());
360         BOOST_ASSERT(0 <= end && end <= pars[endpit].size());
361         BOOST_ASSERT(startpit != endpit || start <= end);
362
363         // Clone the paragraphs within the selection.
364         ParagraphList copy_pars(boost::next(pars.begin(), startpit),
365                                 boost::next(pars.begin(), endpit + 1));
366
367         // Remove the end of the last paragraph; afterwards, remove the
368         // beginning of the first paragraph. Keep this order - there may only
369         // be one paragraph!  Do not track deletions here; this is an internal
370         // action not visible to the user
371
372         Paragraph & back = copy_pars.back();
373         back.eraseChars(end, back.size(), false);
374         Paragraph & front = copy_pars.front();
375         front.eraseChars(0, start, false);
376
377         ParagraphList::iterator it = copy_pars.begin();
378         ParagraphList::iterator it_end = copy_pars.end();
379
380         for (; it != it_end; it++) {
381                 // ERT paragraphs have the Language latex_language.
382                 // This is invalid outside of ERT, so we need to change it
383                 // to the buffer language.
384                 if (it->ownerCode() == Inset::ERT_CODE || it->ownerCode() == Inset::LISTINGS_CODE) {
385                         it->changeLanguage(buf.params(), latex_language,
386                                            buf.getLanguage());
387                 }
388                 it->setInsetOwner(0);
389         }
390
391         // do not copy text (also nested in insets) which is marked as deleted
392         acceptChanges(copy_pars, buf.params());
393
394         cutstack.push(make_pair(copy_pars, tc));
395 }
396
397 } // namespace anon
398
399
400
401
402 namespace cap {
403
404 docstring grabAndEraseSelection(Cursor & cur)
405 {
406         if (!cur.selection())
407                 return docstring();
408         docstring res = grabSelection(cur);
409         eraseSelection(cur);
410         return res;
411 }
412
413
414 void switchBetweenClasses(textclass_type c1, textclass_type c2,
415         InsetText & in, ErrorList & errorlist)
416 {
417         errorlist.clear();
418
419         BOOST_ASSERT(!in.paragraphs().empty());
420         if (c1 == c2)
421                 return;
422
423         TextClass const & tclass1 = textclasslist[c1];
424         TextClass const & tclass2 = textclasslist[c2];
425
426         // layouts
427         ParIterator end = par_iterator_end(in);
428         for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
429                 docstring const name = it->layout()->name();
430                 bool hasLayout = tclass2.hasLayout(name);
431
432                 if (hasLayout)
433                         it->layout(tclass2[name]);
434                 else
435                         it->layout(tclass2.defaultLayout());
436
437                 if (!hasLayout && name != tclass1.defaultLayoutName()) {
438                         docstring const s = bformat(
439                                                  _("Layout had to be changed from\n%1$s to %2$s\n"
440                                                 "because of class conversion from\n%3$s to %4$s"),
441                          name, it->layout()->name(),
442                          from_utf8(tclass1.name()), from_utf8(tclass2.name()));
443                         // To warn the user that something had to be done.
444                         errorlist.push_back(ErrorItem(_("Changed Layout"), s,
445                                                       it->id(), 0,
446                                                       it->size()));
447                 }
448         }
449
450         // character styles
451         InsetIterator const i_end = inset_iterator_end(in);
452         for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
453                 if (it->lyxCode() == Inset::CHARSTYLE_CODE) {
454                         InsetCharStyle & inset =
455                                 static_cast<InsetCharStyle &>(*it);
456                         string const name = inset.params().type;
457                         CharStyles::iterator const found_cs =
458                                 tclass2.charstyle(name);
459                         if (found_cs == tclass2.charstyles().end()) {
460                                 // The character style is undefined in tclass2
461                                 inset.setUndefined();
462                                 docstring const s = bformat(_(
463                                         "Character style %1$s is "
464                                         "undefined because of class "
465                                         "conversion from\n%2$s to %3$s"),
466                                          from_utf8(name), from_utf8(tclass1.name()),
467                                          from_utf8(tclass2.name()));
468                                 // To warn the user that something had to be done.
469                                 errorlist.push_back(ErrorItem(
470                                         _("Undefined character style"),
471                                         s, it.paragraph().id(), it.pos(), it.pos() + 1));
472                         } else if (inset.undefined()) {
473                                 // The character style is undefined in
474                                 // tclass1 and is defined in tclass2
475                                 inset.setDefined(found_cs);
476                         }
477                 }
478         }
479 }
480
481
482 std::vector<docstring> const availableSelections(Buffer const & buffer)
483 {
484         vector<docstring> selList;
485
486         CutStack::const_iterator cit = theCuts.begin();
487         CutStack::const_iterator end = theCuts.end();
488         for (; cit != end; ++cit) {
489                 // we do not use cit-> here because gcc 2.9x does not
490                 // like it (JMarc)
491                 ParagraphList const & pars = (*cit).first;
492                 docstring asciiSel;
493                 ParagraphList::const_iterator pit = pars.begin();
494                 ParagraphList::const_iterator pend = pars.end();
495                 for (; pit != pend; ++pit) {
496                         asciiSel += pit->asString(buffer, false);
497                         if (asciiSel.size() > 25) {
498                                 asciiSel.replace(22, docstring::npos,
499                                                  from_ascii("..."));
500                                 break;
501                         }
502                 }
503
504                 selList.push_back(asciiSel);
505         }
506
507         return selList;
508 }
509
510
511 size_type numberOfSelections()
512 {
513         return theCuts.size();
514 }
515
516
517 void cutSelection(Cursor & cur, bool doclear, bool realcut)
518 {
519         // This doesn't make sense, if there is no selection
520         if (!cur.selection())
521                 return;
522
523         // OK, we have a selection. This is always between cur.selBegin()
524         // and cur.selEnd()
525
526         if (cur.inTexted()) {
527                 Text * text = cur.text();
528                 BOOST_ASSERT(text);
529
530                 saveSelection(cur);
531
532                 // make sure that the depth behind the selection are restored, too
533                 recordUndoSelection(cur);
534                 pit_type begpit = cur.selBegin().pit();
535                 pit_type endpit = cur.selEnd().pit();
536
537                 int endpos = cur.selEnd().pos();
538
539                 BufferParams const & bp = cur.buffer().params();
540                 if (realcut) {
541                         copySelectionHelper(cur.buffer(),
542                                 text->paragraphs(),
543                                 begpit, endpit,
544                                 cur.selBegin().pos(), endpos,
545                                 bp.textclass, theCuts);
546                         // Stuff what we got on the clipboard.
547                         // Even if there is no selection.
548                         putClipboard(theCuts[0].first, theCuts[0].second,
549                                 cur.selectionAsString(true));
550                 }
551
552                 boost::tie(endpit, endpos) =
553                         eraseSelectionHelper(bp,
554                                 text->paragraphs(),
555                                 begpit, endpit,
556                                 cur.selBegin().pos(), endpos,
557                                 doclear);
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                         recordUndoInset(cur);
583                 } else {
584                         // Record only the current cell to avoid a jumping
585                         // cursor after undo
586                         recordUndo(cur);
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(), cur.buffer().params().textclass, cutstack);
630                 dirtyTabularStack(false);
631         }
632
633         if (cur.inMathed()) {
634                 //lyxerr << "copySelection in mathed" << endl;
635                 ParagraphList pars;
636                 Paragraph par;
637                 BufferParams const & bp = cur.buffer().params();
638                 par.layout(bp.getTextClass().defaultLayout());
639                 par.insert(0, grabSelection(cur), Font(), Change(Change::UNCHANGED));
640                 pars.push_back(par);
641                 cutstack.push(make_pair(pars, bp.textclass));
642         }
643 }
644
645 }
646
647
648 void copySelectionToStack()
649 {
650         if (!selectionBuffer.empty())
651                 theCuts.push(selectionBuffer[0]);
652 }
653
654
655 void copySelection(Cursor & cur, docstring const & plaintext)
656 {
657         // In tablemode, because copy and paste actually use special table stack
658         // we do not attemp to get selected paragraphs under cursor. Instead, a
659         // paragraph with the plain text version is generated so that table cells
660         // can be pasted as pure text somewhere else.
661         if (cur.selBegin().idx() != cur.selEnd().idx()) {
662                 ParagraphList pars;
663                 Paragraph par;
664                 BufferParams const & bp = cur.buffer().params();
665                 par.layout(bp.getTextClass().defaultLayout());
666                 par.insert(0, plaintext, Font(), Change(Change::UNCHANGED));
667                 pars.push_back(par);
668                 theCuts.push(make_pair(pars, bp.textclass));
669         } else
670                 copySelectionToStack(cur, theCuts);
671
672         // stuff the selection onto the X clipboard, from an explicit copy request
673         putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
674 }
675
676
677 void saveSelection(Cursor & cur)
678 {
679         // This function is called, not when a selection is formed, but when
680         // a selection is cleared. Therefore, multiple keyboard selection
681         // will not repeatively trigger this function (bug 3877).
682         if (cur.selection() 
683             && cur.selBegin() == cur.bv().cursor().selBegin()
684             && cur.selEnd() == cur.bv().cursor().selEnd()) {
685                 LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION << ": `"
686                            << to_utf8(cur.selectionAsString(true)) << "'."
687                            << endl;
688                 copySelectionToStack(cur, selectionBuffer);
689         }
690 }
691
692
693 bool selection()
694 {
695         return !selectionBuffer.empty();
696 }
697
698
699 void clearSelection()
700 {
701         selectionBuffer.clear();
702 }
703
704
705 docstring getSelection(Buffer const & buf, size_t sel_index)
706 {
707         return sel_index < theCuts.size()
708                 ? theCuts[sel_index].first.back().asString(buf, false)
709                 : docstring();
710 }
711
712
713 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
714                         textclass_type textclass, ErrorList & errorList)
715 {
716         if (cur.inTexted()) {
717                 Text * text = cur.text();
718                 BOOST_ASSERT(text);
719
720                 pit_type endpit;
721                 PitPosPair ppp;
722
723                 boost::tie(ppp, endpit) =
724                         pasteSelectionHelper(cur, parlist,
725                                              textclass, errorList);
726                 updateLabels(cur.buffer());
727                 cur.clearSelection();
728                 text->setCursor(cur, ppp.first, ppp.second);
729         }
730
731         // mathed is handled in InsetMathNest/InsetMathGrid
732         BOOST_ASSERT(!cur.inMathed());
733 }
734
735
736 void pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
737 {
738         // this does not make sense, if there is nothing to paste
739         if (!checkPastePossible(sel_index))
740                 return;
741
742         recordUndo(cur);
743         pasteParagraphList(cur, theCuts[sel_index].first,
744                            theCuts[sel_index].second, errorList);
745         cur.setSelection();
746 }
747
748
749 void pasteClipboard(Cursor & cur, ErrorList & errorList, bool asParagraphs)
750 {
751         // Use internal clipboard if it is the most recent one
752         if (theClipboard().isInternal()) {
753                 pasteFromStack(cur, errorList, 0);
754                 return;
755         }
756
757         // First try LyX format
758         if (theClipboard().hasLyXContents()) {
759                 string lyx = theClipboard().getAsLyX();
760                 if (!lyx.empty()) {
761                         // For some strange reason gcc 3.2 and 3.3 do not accept
762                         // Buffer buffer(string(), false);
763                         Buffer buffer("", false);
764                         buffer.setUnnamed(true);
765                         if (buffer.readString(lyx)) {
766                                 recordUndo(cur);
767                                 pasteParagraphList(cur, buffer.paragraphs(),
768                                         buffer.params().textclass, errorList);
769                                 cur.setSelection();
770                                 return;
771                         }
772                 }
773         }
774
775         // Then try plain text
776         docstring const text = theClipboard().getAsText();
777         if (text.empty())
778                 return;
779         recordUndo(cur);
780         if (asParagraphs)
781                 cur.text()->insertStringAsParagraphs(cur, text);
782         else
783                 cur.text()->insertStringAsLines(cur, text);
784 }
785
786
787 void pasteSelection(Cursor & cur, ErrorList & errorList)
788 {
789         if (selectionBuffer.empty())
790                 return;
791         recordUndo(cur);
792         pasteParagraphList(cur, selectionBuffer[0].first,
793                            selectionBuffer[0].second, errorList);
794 }
795
796
797 void replaceSelectionWithString(Cursor & cur, docstring const & str, bool backwards)
798 {
799         recordUndo(cur);
800         DocIterator selbeg = cur.selectionBegin();
801
802         // Get font setting before we cut
803         Font const font =
804                 selbeg.paragraph().getFontSettings(cur.buffer().params(), selbeg.pos());
805
806         // Insert the new string
807         pos_type pos = cur.selEnd().pos();
808         Paragraph & par = cur.selEnd().paragraph();
809         docstring::const_iterator cit = str.begin();
810         docstring::const_iterator end = str.end();
811         for (; cit != end; ++cit, ++pos)
812                 par.insertChar(pos, *cit, font, cur.buffer().params().trackChanges);
813
814         // Cut the selection
815         cutSelection(cur, true, false);
816
817         // select the replacement
818         if (backwards) {
819                 selbeg.pos() += str.length();
820                 cur.setSelection(selbeg, -int(str.length()));
821         } else
822                 cur.setSelection(selbeg, str.length());
823 }
824
825
826 void replaceSelection(Cursor & cur)
827 {
828         if (cur.selection())
829                 cutSelection(cur, true, false);
830 }
831
832
833 void eraseSelection(Cursor & cur)
834 {
835         //lyxerr << "cap::eraseSelection begin: " << cur << endl;
836         CursorSlice const & i1 = cur.selBegin();
837         CursorSlice const & i2 = cur.selEnd();
838         if (i1.inset().asInsetMath()) {
839                 saveSelection(cur);
840                 cur.top() = i1;
841                 if (i1.idx() == i2.idx()) {
842                         i1.cell().erase(i1.pos(), i2.pos());
843                         // We may have deleted i1.cell(cur.pos()).
844                         // Make sure that pos is valid.
845                         if (cur.pos() > cur.lastpos())
846                                 cur.pos() = cur.lastpos();
847                 } else {
848                         InsetMath * p = i1.asInsetMath();
849                         Inset::row_type r1, r2;
850                         Inset::col_type c1, c2;
851                         region(i1, i2, r1, r2, c1, c2);
852                         for (Inset::row_type row = r1; row <= r2; ++row)
853                                 for (Inset::col_type col = c1; col <= c2; ++col)
854                                         p->cell(p->index(row, col)).clear();
855                         // We've deleted the whole cell. Only pos 0 is valid.
856                         cur.pos() = 0;
857                 }
858                 // need a valid cursor. (Lgb)
859                 cur.clearSelection();
860         } else {
861                 lyxerr << "can't erase this selection 1" << endl;
862         }
863         //lyxerr << "cap::eraseSelection end: " << cur << endl;
864 }
865
866
867 void selDel(Cursor & cur)
868 {
869         //lyxerr << "cap::selDel" << endl;
870         if (cur.selection())
871                 eraseSelection(cur);
872 }
873
874
875 void selClearOrDel(Cursor & cur)
876 {
877         //lyxerr << "cap::selClearOrDel" << endl;
878         if (lyxrc.auto_region_delete)
879                 selDel(cur);
880         else
881                 cur.selection() = false;
882 }
883
884
885 docstring grabSelection(Cursor const & cur)
886 {
887         if (!cur.selection())
888                 return docstring();
889
890         // FIXME: What is wrong with the following?
891 #if 0
892         std::ostringstream os;
893         for (DocIterator dit = cur.selectionBegin();
894              dit != cur.selectionEnd(); dit.forwardPos())
895                 os << asString(dit.cell());
896         return os.str();
897 #endif
898
899         CursorSlice i1 = cur.selBegin();
900         CursorSlice i2 = cur.selEnd();
901
902         if (i1.idx() == i2.idx()) {
903                 if (i1.inset().asInsetMath()) {
904                         MathData::const_iterator it = i1.cell().begin();
905                         return asString(MathData(it + i1.pos(), it + i2.pos()));
906                 } else {
907                         return from_ascii("unknown selection 1");
908                 }
909         }
910
911         Inset::row_type r1, r2;
912         Inset::col_type c1, c2;
913         region(i1, i2, r1, r2, c1, c2);
914
915         docstring data;
916         if (i1.inset().asInsetMath()) {
917                 for (Inset::row_type row = r1; row <= r2; ++row) {
918                         if (row > r1)
919                                 data += "\\\\";
920                         for (Inset::col_type col = c1; col <= c2; ++col) {
921                                 if (col > c1)
922                                         data += '&';
923                                 data += asString(i1.asInsetMath()->
924                                         cell(i1.asInsetMath()->index(row, col)));
925                         }
926                 }
927         } else {
928                 data = from_ascii("unknown selection 2");
929         }
930         return data;
931 }
932
933
934 void dirtyTabularStack(bool b)
935 {
936         dirty_tabular_stack_ = b;
937 }
938
939
940 bool tabularStackDirty()
941 {
942         return dirty_tabular_stack_;
943 }
944
945
946 } // namespace cap
947
948 } // namespace lyx