]> git.lyx.org Git - lyx.git/blob - src/CutAndPaste.cpp
Move background colour into the layout files -- for all collapsables
[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                         InsetLayout const il = 
459                                 tclass2.insetlayout(from_utf8(name));
460                         inset.setLayout(il);
461                         if (il.labelstring == from_utf8("UNDEFINED")) {
462                                 // The character style is undefined in tclass2
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                         } 
474                 }
475         }
476 }
477
478
479 std::vector<docstring> const availableSelections(Buffer const & buffer)
480 {
481         vector<docstring> selList;
482
483         CutStack::const_iterator cit = theCuts.begin();
484         CutStack::const_iterator end = theCuts.end();
485         for (; cit != end; ++cit) {
486                 // we do not use cit-> here because gcc 2.9x does not
487                 // like it (JMarc)
488                 ParagraphList const & pars = (*cit).first;
489                 docstring asciiSel;
490                 ParagraphList::const_iterator pit = pars.begin();
491                 ParagraphList::const_iterator pend = pars.end();
492                 for (; pit != pend; ++pit) {
493                         asciiSel += pit->asString(buffer, false);
494                         if (asciiSel.size() > 25) {
495                                 asciiSel.replace(22, docstring::npos,
496                                                  from_ascii("..."));
497                                 break;
498                         }
499                 }
500
501                 selList.push_back(asciiSel);
502         }
503
504         return selList;
505 }
506
507
508 size_type numberOfSelections()
509 {
510         return theCuts.size();
511 }
512
513
514 void cutSelection(Cursor & cur, bool doclear, bool realcut)
515 {
516         // This doesn't make sense, if there is no selection
517         if (!cur.selection())
518                 return;
519
520         // OK, we have a selection. This is always between cur.selBegin()
521         // and cur.selEnd()
522
523         if (cur.inTexted()) {
524                 Text * text = cur.text();
525                 BOOST_ASSERT(text);
526
527                 saveSelection(cur);
528
529                 // make sure that the depth behind the selection are restored, too
530                 recordUndoSelection(cur);
531                 pit_type begpit = cur.selBegin().pit();
532                 pit_type endpit = cur.selEnd().pit();
533
534                 int endpos = cur.selEnd().pos();
535
536                 BufferParams const & bp = cur.buffer().params();
537                 if (realcut) {
538                         copySelectionHelper(cur.buffer(),
539                                 text->paragraphs(),
540                                 begpit, endpit,
541                                 cur.selBegin().pos(), endpos,
542                                 bp.getTextClass_ptr(), theCuts);
543                         // Stuff what we got on the clipboard.
544                         // Even if there is no selection.
545                         putClipboard(theCuts[0].first, theCuts[0].second,
546                                 cur.selectionAsString(true));
547                 }
548
549                 boost::tie(endpit, endpos) =
550                         eraseSelectionHelper(bp,
551                                 text->paragraphs(),
552                                 begpit, endpit,
553                                 cur.selBegin().pos(), endpos,
554                                 doclear);
555
556                 // cutSelection can invalidate the cursor so we need to set
557                 // it anew. (Lgb)
558                 // we prefer the end for when tracking changes
559                 cur.pos() = endpos;
560                 cur.pit() = endpit;
561
562                 // sometimes necessary
563                 if (doclear
564                         && text->paragraphs()[begpit].stripLeadingSpaces(bp.trackChanges))
565                         cur.fixIfBroken();
566
567                 // need a valid cursor. (Lgb)
568                 cur.clearSelection();
569                 updateLabels(cur.buffer());
570
571                 // tell tabular that a recent copy happened
572                 dirtyTabularStack(false);
573         }
574
575         if (cur.inMathed()) {
576                 if (cur.selBegin().idx() != cur.selEnd().idx()) {
577                         // The current selection spans more than one cell.
578                         // Record all cells
579                         recordUndoInset(cur);
580                 } else {
581                         // Record only the current cell to avoid a jumping
582                         // cursor after undo
583                         recordUndo(cur);
584                 }
585                 if (realcut)
586                         copySelection(cur);
587                 eraseSelection(cur);
588         }
589 }
590
591
592 void copySelection(Cursor & cur)
593 {
594         copySelection(cur, cur.selectionAsString(true));
595 }
596
597
598 namespace {
599
600 void copySelectionToStack(Cursor & cur, CutStack & cutstack)
601 {
602         // this doesn't make sense, if there is no selection
603         if (!cur.selection())
604                 return;
605
606         // copySelection can not yet handle the case of cross idx selection
607         if (cur.selBegin().idx() != cur.selEnd().idx())
608                 return;
609
610         if (cur.inTexted()) {
611                 Text * text = cur.text();
612                 BOOST_ASSERT(text);
613                 // ok we have a selection. This is always between cur.selBegin()
614                 // and sel_end cursor
615
616                 // copy behind a space if there is one
617                 ParagraphList & pars = text->paragraphs();
618                 pos_type pos = cur.selBegin().pos();
619                 pit_type par = cur.selBegin().pit();
620                 while (pos < pars[par].size() &&
621                        pars[par].isLineSeparator(pos) &&
622                        (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
623                         ++pos;
624
625                 copySelectionHelper(cur.buffer(), pars, par, cur.selEnd().pit(),
626                         pos, cur.selEnd().pos(), 
627                         cur.buffer().params().getTextClass_ptr(), cutstack);
628                 dirtyTabularStack(false);
629         }
630
631         if (cur.inMathed()) {
632                 //lyxerr << "copySelection in mathed" << endl;
633                 ParagraphList pars;
634                 Paragraph par;
635                 BufferParams const & bp = cur.buffer().params();
636                 par.layout(bp.getTextClass().defaultLayout());
637                 par.insert(0, grabSelection(cur), Font(), Change(Change::UNCHANGED));
638                 pars.push_back(par);
639                 cutstack.push(make_pair(pars, bp.getTextClass_ptr()));
640         }
641 }
642
643 }
644
645
646 void copySelectionToStack()
647 {
648         if (!selectionBuffer.empty())
649                 theCuts.push(selectionBuffer[0]);
650 }
651
652
653 void copySelection(Cursor & cur, docstring const & plaintext)
654 {
655         // In tablemode, because copy and paste actually use special table stack
656         // we do not attemp to get selected paragraphs under cursor. Instead, a
657         // paragraph with the plain text version is generated so that table cells
658         // can be pasted as pure text somewhere else.
659         if (cur.selBegin().idx() != cur.selEnd().idx()) {
660                 ParagraphList pars;
661                 Paragraph par;
662                 BufferParams const & bp = cur.buffer().params();
663                 par.layout(bp.getTextClass().defaultLayout());
664                 par.insert(0, plaintext, Font(), Change(Change::UNCHANGED));
665                 pars.push_back(par);
666                 theCuts.push(make_pair(pars, bp.getTextClass_ptr()));
667         } else
668                 copySelectionToStack(cur, theCuts);
669
670         // stuff the selection onto the X clipboard, from an explicit copy request
671         putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
672 }
673
674
675 void saveSelection(Cursor & cur)
676 {
677         // This function is called, not when a selection is formed, but when
678         // a selection is cleared. Therefore, multiple keyboard selection
679         // will not repeatively trigger this function (bug 3877).
680         if (cur.selection() 
681             && cur.selBegin() == cur.bv().cursor().selBegin()
682             && cur.selEnd() == cur.bv().cursor().selEnd()) {
683                 LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION << ": `"
684                            << to_utf8(cur.selectionAsString(true)) << "'."
685                            << endl;
686                 copySelectionToStack(cur, selectionBuffer);
687         }
688 }
689
690
691 bool selection()
692 {
693         return !selectionBuffer.empty();
694 }
695
696
697 void clearSelection()
698 {
699         selectionBuffer.clear();
700 }
701
702
703 docstring getSelection(Buffer const & buf, size_t sel_index)
704 {
705         return sel_index < theCuts.size()
706                 ? theCuts[sel_index].first.back().asString(buf, false)
707                 : docstring();
708 }
709
710
711 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
712                         TextClass_ptr textclass, ErrorList & errorList)
713 {
714         if (cur.inTexted()) {
715                 Text * text = cur.text();
716                 BOOST_ASSERT(text);
717
718                 pit_type endpit;
719                 PitPosPair ppp;
720
721                 boost::tie(ppp, endpit) =
722                         pasteSelectionHelper(cur, parlist,
723                                              textclass, errorList);
724                 updateLabels(cur.buffer());
725                 cur.clearSelection();
726                 text->setCursor(cur, ppp.first, ppp.second);
727         }
728
729         // mathed is handled in InsetMathNest/InsetMathGrid
730         BOOST_ASSERT(!cur.inMathed());
731 }
732
733
734 void pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
735 {
736         // this does not make sense, if there is nothing to paste
737         if (!checkPastePossible(sel_index))
738                 return;
739
740         recordUndo(cur);
741         pasteParagraphList(cur, theCuts[sel_index].first,
742                            theCuts[sel_index].second, errorList);
743         cur.setSelection();
744 }
745
746
747 void pasteClipboard(Cursor & cur, ErrorList & errorList, bool asParagraphs)
748 {
749         // Use internal clipboard if it is the most recent one
750         if (theClipboard().isInternal()) {
751                 pasteFromStack(cur, errorList, 0);
752                 return;
753         }
754
755         // First try LyX format
756         if (theClipboard().hasLyXContents()) {
757                 string lyx = theClipboard().getAsLyX();
758                 if (!lyx.empty()) {
759                         // For some strange reason gcc 3.2 and 3.3 do not accept
760                         // Buffer buffer(string(), false);
761                         Buffer buffer("", false);
762                         buffer.setUnnamed(true);
763                         if (buffer.readString(lyx)) {
764                                 recordUndo(cur);
765                                 pasteParagraphList(cur, buffer.paragraphs(),
766                                         buffer.params().getTextClass_ptr(), errorList);
767                                 cur.setSelection();
768                                 return;
769                         }
770                 }
771         }
772
773         // Then try plain text
774         docstring const text = theClipboard().getAsText();
775         if (text.empty())
776                 return;
777         recordUndo(cur);
778         if (asParagraphs)
779                 cur.text()->insertStringAsParagraphs(cur, text);
780         else
781                 cur.text()->insertStringAsLines(cur, text);
782 }
783
784
785 void pasteSelection(Cursor & cur, ErrorList & errorList)
786 {
787         if (selectionBuffer.empty())
788                 return;
789         recordUndo(cur);
790         pasteParagraphList(cur, selectionBuffer[0].first,
791                            selectionBuffer[0].second, errorList);
792 }
793
794
795 void replaceSelectionWithString(Cursor & cur, docstring const & str, bool backwards)
796 {
797         recordUndo(cur);
798         DocIterator selbeg = cur.selectionBegin();
799
800         // Get font setting before we cut
801         Font const font =
802                 selbeg.paragraph().getFontSettings(cur.buffer().params(), selbeg.pos());
803
804         // Insert the new string
805         pos_type pos = cur.selEnd().pos();
806         Paragraph & par = cur.selEnd().paragraph();
807         docstring::const_iterator cit = str.begin();
808         docstring::const_iterator end = str.end();
809         for (; cit != end; ++cit, ++pos)
810                 par.insertChar(pos, *cit, font, cur.buffer().params().trackChanges);
811
812         // Cut the selection
813         cutSelection(cur, true, false);
814
815         // select the replacement
816         if (backwards) {
817                 selbeg.pos() += str.length();
818                 cur.setSelection(selbeg, -int(str.length()));
819         } else
820                 cur.setSelection(selbeg, str.length());
821 }
822
823
824 void replaceSelection(Cursor & cur)
825 {
826         if (cur.selection())
827                 cutSelection(cur, true, false);
828 }
829
830
831 void eraseSelection(Cursor & cur)
832 {
833         //lyxerr << "cap::eraseSelection begin: " << cur << endl;
834         CursorSlice const & i1 = cur.selBegin();
835         CursorSlice const & i2 = cur.selEnd();
836         if (i1.inset().asInsetMath()) {
837                 saveSelection(cur);
838                 cur.top() = i1;
839                 if (i1.idx() == i2.idx()) {
840                         i1.cell().erase(i1.pos(), i2.pos());
841                         // We may have deleted i1.cell(cur.pos()).
842                         // Make sure that pos is valid.
843                         if (cur.pos() > cur.lastpos())
844                                 cur.pos() = cur.lastpos();
845                 } else {
846                         InsetMath * p = i1.asInsetMath();
847                         Inset::row_type r1, r2;
848                         Inset::col_type c1, c2;
849                         region(i1, i2, r1, r2, c1, c2);
850                         for (Inset::row_type row = r1; row <= r2; ++row)
851                                 for (Inset::col_type col = c1; col <= c2; ++col)
852                                         p->cell(p->index(row, col)).clear();
853                         // We've deleted the whole cell. Only pos 0 is valid.
854                         cur.pos() = 0;
855                 }
856                 // need a valid cursor. (Lgb)
857                 cur.clearSelection();
858         } else {
859                 lyxerr << "can't erase this selection 1" << endl;
860         }
861         //lyxerr << "cap::eraseSelection end: " << cur << endl;
862 }
863
864
865 void selDel(Cursor & cur)
866 {
867         //lyxerr << "cap::selDel" << endl;
868         if (cur.selection())
869                 eraseSelection(cur);
870 }
871
872
873 void selClearOrDel(Cursor & cur)
874 {
875         //lyxerr << "cap::selClearOrDel" << endl;
876         if (lyxrc.auto_region_delete)
877                 selDel(cur);
878         else
879                 cur.selection() = false;
880 }
881
882
883 docstring grabSelection(Cursor const & cur)
884 {
885         if (!cur.selection())
886                 return docstring();
887
888         // FIXME: What is wrong with the following?
889 #if 0
890         std::ostringstream os;
891         for (DocIterator dit = cur.selectionBegin();
892              dit != cur.selectionEnd(); dit.forwardPos())
893                 os << asString(dit.cell());
894         return os.str();
895 #endif
896
897         CursorSlice i1 = cur.selBegin();
898         CursorSlice i2 = cur.selEnd();
899
900         if (i1.idx() == i2.idx()) {
901                 if (i1.inset().asInsetMath()) {
902                         MathData::const_iterator it = i1.cell().begin();
903                         return asString(MathData(it + i1.pos(), it + i2.pos()));
904                 } else {
905                         return from_ascii("unknown selection 1");
906                 }
907         }
908
909         Inset::row_type r1, r2;
910         Inset::col_type c1, c2;
911         region(i1, i2, r1, r2, c1, c2);
912
913         docstring data;
914         if (i1.inset().asInsetMath()) {
915                 for (Inset::row_type row = r1; row <= r2; ++row) {
916                         if (row > r1)
917                                 data += "\\\\";
918                         for (Inset::col_type col = c1; col <= c2; ++col) {
919                                 if (col > c1)
920                                         data += '&';
921                                 data += asString(i1.asInsetMath()->
922                                         cell(i1.asInsetMath()->index(row, col)));
923                         }
924                 }
925         } else {
926                 data = from_ascii("unknown selection 2");
927         }
928         return data;
929 }
930
931
932 void dirtyTabularStack(bool b)
933 {
934         dirty_tabular_stack_ = b;
935 }
936
937
938 bool tabularStackDirty()
939 {
940         return dirty_tabular_stack_;
941 }
942
943
944 } // namespace cap
945
946 } // namespace lyx