]> git.lyx.org Git - lyx.git/blob - src/CutAndPaste.cpp
Name change CharStyle -> Flex
[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/InsetFlex.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)
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                 bool const merge = pars[pit].isMergedOnEndOfParDeletion(params.trackChanges);
308
309                 // Logically erase only, including the end-of-paragraph character
310                 pars[pit].eraseChars(left, right, params.trackChanges);
311
312                 // Separate handling of paragraph break:
313                 if (merge && pit != endpit &&
314                     (pit + 1 != endpit || pars[pit].hasSameLayout(pars[endpit]))) {
315                         if (pit + 1 == endpit)
316                                 endpos += pars[pit].size();
317                         mergeParagraph(params, pars, pit);
318                         --endpit;
319                 } else
320                         ++pit;
321         }
322
323         // Ensure legal cursor pos:
324         endpit = startpit;
325         endpos = startpos;
326         return PitPosPair(endpit, endpos);
327 }
328
329
330 void putClipboard(ParagraphList const & paragraphs, TextClass_ptr textclass,
331                   docstring const & plaintext)
332 {
333         // For some strange reason gcc 3.2 and 3.3 do not accept
334         // Buffer buffer(string(), false);
335         Buffer buffer("", false);
336         buffer.setUnnamed(true);
337         buffer.paragraphs() = paragraphs;
338         buffer.params().setTextClass(textclass);
339         std::ostringstream lyx;
340         if (buffer.write(lyx))
341                 theClipboard().put(lyx.str(), plaintext);
342         else
343                 theClipboard().put(string(), plaintext);
344 }
345
346
347 void copySelectionHelper(Buffer const & buf, ParagraphList & pars,
348         pit_type startpit, pit_type endpit,
349         int start, int end, TextClass_ptr tc, CutStack & cutstack)
350 {
351         BOOST_ASSERT(0 <= start && start <= pars[startpit].size());
352         BOOST_ASSERT(0 <= end && end <= pars[endpit].size());
353         BOOST_ASSERT(startpit != endpit || start <= end);
354
355         // Clone the paragraphs within the selection.
356         ParagraphList copy_pars(boost::next(pars.begin(), startpit),
357                                 boost::next(pars.begin(), endpit + 1));
358
359         // Remove the end of the last paragraph; afterwards, remove the
360         // beginning of the first paragraph. Keep this order - there may only
361         // be one paragraph!  Do not track deletions here; this is an internal
362         // action not visible to the user
363
364         Paragraph & back = copy_pars.back();
365         back.eraseChars(end, back.size(), false);
366         Paragraph & front = copy_pars.front();
367         front.eraseChars(0, start, false);
368
369         ParagraphList::iterator it = copy_pars.begin();
370         ParagraphList::iterator it_end = copy_pars.end();
371
372         for (; it != it_end; it++) {
373                 // ERT paragraphs have the Language latex_language.
374                 // This is invalid outside of ERT, so we need to change it
375                 // to the buffer language.
376                 if (it->ownerCode() == Inset::ERT_CODE || it->ownerCode() == Inset::LISTINGS_CODE) {
377                         it->changeLanguage(buf.params(), latex_language,
378                                            buf.getLanguage());
379                 }
380                 it->setInsetOwner(0);
381         }
382
383         // do not copy text (also nested in insets) which is marked as deleted
384         acceptChanges(copy_pars, buf.params());
385
386         cutstack.push(make_pair(copy_pars, tc));
387 }
388
389 } // namespace anon
390
391
392
393
394 namespace cap {
395
396 docstring grabAndEraseSelection(Cursor & cur)
397 {
398         if (!cur.selection())
399                 return docstring();
400         docstring res = grabSelection(cur);
401         eraseSelection(cur);
402         return res;
403 }
404
405
406 void switchBetweenClasses(TextClass_ptr const & c1, 
407         TextClass_ptr const & c2, InsetText & in, ErrorList & errorlist)
408 {
409         errorlist.clear();
410
411         BOOST_ASSERT(!in.paragraphs().empty());
412         if (c1 == c2)
413                 return;
414         
415         TextClass const & tclass1 = *c1;
416         TextClass const & tclass2 = *c2;
417
418         // layouts
419         ParIterator end = par_iterator_end(in);
420         for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
421                 docstring const name = it->layout()->name();
422                 bool hasLayout = tclass2.hasLayout(name);
423
424                 if (hasLayout)
425                         it->layout(tclass2[name]);
426                 else
427                         it->layout(tclass2.defaultLayout());
428
429                 if (!hasLayout && name != tclass1.defaultLayoutName()) {
430                         docstring const s = bformat(
431                                                  _("Layout had to be changed from\n%1$s to %2$s\n"
432                                                 "because of class conversion from\n%3$s to %4$s"),
433                          name, it->layout()->name(),
434                          from_utf8(tclass1.name()), from_utf8(tclass2.name()));
435                         // To warn the user that something had to be done.
436                         errorlist.push_back(ErrorItem(_("Changed Layout"), s,
437                                                       it->id(), 0,
438                                                       it->size()));
439                 }
440         }
441
442         // character styles
443         InsetIterator const i_end = inset_iterator_end(in);
444         for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
445                 if (it->lyxCode() == Inset::FLEX_CODE) {
446                         InsetFlex & inset =
447                                 static_cast<InsetFlex &>(*it);
448                         string const name = inset.params().name;
449                         InsetLayout const il = 
450                                 tclass2.insetlayout(from_utf8(name));
451                         inset.setLayout(il);
452                         if (il.labelstring == from_utf8("UNDEFINED")) {
453                                 // The flex inset is undefined in tclass2
454                                 docstring const s = bformat(_(
455                                         "Flex inset %1$s is "
456                                         "undefined because of class "
457                                         "conversion from\n%2$s to %3$s"),
458                                          from_utf8(name), from_utf8(tclass1.name()),
459                                          from_utf8(tclass2.name()));
460                                 // To warn the user that something had to be done.
461                                 errorlist.push_back(ErrorItem(
462                                         _("Undefined flex inset"),
463                                         s, it.paragraph().id(), it.pos(), it.pos() + 1));
464                         } 
465                 }
466         }
467 }
468
469
470 std::vector<docstring> const availableSelections(Buffer const & buffer)
471 {
472         vector<docstring> selList;
473
474         CutStack::const_iterator cit = theCuts.begin();
475         CutStack::const_iterator end = theCuts.end();
476         for (; cit != end; ++cit) {
477                 // we do not use cit-> here because gcc 2.9x does not
478                 // like it (JMarc)
479                 ParagraphList const & pars = (*cit).first;
480                 docstring asciiSel;
481                 ParagraphList::const_iterator pit = pars.begin();
482                 ParagraphList::const_iterator pend = pars.end();
483                 for (; pit != pend; ++pit) {
484                         asciiSel += pit->asString(buffer, false);
485                         if (asciiSel.size() > 25) {
486                                 asciiSel.replace(22, docstring::npos,
487                                                  from_ascii("..."));
488                                 break;
489                         }
490                 }
491
492                 selList.push_back(asciiSel);
493         }
494
495         return selList;
496 }
497
498
499 size_type numberOfSelections()
500 {
501         return theCuts.size();
502 }
503
504
505 void cutSelection(Cursor & cur, bool doclear, bool realcut)
506 {
507         // This doesn't make sense, if there is no selection
508         if (!cur.selection())
509                 return;
510
511         // OK, we have a selection. This is always between cur.selBegin()
512         // and cur.selEnd()
513
514         if (cur.inTexted()) {
515                 Text * text = cur.text();
516                 BOOST_ASSERT(text);
517
518                 saveSelection(cur);
519
520                 // make sure that the depth behind the selection are restored, too
521                 recordUndoSelection(cur);
522                 pit_type begpit = cur.selBegin().pit();
523                 pit_type endpit = cur.selEnd().pit();
524
525                 int endpos = cur.selEnd().pos();
526
527                 BufferParams const & bp = cur.buffer().params();
528                 if (realcut) {
529                         copySelectionHelper(cur.buffer(),
530                                 text->paragraphs(),
531                                 begpit, endpit,
532                                 cur.selBegin().pos(), endpos,
533                                 bp.getTextClass_ptr(), theCuts);
534                         // Stuff what we got on the clipboard.
535                         // Even if there is no selection.
536                         putClipboard(theCuts[0].first, theCuts[0].second,
537                                 cur.selectionAsString(true));
538                 }
539
540                 boost::tie(endpit, endpos) =
541                         eraseSelectionHelper(bp,
542                                 text->paragraphs(),
543                                 begpit, endpit,
544                                 cur.selBegin().pos(), endpos);
545
546                 // cutSelection can invalidate the cursor so we need to set
547                 // it anew. (Lgb)
548                 // we prefer the end for when tracking changes
549                 cur.pos() = endpos;
550                 cur.pit() = endpit;
551
552                 // sometimes necessary
553                 if (doclear
554                         && text->paragraphs()[begpit].stripLeadingSpaces(bp.trackChanges))
555                         cur.fixIfBroken();
556
557                 // need a valid cursor. (Lgb)
558                 cur.clearSelection();
559                 updateLabels(cur.buffer());
560
561                 // tell tabular that a recent copy happened
562                 dirtyTabularStack(false);
563         }
564
565         if (cur.inMathed()) {
566                 if (cur.selBegin().idx() != cur.selEnd().idx()) {
567                         // The current selection spans more than one cell.
568                         // Record all cells
569                         recordUndoInset(cur);
570                 } else {
571                         // Record only the current cell to avoid a jumping
572                         // cursor after undo
573                         recordUndo(cur);
574                 }
575                 if (realcut)
576                         copySelection(cur);
577                 eraseSelection(cur);
578         }
579 }
580
581
582 void copySelection(Cursor & cur)
583 {
584         copySelection(cur, cur.selectionAsString(true));
585 }
586
587
588 namespace {
589
590 void copySelectionToStack(Cursor & cur, CutStack & cutstack)
591 {
592         // this doesn't make sense, if there is no selection
593         if (!cur.selection())
594                 return;
595
596         // copySelection can not yet handle the case of cross idx selection
597         if (cur.selBegin().idx() != cur.selEnd().idx())
598                 return;
599
600         if (cur.inTexted()) {
601                 Text * text = cur.text();
602                 BOOST_ASSERT(text);
603                 // ok we have a selection. This is always between cur.selBegin()
604                 // and sel_end cursor
605
606                 // copy behind a space if there is one
607                 ParagraphList & pars = text->paragraphs();
608                 pos_type pos = cur.selBegin().pos();
609                 pit_type par = cur.selBegin().pit();
610                 while (pos < pars[par].size() &&
611                        pars[par].isLineSeparator(pos) &&
612                        (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
613                         ++pos;
614
615                 copySelectionHelper(cur.buffer(), pars, par, cur.selEnd().pit(),
616                         pos, cur.selEnd().pos(), 
617                         cur.buffer().params().getTextClass_ptr(), cutstack);
618                 dirtyTabularStack(false);
619         }
620
621         if (cur.inMathed()) {
622                 //lyxerr << "copySelection in mathed" << endl;
623                 ParagraphList pars;
624                 Paragraph par;
625                 BufferParams const & bp = cur.buffer().params();
626                 par.layout(bp.getTextClass().defaultLayout());
627                 par.insert(0, grabSelection(cur), Font(), Change(Change::UNCHANGED));
628                 pars.push_back(par);
629                 cutstack.push(make_pair(pars, bp.getTextClass_ptr()));
630         }
631 }
632
633 }
634
635
636 void copySelectionToStack()
637 {
638         if (!selectionBuffer.empty())
639                 theCuts.push(selectionBuffer[0]);
640 }
641
642
643 void copySelection(Cursor & cur, docstring const & plaintext)
644 {
645         // In tablemode, because copy and paste actually use special table stack
646         // we do not attemp to get selected paragraphs under cursor. Instead, a
647         // paragraph with the plain text version is generated so that table cells
648         // can be pasted as pure text somewhere else.
649         if (cur.selBegin().idx() != cur.selEnd().idx()) {
650                 ParagraphList pars;
651                 Paragraph par;
652                 BufferParams const & bp = cur.buffer().params();
653                 par.layout(bp.getTextClass().defaultLayout());
654                 par.insert(0, plaintext, Font(), Change(Change::UNCHANGED));
655                 pars.push_back(par);
656                 theCuts.push(make_pair(pars, bp.getTextClass_ptr()));
657         } else
658                 copySelectionToStack(cur, theCuts);
659
660         // stuff the selection onto the X clipboard, from an explicit copy request
661         putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
662 }
663
664
665 void saveSelection(Cursor & cur)
666 {
667         // This function is called, not when a selection is formed, but when
668         // a selection is cleared. Therefore, multiple keyboard selection
669         // will not repeatively trigger this function (bug 3877).
670         if (cur.selection() 
671             && cur.selBegin() == cur.bv().cursor().selBegin()
672             && cur.selEnd() == cur.bv().cursor().selEnd()) {
673                 LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION << ": `"
674                            << to_utf8(cur.selectionAsString(true)) << "'."
675                            << endl;
676                 copySelectionToStack(cur, selectionBuffer);
677         }
678 }
679
680
681 bool selection()
682 {
683         return !selectionBuffer.empty();
684 }
685
686
687 void clearSelection()
688 {
689         selectionBuffer.clear();
690 }
691
692
693 docstring getSelection(Buffer const & buf, size_t sel_index)
694 {
695         return sel_index < theCuts.size()
696                 ? theCuts[sel_index].first.back().asString(buf, false)
697                 : docstring();
698 }
699
700
701 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
702                         TextClass_ptr textclass, ErrorList & errorList)
703 {
704         if (cur.inTexted()) {
705                 Text * text = cur.text();
706                 BOOST_ASSERT(text);
707
708                 pit_type endpit;
709                 PitPosPair ppp;
710
711                 boost::tie(ppp, endpit) =
712                         pasteSelectionHelper(cur, parlist,
713                                              textclass, errorList);
714                 updateLabels(cur.buffer());
715                 cur.clearSelection();
716                 text->setCursor(cur, ppp.first, ppp.second);
717         }
718
719         // mathed is handled in InsetMathNest/InsetMathGrid
720         BOOST_ASSERT(!cur.inMathed());
721 }
722
723
724 void pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
725 {
726         // this does not make sense, if there is nothing to paste
727         if (!checkPastePossible(sel_index))
728                 return;
729
730         recordUndo(cur);
731         pasteParagraphList(cur, theCuts[sel_index].first,
732                            theCuts[sel_index].second, errorList);
733         cur.setSelection();
734 }
735
736
737 void pasteClipboard(Cursor & cur, ErrorList & errorList, bool asParagraphs)
738 {
739         // Use internal clipboard if it is the most recent one
740         if (theClipboard().isInternal()) {
741                 pasteFromStack(cur, errorList, 0);
742                 return;
743         }
744
745         // First try LyX format
746         if (theClipboard().hasLyXContents()) {
747                 string lyx = theClipboard().getAsLyX();
748                 if (!lyx.empty()) {
749                         // For some strange reason gcc 3.2 and 3.3 do not accept
750                         // Buffer buffer(string(), false);
751                         Buffer buffer("", false);
752                         buffer.setUnnamed(true);
753                         if (buffer.readString(lyx)) {
754                                 recordUndo(cur);
755                                 pasteParagraphList(cur, buffer.paragraphs(),
756                                         buffer.params().getTextClass_ptr(), errorList);
757                                 cur.setSelection();
758                                 return;
759                         }
760                 }
761         }
762
763         // Then try plain text
764         docstring const text = theClipboard().getAsText();
765         if (text.empty())
766                 return;
767         recordUndo(cur);
768         if (asParagraphs)
769                 cur.text()->insertStringAsParagraphs(cur, text);
770         else
771                 cur.text()->insertStringAsLines(cur, text);
772 }
773
774
775 void pasteSelection(Cursor & cur, ErrorList & errorList)
776 {
777         if (selectionBuffer.empty())
778                 return;
779         recordUndo(cur);
780         pasteParagraphList(cur, selectionBuffer[0].first,
781                            selectionBuffer[0].second, errorList);
782 }
783
784
785 void replaceSelectionWithString(Cursor & cur, docstring const & str, bool backwards)
786 {
787         recordUndo(cur);
788         DocIterator selbeg = cur.selectionBegin();
789
790         // Get font setting before we cut
791         Font const font =
792                 selbeg.paragraph().getFontSettings(cur.buffer().params(), selbeg.pos());
793
794         // Insert the new string
795         pos_type pos = cur.selEnd().pos();
796         Paragraph & par = cur.selEnd().paragraph();
797         docstring::const_iterator cit = str.begin();
798         docstring::const_iterator end = str.end();
799         for (; cit != end; ++cit, ++pos)
800                 par.insertChar(pos, *cit, font, cur.buffer().params().trackChanges);
801
802         // Cut the selection
803         cutSelection(cur, true, false);
804
805         // select the replacement
806         if (backwards) {
807                 selbeg.pos() += str.length();
808                 cur.setSelection(selbeg, -int(str.length()));
809         } else
810                 cur.setSelection(selbeg, str.length());
811 }
812
813
814 void replaceSelection(Cursor & cur)
815 {
816         if (cur.selection())
817                 cutSelection(cur, true, false);
818 }
819
820
821 void eraseSelection(Cursor & cur)
822 {
823         //lyxerr << "cap::eraseSelection begin: " << cur << endl;
824         CursorSlice const & i1 = cur.selBegin();
825         CursorSlice const & i2 = cur.selEnd();
826         if (i1.inset().asInsetMath()) {
827                 saveSelection(cur);
828                 cur.top() = i1;
829                 if (i1.idx() == i2.idx()) {
830                         i1.cell().erase(i1.pos(), i2.pos());
831                         // We may have deleted i1.cell(cur.pos()).
832                         // Make sure that pos is valid.
833                         if (cur.pos() > cur.lastpos())
834                                 cur.pos() = cur.lastpos();
835                 } else {
836                         InsetMath * p = i1.asInsetMath();
837                         Inset::row_type r1, r2;
838                         Inset::col_type c1, c2;
839                         region(i1, i2, r1, r2, c1, c2);
840                         for (Inset::row_type row = r1; row <= r2; ++row)
841                                 for (Inset::col_type col = c1; col <= c2; ++col)
842                                         p->cell(p->index(row, col)).clear();
843                         // We've deleted the whole cell. Only pos 0 is valid.
844                         cur.pos() = 0;
845                 }
846                 // need a valid cursor. (Lgb)
847                 cur.clearSelection();
848         } else {
849                 lyxerr << "can't erase this selection 1" << endl;
850         }
851         //lyxerr << "cap::eraseSelection end: " << cur << endl;
852 }
853
854
855 void selDel(Cursor & cur)
856 {
857         //lyxerr << "cap::selDel" << endl;
858         if (cur.selection())
859                 eraseSelection(cur);
860 }
861
862
863 void selClearOrDel(Cursor & cur)
864 {
865         //lyxerr << "cap::selClearOrDel" << endl;
866         if (lyxrc.auto_region_delete)
867                 selDel(cur);
868         else
869                 cur.selection() = false;
870 }
871
872
873 docstring grabSelection(Cursor const & cur)
874 {
875         if (!cur.selection())
876                 return docstring();
877
878         // FIXME: What is wrong with the following?
879 #if 0
880         std::ostringstream os;
881         for (DocIterator dit = cur.selectionBegin();
882              dit != cur.selectionEnd(); dit.forwardPos())
883                 os << asString(dit.cell());
884         return os.str();
885 #endif
886
887         CursorSlice i1 = cur.selBegin();
888         CursorSlice i2 = cur.selEnd();
889
890         if (i1.idx() == i2.idx()) {
891                 if (i1.inset().asInsetMath()) {
892                         MathData::const_iterator it = i1.cell().begin();
893                         return asString(MathData(it + i1.pos(), it + i2.pos()));
894                 } else {
895                         return from_ascii("unknown selection 1");
896                 }
897         }
898
899         Inset::row_type r1, r2;
900         Inset::col_type c1, c2;
901         region(i1, i2, r1, r2, c1, c2);
902
903         docstring data;
904         if (i1.inset().asInsetMath()) {
905                 for (Inset::row_type row = r1; row <= r2; ++row) {
906                         if (row > r1)
907                                 data += "\\\\";
908                         for (Inset::col_type col = c1; col <= c2; ++col) {
909                                 if (col > c1)
910                                         data += '&';
911                                 data += asString(i1.asInsetMath()->
912                                         cell(i1.asInsetMath()->index(row, col)));
913                         }
914                 }
915         } else {
916                 data = from_ascii("unknown selection 2");
917         }
918         return data;
919 }
920
921
922 void dirtyTabularStack(bool b)
923 {
924         dirty_tabular_stack_ = b;
925 }
926
927
928 bool tabularStackDirty()
929 {
930         return dirty_tabular_stack_;
931 }
932
933
934 } // namespace cap
935
936 } // namespace lyx