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