]> git.lyx.org Git - lyx.git/blob - src/CutAndPaste.cpp
rename Layout_ptr into LayoutPtr
[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 "TextClass_ptr.h"
34 #include "TextClassList.h"
35 #include "Paragraph.h"
36 #include "paragraph_funcs.h"
37 #include "ParagraphParameters.h"
38 #include "ParIterator.h"
39 #include "Undo.h"
40
41 #include "insets/InsetCharStyle.h"
42 #include "insets/InsetTabular.h"
43
44 #include "mathed/MathData.h"
45 #include "mathed/InsetMath.h"
46 #include "mathed/MathSupport.h"
47
48 #include "support/lstrings.h"
49
50 #include "frontends/Clipboard.h"
51 #include "frontends/Selection.h"
52
53 #include <boost/current_function.hpp>
54 #include <boost/tuple/tuple.hpp>
55
56 #include <string>
57
58 using std::endl;
59 using std::for_each;
60 using std::make_pair;
61 using std::pair;
62 using std::vector;
63 using std::string;
64
65
66 namespace lyx {
67
68 using support::bformat;
69 using frontend::Clipboard;
70
71 namespace {
72
73 typedef std::pair<pit_type, int> PitPosPair;
74
75 typedef limited_stack<pair<ParagraphList, TextClass_ptr> > CutStack;
76
77 CutStack theCuts(10);
78 // persistent selection, cleared until the next selection
79 CutStack selectionBuffer(1);
80
81 // store whether the tabular stack is newer than the normal copy stack
82 // FIXME: this is a workaround for bug 1919. Should be removed for 1.5,
83 // when we (hopefully) have a one-for-all paste mechanism.
84 bool dirty_tabular_stack_ = false;
85
86
87 void region(CursorSlice const & i1, CursorSlice const & i2,
88         Inset::row_type & r1, Inset::row_type & r2,
89         Inset::col_type & c1, Inset::col_type & c2)
90 {
91         Inset & p = i1.inset();
92         c1 = p.col(i1.idx());
93         c2 = p.col(i2.idx());
94         if (c1 > c2)
95                 std::swap(c1, c2);
96         r1 = p.row(i1.idx());
97         r2 = p.row(i2.idx());
98         if (r1 > r2)
99                 std::swap(r1, r2);
100 }
101
102
103 bool checkPastePossible(int index)
104 {
105         return size_t(index) < theCuts.size() && !theCuts[index].first.empty();
106 }
107
108
109 pair<PitPosPair, pit_type>
110 pasteSelectionHelper(Cursor & cur, ParagraphList const & parlist,
111                      TextClass_ptr textclass, ErrorList & errorlist)
112 {
113         Buffer const & buffer = cur.buffer();
114         pit_type pit = cur.pit();
115         pos_type pos = cur.pos();
116         ParagraphList & pars = cur.text()->paragraphs();
117
118         if (parlist.empty())
119                 return make_pair(PitPosPair(pit, pos), pit);
120
121         BOOST_ASSERT (pos <= pars[pit].size());
122
123         // Make a copy of the CaP paragraphs.
124         ParagraphList insertion = parlist;
125         TextClass_ptr const tc = buffer.params().getTextClass_ptr();
126
127         // Now remove all out of the pars which is NOT allowed in the
128         // new environment and set also another font if that is required.
129
130         // Convert newline to paragraph break in ERT inset.
131         // This should not be here!
132         if (pars[pit].inInset() &&
133             (pars[pit].inInset()->lyxCode() == Inset::ERT_CODE ||
134                 pars[pit].inInset()->lyxCode() == Inset::LISTINGS_CODE)) {
135                 for (ParagraphList::size_type i = 0; i < insertion.size(); ++i) {
136                         for (pos_type j = 0; j < insertion[i].size(); ++j) {
137                                 if (insertion[i].isNewline(j)) {
138                                         // do not track deletion of newline
139                                         insertion[i].eraseChar(j, false);
140                                         breakParagraphConservative(
141                                                         buffer.params(),
142                                                         insertion, i, j);
143                                 }
144                         }
145                 }
146         }
147
148         // If we are in an inset which returns forceDefaultParagraphs,
149         // set the paragraphs to default
150         if (cur.inset().forceDefaultParagraphs(cur.idx())) {
151                 LayoutPtr const layout =
152                         buffer.params().getTextClass().defaultLayout();
153                 ParagraphList::iterator const end = insertion.end();
154                 for (ParagraphList::iterator par = insertion.begin();
155                                 par != end; ++par)
156                         par->layout(layout);
157         }
158
159         // Make sure there is no class difference.
160         InsetText in;
161         // This works without copying any paragraph data because we have
162         // a specialized swap method for ParagraphList. This is important
163         // since we store pointers to insets at some places and we don't
164         // want to invalidate them.
165         insertion.swap(in.paragraphs());
166         cap::switchBetweenClasses(textclass, tc, in, errorlist);
167         insertion.swap(in.paragraphs());
168
169         ParagraphList::iterator tmpbuf = insertion.begin();
170         int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
171
172         depth_type max_depth = pars[pit].getMaxDepthAfter();
173
174         for (; tmpbuf != insertion.end(); ++tmpbuf) {
175                 // If we have a negative jump so that the depth would
176                 // go below 0 depth then we have to redo the delta to
177                 // this new max depth level so that subsequent
178                 // paragraphs are aligned correctly to this paragraph
179                 // at level 0.
180                 if (int(tmpbuf->params().depth()) + depth_delta < 0)
181                         depth_delta = 0;
182
183                 // Set the right depth so that we are not too deep or shallow.
184                 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
185                 if (tmpbuf->params().depth() > max_depth)
186                         tmpbuf->params().depth(max_depth);
187
188                 // Only set this from the 2nd on as the 2nd depends
189                 // for maxDepth still on pit.
190                 if (tmpbuf != insertion.begin())
191                         max_depth = tmpbuf->getMaxDepthAfter();
192
193                 // Set the inset owner of this paragraph.
194                 tmpbuf->setInsetOwner(pars[pit].inInset());
195                 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
196                         if (tmpbuf->getChar(i) == Paragraph::META_INSET &&
197                             !pars[pit].insetAllowed(tmpbuf->getInset(i)->lyxCode()))
198                                 // do not track deletion of invalid insets
199                                 tmpbuf->eraseChar(i--, false);
200                 }
201
202                 tmpbuf->setChange(Change(buffer.params().trackChanges ?
203                                          Change::INSERTED : Change::UNCHANGED));
204         }
205
206         bool const empty = pars[pit].empty();
207         if (!empty) {
208                 // Make the buf exactly the same layout as the cursor
209                 // paragraph.
210                 insertion.begin()->makeSameLayout(pars[pit]);
211         }
212
213         // Prepare the paragraphs and insets for insertion.
214         // A couple of insets store buffer references so need updating.
215         insertion.swap(in.paragraphs());
216
217         ParIterator fpit = par_iterator_begin(in);
218         ParIterator fend = par_iterator_end(in);
219
220         for (; fpit != fend; ++fpit) {
221                 InsetList::const_iterator lit = fpit->insetlist.begin();
222                 InsetList::const_iterator eit = fpit->insetlist.end();
223
224                 for (; lit != eit; ++lit) {
225                         switch (lit->inset->lyxCode()) {
226                         case Inset::TABULAR_CODE: {
227                                 InsetTabular * it = static_cast<InsetTabular*>(lit->inset);
228                                 it->buffer(&buffer);
229                                 break;
230                         }
231
232                         default:
233                                 break; // nothing
234                         }
235                 }
236         }
237         insertion.swap(in.paragraphs());
238
239         // Split the paragraph for inserting the buf if necessary.
240         if (!empty)
241                 breakParagraphConservative(buffer.params(), pars, pit, pos);
242
243         // Paste it!
244         if (empty) {
245                 pars.insert(boost::next(pars.begin(), pit),
246                             insertion.begin(),
247                             insertion.end());
248
249                 // merge the empty par with the last par of the insertion
250                 mergeParagraph(buffer.params(), pars,
251                                pit + insertion.size() - 1);
252         } else {
253                 pars.insert(boost::next(pars.begin(), pit + 1),
254                             insertion.begin(),
255                             insertion.end());
256
257                 // merge the first par of the insertion with the current par
258                 mergeParagraph(buffer.params(), pars, pit);
259         }
260
261         pit_type last_paste = pit + insertion.size() - 1;
262
263         // Store the new cursor position.
264         pit = last_paste;
265         pos = pars[last_paste].size();
266
267         // Join (conditionally) last pasted paragraph with next one, i.e.,
268         // the tail of the spliced document paragraph
269         if (!empty && last_paste + 1 != pit_type(pars.size())) {
270                 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
271                         mergeParagraph(buffer.params(), pars, last_paste);
272                 } else if (pars[last_paste + 1].empty()) {
273                         pars[last_paste + 1].makeSameLayout(pars[last_paste]);
274                         mergeParagraph(buffer.params(), pars, last_paste);
275                 } else if (pars[last_paste].empty()) {
276                         pars[last_paste].makeSameLayout(pars[last_paste + 1]);
277                         mergeParagraph(buffer.params(), pars, last_paste);
278                 } else {
279                         pars[last_paste + 1].stripLeadingSpaces(buffer.params().trackChanges);
280                         ++last_paste;
281                 }
282         }
283
284         return make_pair(PitPosPair(pit, pos), last_paste + 1);
285 }
286
287
288 PitPosPair eraseSelectionHelper(BufferParams const & params,
289         ParagraphList & pars,
290         pit_type startpit, pit_type endpit,
291         int startpos, int endpos, bool doclear)
292 {
293         // Start of selection is really invalid.
294         if (startpit == pit_type(pars.size()) ||
295             (startpos > pars[startpit].size()))
296                 return PitPosPair(endpit, endpos);
297
298         // Start and end is inside same paragraph
299         if (endpit == pit_type(pars.size()) || startpit == endpit) {
300                 endpos -= pars[startpit].eraseChars(startpos, endpos, params.trackChanges);
301                 return PitPosPair(endpit, endpos);
302         }
303
304         for (pit_type pit = startpit; pit != endpit + 1;) {
305                 pos_type const left  = (pit == startpit ? startpos : 0);
306                 pos_type right = (pit == endpit ? endpos : pars[pit].size() + 1);
307                 // FIXME: this is a quick fix for bug 3600. It stops a crash but the problem
308                 // still remains unsolved (e.g. the second example in the bug report).
309                 // c.f. http://bugzilla.lyx.org/show_bug.cgi?id=3600
310                 if (right > pars[pit].size() + 1)
311                         right = pars[pit].size() + 1;
312
313                 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.trackChanges);
314
315                 // Logically erase only, including the end-of-paragraph character
316                 pars[pit].eraseChars(left, right, params.trackChanges);
317
318                 // Separate handling of paragraph break:
319                 if (merge && pit != endpit &&
320                     (pit + 1 != endpit || pars[pit].hasSameLayout(pars[pit + 1]))) {
321                         pos_type const thissize = pars[pit].size();
322                         if (doclear)
323                                 pars[pit + 1].stripLeadingSpaces(params.trackChanges);
324                         mergeParagraph(params, pars, pit);
325                         --endpit;
326                         if (pit == endpit)
327                                 endpos += thissize;
328                 } else
329                         ++pit;
330         }
331
332         // Ensure legal cursor pos:
333         endpit = startpit;
334         endpos = startpos;
335         return PitPosPair(endpit, endpos);
336 }
337
338
339 void putClipboard(ParagraphList const & paragraphs, TextClass_ptr textclass,
340                   docstring const & plaintext)
341 {
342         // For some strange reason gcc 3.2 and 3.3 do not accept
343         // Buffer buffer(string(), false);
344         Buffer buffer("", false);
345         buffer.setUnnamed(true);
346         buffer.paragraphs() = paragraphs;
347         buffer.params().setTextClass(textclass);
348         std::ostringstream lyx;
349         if (buffer.write(lyx))
350                 theClipboard().put(lyx.str(), plaintext);
351         else
352                 theClipboard().put(string(), plaintext);
353 }
354
355
356 void copySelectionHelper(Buffer const & buf, ParagraphList & pars,
357         pit_type startpit, pit_type endpit,
358         int start, int end, TextClass_ptr tc, CutStack & cutstack)
359 {
360         BOOST_ASSERT(0 <= start && start <= pars[startpit].size());
361         BOOST_ASSERT(0 <= end && end <= pars[endpit].size());
362         BOOST_ASSERT(startpit != endpit || start <= end);
363
364         // Clone the paragraphs within the selection.
365         ParagraphList copy_pars(boost::next(pars.begin(), startpit),
366                                 boost::next(pars.begin(), endpit + 1));
367
368         // Remove the end of the last paragraph; afterwards, remove the
369         // beginning of the first paragraph. Keep this order - there may only
370         // be one paragraph!  Do not track deletions here; this is an internal
371         // action not visible to the user
372
373         Paragraph & back = copy_pars.back();
374         back.eraseChars(end, back.size(), false);
375         Paragraph & front = copy_pars.front();
376         front.eraseChars(0, start, false);
377
378         ParagraphList::iterator it = copy_pars.begin();
379         ParagraphList::iterator it_end = copy_pars.end();
380
381         for (; it != it_end; it++) {
382                 // ERT paragraphs have the Language latex_language.
383                 // This is invalid outside of ERT, so we need to change it
384                 // to the buffer language.
385                 if (it->ownerCode() == Inset::ERT_CODE || it->ownerCode() == Inset::LISTINGS_CODE) {
386                         it->changeLanguage(buf.params(), latex_language,
387                                            buf.getLanguage());
388                 }
389                 it->setInsetOwner(0);
390         }
391
392         // do not copy text (also nested in insets) which is marked as deleted
393         acceptChanges(copy_pars, buf.params());
394
395         cutstack.push(make_pair(copy_pars, tc));
396 }
397
398 } // namespace anon
399
400
401
402
403 namespace cap {
404
405 docstring grabAndEraseSelection(Cursor & cur)
406 {
407         if (!cur.selection())
408                 return docstring();
409         docstring res = grabSelection(cur);
410         eraseSelection(cur);
411         return res;
412 }
413
414
415 void switchBetweenClasses(TextClass_ptr const & c1, 
416         TextClass_ptr const & c2, InsetText & in, ErrorList & errorlist)
417 {
418         errorlist.clear();
419
420         BOOST_ASSERT(!in.paragraphs().empty());
421         if (c1 == c2)
422                 return;
423         
424         TextClass const & tclass1 = *c1;
425         TextClass const & tclass2 = *c2;
426
427         // layouts
428         ParIterator end = par_iterator_end(in);
429         for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
430                 docstring const name = it->layout()->name();
431                 bool hasLayout = tclass2.hasLayout(name);
432
433                 if (hasLayout)
434                         it->layout(tclass2[name]);
435                 else
436                         it->layout(tclass2.defaultLayout());
437
438                 if (!hasLayout && name != tclass1.defaultLayoutName()) {
439                         docstring const s = bformat(
440                                                  _("Layout had to be changed from\n%1$s to %2$s\n"
441                                                 "because of class conversion from\n%3$s to %4$s"),
442                          name, it->layout()->name(),
443                          from_utf8(tclass1.name()), from_utf8(tclass2.name()));
444                         // To warn the user that something had to be done.
445                         errorlist.push_back(ErrorItem(_("Changed Layout"), s,
446                                                       it->id(), 0,
447                                                       it->size()));
448                 }
449         }
450
451         // character styles
452         InsetIterator const i_end = inset_iterator_end(in);
453         for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
454                 if (it->lyxCode() == Inset::CHARSTYLE_CODE) {
455                         InsetCharStyle & inset =
456                                 static_cast<InsetCharStyle &>(*it);
457                         string const name = inset.params().name;
458                         CharStyles::iterator const found_cs =
459                                 tclass2.charstyle(name);
460                         if (found_cs == tclass2.charstyles().end()) {
461                                 // The character style is undefined in tclass2
462                                 inset.setUndefined();
463                                 docstring const s = bformat(_(
464                                         "Character style %1$s is "
465                                         "undefined because of class "
466                                         "conversion from\n%2$s to %3$s"),
467                                          from_utf8(name), from_utf8(tclass1.name()),
468                                          from_utf8(tclass2.name()));
469                                 // To warn the user that something had to be done.
470                                 errorlist.push_back(ErrorItem(
471                                         _("Undefined character style"),
472                                         s, it.paragraph().id(), it.pos(), it.pos() + 1));
473                         } else if (inset.undefined()) {
474                                 // The character style is undefined in
475                                 // tclass1 and is defined in tclass2
476                                 inset.setDefined(found_cs);
477                         }
478                 }
479         }
480 }
481
482
483 std::vector<docstring> const availableSelections(Buffer const & buffer)
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(buffer, 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                 recordUndoSelection(cur);
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.getTextClass_ptr(), 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                                 doclear);
559
560                 // cutSelection can invalidate the cursor so we need to set
561                 // it anew. (Lgb)
562                 // we prefer the end for when tracking changes
563                 cur.pos() = endpos;
564                 cur.pit() = endpit;
565
566                 // sometimes necessary
567                 if (doclear
568                         && text->paragraphs()[begpit].stripLeadingSpaces(bp.trackChanges))
569                         cur.fixIfBroken();
570
571                 // need a valid cursor. (Lgb)
572                 cur.clearSelection();
573                 updateLabels(cur.buffer());
574
575                 // tell tabular that a recent copy happened
576                 dirtyTabularStack(false);
577         }
578
579         if (cur.inMathed()) {
580                 if (cur.selBegin().idx() != cur.selEnd().idx()) {
581                         // The current selection spans more than one cell.
582                         // Record all cells
583                         recordUndoInset(cur);
584                 } else {
585                         // Record only the current cell to avoid a jumping
586                         // cursor after undo
587                         recordUndo(cur);
588                 }
589                 if (realcut)
590                         copySelection(cur);
591                 eraseSelection(cur);
592         }
593 }
594
595
596 void copySelection(Cursor & cur)
597 {
598         copySelection(cur, cur.selectionAsString(true));
599 }
600
601
602 namespace {
603
604 void copySelectionToStack(Cursor & cur, CutStack & cutstack)
605 {
606         // this doesn't make sense, if there is no selection
607         if (!cur.selection())
608                 return;
609
610         // copySelection can not yet handle the case of cross idx selection
611         if (cur.selBegin().idx() != cur.selEnd().idx())
612                 return;
613
614         if (cur.inTexted()) {
615                 Text * text = cur.text();
616                 BOOST_ASSERT(text);
617                 // ok we have a selection. This is always between cur.selBegin()
618                 // and sel_end cursor
619
620                 // copy behind a space if there is one
621                 ParagraphList & pars = text->paragraphs();
622                 pos_type pos = cur.selBegin().pos();
623                 pit_type par = cur.selBegin().pit();
624                 while (pos < pars[par].size() &&
625                        pars[par].isLineSeparator(pos) &&
626                        (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
627                         ++pos;
628
629                 copySelectionHelper(cur.buffer(), pars, par, cur.selEnd().pit(),
630                         pos, cur.selEnd().pos(), 
631                         cur.buffer().params().getTextClass_ptr(), cutstack);
632                 dirtyTabularStack(false);
633         }
634
635         if (cur.inMathed()) {
636                 //lyxerr << "copySelection in mathed" << endl;
637                 ParagraphList pars;
638                 Paragraph par;
639                 BufferParams const & bp = cur.buffer().params();
640                 par.layout(bp.getTextClass().defaultLayout());
641                 par.insert(0, grabSelection(cur), Font(), Change(Change::UNCHANGED));
642                 pars.push_back(par);
643                 cutstack.push(make_pair(pars, bp.getTextClass_ptr()));
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 attemp 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.layout(bp.getTextClass().defaultLayout());
668                 par.insert(0, plaintext, Font(), Change(Change::UNCHANGED));
669                 pars.push_back(par);
670                 theCuts.push(make_pair(pars, bp.getTextClass_ptr()));
671         } else
672                 copySelectionToStack(cur, theCuts);
673
674         // stuff the selection onto the X clipboard, from an explicit copy request
675         putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
676 }
677
678
679 void saveSelection(Cursor & cur)
680 {
681         // This function is called, not when a selection is formed, but when
682         // a selection is cleared. Therefore, multiple keyboard selection
683         // will not repeatively trigger this function (bug 3877).
684         if (cur.selection() 
685             && cur.selBegin() == cur.bv().cursor().selBegin()
686             && cur.selEnd() == cur.bv().cursor().selEnd()) {
687                 LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION << ": `"
688                            << to_utf8(cur.selectionAsString(true)) << "'."
689                            << endl;
690                 copySelectionToStack(cur, selectionBuffer);
691         }
692 }
693
694
695 bool selection()
696 {
697         return !selectionBuffer.empty();
698 }
699
700
701 void clearSelection()
702 {
703         selectionBuffer.clear();
704 }
705
706
707 docstring getSelection(Buffer const & buf, size_t sel_index)
708 {
709         return sel_index < theCuts.size()
710                 ? theCuts[sel_index].first.back().asString(buf, false)
711                 : docstring();
712 }
713
714
715 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
716                         TextClass_ptr textclass, ErrorList & errorList)
717 {
718         if (cur.inTexted()) {
719                 Text * text = cur.text();
720                 BOOST_ASSERT(text);
721
722                 pit_type endpit;
723                 PitPosPair ppp;
724
725                 boost::tie(ppp, endpit) =
726                         pasteSelectionHelper(cur, parlist,
727                                              textclass, errorList);
728                 updateLabels(cur.buffer());
729                 cur.clearSelection();
730                 text->setCursor(cur, ppp.first, ppp.second);
731         }
732
733         // mathed is handled in InsetMathNest/InsetMathGrid
734         BOOST_ASSERT(!cur.inMathed());
735 }
736
737
738 void pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
739 {
740         // this does not make sense, if there is nothing to paste
741         if (!checkPastePossible(sel_index))
742                 return;
743
744         recordUndo(cur);
745         pasteParagraphList(cur, theCuts[sel_index].first,
746                            theCuts[sel_index].second, errorList);
747         cur.setSelection();
748 }
749
750
751 void pasteClipboard(Cursor & cur, ErrorList & errorList, bool asParagraphs)
752 {
753         // Use internal clipboard if it is the most recent one
754         if (theClipboard().isInternal()) {
755                 pasteFromStack(cur, errorList, 0);
756                 return;
757         }
758
759         // First try LyX format
760         if (theClipboard().hasLyXContents()) {
761                 string lyx = theClipboard().getAsLyX();
762                 if (!lyx.empty()) {
763                         // For some strange reason gcc 3.2 and 3.3 do not accept
764                         // Buffer buffer(string(), false);
765                         Buffer buffer("", false);
766                         buffer.setUnnamed(true);
767                         if (buffer.readString(lyx)) {
768                                 recordUndo(cur);
769                                 pasteParagraphList(cur, buffer.paragraphs(),
770                                         buffer.params().getTextClass_ptr(), errorList);
771                                 cur.setSelection();
772                                 return;
773                         }
774                 }
775         }
776
777         // Then try plain text
778         docstring const text = theClipboard().getAsText();
779         if (text.empty())
780                 return;
781         recordUndo(cur);
782         if (asParagraphs)
783                 cur.text()->insertStringAsParagraphs(cur, text);
784         else
785                 cur.text()->insertStringAsLines(cur, text);
786 }
787
788
789 void pasteSelection(Cursor & cur, ErrorList & errorList)
790 {
791         if (selectionBuffer.empty())
792                 return;
793         recordUndo(cur);
794         pasteParagraphList(cur, selectionBuffer[0].first,
795                            selectionBuffer[0].second, errorList);
796 }
797
798
799 void replaceSelectionWithString(Cursor & cur, docstring const & str, bool backwards)
800 {
801         recordUndo(cur);
802         DocIterator selbeg = cur.selectionBegin();
803
804         // Get font setting before we cut
805         Font const font =
806                 selbeg.paragraph().getFontSettings(cur.buffer().params(), selbeg.pos());
807
808         // Insert the new string
809         pos_type pos = cur.selEnd().pos();
810         Paragraph & par = cur.selEnd().paragraph();
811         docstring::const_iterator cit = str.begin();
812         docstring::const_iterator end = str.end();
813         for (; cit != end; ++cit, ++pos)
814                 par.insertChar(pos, *cit, font, cur.buffer().params().trackChanges);
815
816         // Cut the selection
817         cutSelection(cur, true, false);
818
819         // select the replacement
820         if (backwards) {
821                 selbeg.pos() += str.length();
822                 cur.setSelection(selbeg, -int(str.length()));
823         } else
824                 cur.setSelection(selbeg, str.length());
825 }
826
827
828 void replaceSelection(Cursor & cur)
829 {
830         if (cur.selection())
831                 cutSelection(cur, true, false);
832 }
833
834
835 void eraseSelection(Cursor & cur)
836 {
837         //lyxerr << "cap::eraseSelection begin: " << cur << endl;
838         CursorSlice const & i1 = cur.selBegin();
839         CursorSlice const & i2 = cur.selEnd();
840         if (i1.inset().asInsetMath()) {
841                 saveSelection(cur);
842                 cur.top() = i1;
843                 if (i1.idx() == i2.idx()) {
844                         i1.cell().erase(i1.pos(), i2.pos());
845                         // We may have deleted i1.cell(cur.pos()).
846                         // Make sure that pos is valid.
847                         if (cur.pos() > cur.lastpos())
848                                 cur.pos() = cur.lastpos();
849                 } else {
850                         InsetMath * p = i1.asInsetMath();
851                         Inset::row_type r1, r2;
852                         Inset::col_type c1, c2;
853                         region(i1, i2, r1, r2, c1, c2);
854                         for (Inset::row_type row = r1; row <= r2; ++row)
855                                 for (Inset::col_type col = c1; col <= c2; ++col)
856                                         p->cell(p->index(row, col)).clear();
857                         // We've deleted the whole cell. Only pos 0 is valid.
858                         cur.pos() = 0;
859                 }
860                 // need a valid cursor. (Lgb)
861                 cur.clearSelection();
862         } else {
863                 lyxerr << "can't erase this selection 1" << endl;
864         }
865         //lyxerr << "cap::eraseSelection end: " << cur << endl;
866 }
867
868
869 void selDel(Cursor & cur)
870 {
871         //lyxerr << "cap::selDel" << endl;
872         if (cur.selection())
873                 eraseSelection(cur);
874 }
875
876
877 void selClearOrDel(Cursor & cur)
878 {
879         //lyxerr << "cap::selClearOrDel" << endl;
880         if (lyxrc.auto_region_delete)
881                 selDel(cur);
882         else
883                 cur.selection() = false;
884 }
885
886
887 docstring grabSelection(Cursor const & cur)
888 {
889         if (!cur.selection())
890                 return docstring();
891
892         // FIXME: What is wrong with the following?
893 #if 0
894         std::ostringstream os;
895         for (DocIterator dit = cur.selectionBegin();
896              dit != cur.selectionEnd(); dit.forwardPos())
897                 os << asString(dit.cell());
898         return os.str();
899 #endif
900
901         CursorSlice i1 = cur.selBegin();
902         CursorSlice i2 = cur.selEnd();
903
904         if (i1.idx() == i2.idx()) {
905                 if (i1.inset().asInsetMath()) {
906                         MathData::const_iterator it = i1.cell().begin();
907                         return asString(MathData(it + i1.pos(), it + i2.pos()));
908                 } else {
909                         return from_ascii("unknown selection 1");
910                 }
911         }
912
913         Inset::row_type r1, r2;
914         Inset::col_type c1, c2;
915         region(i1, i2, r1, r2, c1, c2);
916
917         docstring data;
918         if (i1.inset().asInsetMath()) {
919                 for (Inset::row_type row = r1; row <= r2; ++row) {
920                         if (row > r1)
921                                 data += "\\\\";
922                         for (Inset::col_type col = c1; col <= c2; ++col) {
923                                 if (col > c1)
924                                         data += '&';
925                                 data += asString(i1.asInsetMath()->
926                                         cell(i1.asInsetMath()->index(row, col)));
927                         }
928                 }
929         } else {
930                 data = from_ascii("unknown selection 2");
931         }
932         return data;
933 }
934
935
936 void dirtyTabularStack(bool b)
937 {
938         dirty_tabular_stack_ = b;
939 }
940
941
942 bool tabularStackDirty()
943 {
944         return dirty_tabular_stack_;
945 }
946
947
948 } // namespace cap
949
950 } // namespace lyx