]> git.lyx.org Git - lyx.git/blob - src/CutAndPaste.cpp
Refactor Undo/Redo framework into an Undo class owned by a Buffer. This reduces heade...
[lyx.git] / src / CutAndPaste.cpp
1 /*
2  * \file CutAndPaste.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Jürgen Vigna
7  * \author Lars Gullik Bjønnes
8  * \author Alfredo Braunstein
9  * \author Michael Gerz
10  *
11  * Full author contact details are available in file CREDITS.
12  */
13
14 #include <config.h>
15
16 #include "CutAndPaste.h"
17
18 #include "Buffer.h"
19 #include "buffer_funcs.h"
20 #include "BufferParams.h"
21 #include "BufferView.h"
22 #include "Cursor.h"
23 #include "debug.h"
24 #include "ErrorList.h"
25 #include "FuncRequest.h"
26 #include "gettext.h"
27 #include "InsetIterator.h"
28 #include "Language.h"
29 #include "lfuns.h"
30 #include "LyXFunc.h"
31 #include "LyXRC.h"
32 #include "Text.h"
33 #include "TextClassList.h"
34 #include "Paragraph.h"
35 #include "paragraph_funcs.h"
36 #include "ParagraphParameters.h"
37 #include "ParIterator.h"
38 #include "Undo.h"
39
40 #include "insets/InsetFlex.h"
41 #include "insets/InsetTabular.h"
42
43 #include "mathed/MathData.h"
44 #include "mathed/InsetMath.h"
45 #include "mathed/MathSupport.h"
46
47 #include "support/lstrings.h"
48
49 #include "frontends/Clipboard.h"
50 #include "frontends/Selection.h"
51
52 #include <boost/current_function.hpp>
53 #include <boost/tuple/tuple.hpp>
54 #include <boost/next_prior.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, TextClassPtr> > 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                      TextClassPtr 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         TextClassPtr const tc = buffer.params().getTextClassPtr();
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() == ERT_CODE ||
134                 pars[pit].inInset()->lyxCode() == 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 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, TextClassPtr 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, TextClassPtr 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() == ERT_CODE || it->ownerCode() == 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(TextClassPtr const & c1, 
407         TextClassPtr 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() == 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                 cur.recordUndoSelection();
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.getTextClassPtr(), 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                         cur.recordUndoInset();
570                 } else {
571                         // Record only the current cell to avoid a jumping
572                         // cursor after undo
573                         cur.recordUndo();
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().getTextClassPtr(), 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.getTextClassPtr()));
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.getTextClassPtr()));
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 void clearCutStack()
694 {
695         theCuts.clear();
696 }
697
698
699 docstring getSelection(Buffer const & buf, size_t sel_index)
700 {
701         return sel_index < theCuts.size()
702                 ? theCuts[sel_index].first.back().asString(buf, false)
703                 : docstring();
704 }
705
706
707 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
708                         TextClassPtr textclass, ErrorList & errorList)
709 {
710         if (cur.inTexted()) {
711                 Text * text = cur.text();
712                 BOOST_ASSERT(text);
713
714                 pit_type endpit;
715                 PitPosPair ppp;
716
717                 boost::tie(ppp, endpit) =
718                         pasteSelectionHelper(cur, parlist,
719                                              textclass, errorList);
720                 updateLabels(cur.buffer());
721                 cur.clearSelection();
722                 text->setCursor(cur, ppp.first, ppp.second);
723         }
724
725         // mathed is handled in InsetMathNest/InsetMathGrid
726         BOOST_ASSERT(!cur.inMathed());
727 }
728
729
730 void pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
731 {
732         // this does not make sense, if there is nothing to paste
733         if (!checkPastePossible(sel_index))
734                 return;
735
736         cur.recordUndo();
737         pasteParagraphList(cur, theCuts[sel_index].first,
738                            theCuts[sel_index].second, errorList);
739         cur.setSelection();
740 }
741
742
743 void pasteClipboard(Cursor & cur, ErrorList & errorList, bool asParagraphs)
744 {
745         // Use internal clipboard if it is the most recent one
746         if (theClipboard().isInternal()) {
747                 pasteFromStack(cur, errorList, 0);
748                 return;
749         }
750
751         // First try LyX format
752         if (theClipboard().hasLyXContents()) {
753                 string lyx = theClipboard().getAsLyX();
754                 if (!lyx.empty()) {
755                         // For some strange reason gcc 3.2 and 3.3 do not accept
756                         // Buffer buffer(string(), false);
757                         Buffer buffer("", false);
758                         buffer.setUnnamed(true);
759                         if (buffer.readString(lyx)) {
760                                 cur.recordUndo();
761                                 pasteParagraphList(cur, buffer.paragraphs(),
762                                         buffer.params().getTextClassPtr(), errorList);
763                                 cur.setSelection();
764                                 return;
765                         }
766                 }
767         }
768
769         // Then try plain text
770         docstring const text = theClipboard().getAsText();
771         if (text.empty())
772                 return;
773         cur.recordUndo();
774         if (asParagraphs)
775                 cur.text()->insertStringAsParagraphs(cur, text);
776         else
777                 cur.text()->insertStringAsLines(cur, text);
778 }
779
780
781 void pasteSelection(Cursor & cur, ErrorList & errorList)
782 {
783         if (selectionBuffer.empty())
784                 return;
785         cur.recordUndo();
786         pasteParagraphList(cur, selectionBuffer[0].first,
787                            selectionBuffer[0].second, errorList);
788 }
789
790
791 void replaceSelectionWithString(Cursor & cur, docstring const & str, bool backwards)
792 {
793         cur.recordUndo();
794         DocIterator selbeg = cur.selectionBegin();
795
796         // Get font setting before we cut
797         Font const font =
798                 selbeg.paragraph().getFontSettings(cur.buffer().params(), selbeg.pos());
799
800         // Insert the new string
801         pos_type pos = cur.selEnd().pos();
802         Paragraph & par = cur.selEnd().paragraph();
803         docstring::const_iterator cit = str.begin();
804         docstring::const_iterator end = str.end();
805         for (; cit != end; ++cit, ++pos)
806                 par.insertChar(pos, *cit, font, cur.buffer().params().trackChanges);
807
808         // Cut the selection
809         cutSelection(cur, true, false);
810
811         // select the replacement
812         if (backwards) {
813                 selbeg.pos() += str.length();
814                 cur.setSelection(selbeg, -int(str.length()));
815         } else
816                 cur.setSelection(selbeg, str.length());
817 }
818
819
820 void replaceSelection(Cursor & cur)
821 {
822         if (cur.selection())
823                 cutSelection(cur, true, false);
824 }
825
826
827 void eraseSelection(Cursor & cur)
828 {
829         //lyxerr << "cap::eraseSelection begin: " << cur << endl;
830         CursorSlice const & i1 = cur.selBegin();
831         CursorSlice const & i2 = cur.selEnd();
832         if (i1.inset().asInsetMath()) {
833                 saveSelection(cur);
834                 cur.top() = i1;
835                 if (i1.idx() == i2.idx()) {
836                         i1.cell().erase(i1.pos(), i2.pos());
837                         // We may have deleted i1.cell(cur.pos()).
838                         // Make sure that pos is valid.
839                         if (cur.pos() > cur.lastpos())
840                                 cur.pos() = cur.lastpos();
841                 } else {
842                         InsetMath * p = i1.asInsetMath();
843                         Inset::row_type r1, r2;
844                         Inset::col_type c1, c2;
845                         region(i1, i2, r1, r2, c1, c2);
846                         for (Inset::row_type row = r1; row <= r2; ++row)
847                                 for (Inset::col_type col = c1; col <= c2; ++col)
848                                         p->cell(p->index(row, col)).clear();
849                         // We've deleted the whole cell. Only pos 0 is valid.
850                         cur.pos() = 0;
851                 }
852                 // need a valid cursor. (Lgb)
853                 cur.clearSelection();
854         } else {
855                 lyxerr << "can't erase this selection 1" << endl;
856         }
857         //lyxerr << "cap::eraseSelection end: " << cur << endl;
858 }
859
860
861 void selDel(Cursor & cur)
862 {
863         //lyxerr << "cap::selDel" << endl;
864         if (cur.selection())
865                 eraseSelection(cur);
866 }
867
868
869 void selClearOrDel(Cursor & cur)
870 {
871         //lyxerr << "cap::selClearOrDel" << endl;
872         if (lyxrc.auto_region_delete)
873                 selDel(cur);
874         else
875                 cur.selection() = false;
876 }
877
878
879 docstring grabSelection(Cursor const & cur)
880 {
881         if (!cur.selection())
882                 return docstring();
883
884         // FIXME: What is wrong with the following?
885 #if 0
886         std::ostringstream os;
887         for (DocIterator dit = cur.selectionBegin();
888              dit != cur.selectionEnd(); dit.forwardPos())
889                 os << asString(dit.cell());
890         return os.str();
891 #endif
892
893         CursorSlice i1 = cur.selBegin();
894         CursorSlice i2 = cur.selEnd();
895
896         if (i1.idx() == i2.idx()) {
897                 if (i1.inset().asInsetMath()) {
898                         MathData::const_iterator it = i1.cell().begin();
899                         return asString(MathData(it + i1.pos(), it + i2.pos()));
900                 } else {
901                         return from_ascii("unknown selection 1");
902                 }
903         }
904
905         Inset::row_type r1, r2;
906         Inset::col_type c1, c2;
907         region(i1, i2, r1, r2, c1, c2);
908
909         docstring data;
910         if (i1.inset().asInsetMath()) {
911                 for (Inset::row_type row = r1; row <= r2; ++row) {
912                         if (row > r1)
913                                 data += "\\\\";
914                         for (Inset::col_type col = c1; col <= c2; ++col) {
915                                 if (col > c1)
916                                         data += '&';
917                                 data += asString(i1.asInsetMath()->
918                                         cell(i1.asInsetMath()->index(row, col)));
919                         }
920                 }
921         } else {
922                 data = from_ascii("unknown selection 2");
923         }
924         return data;
925 }
926
927
928 void dirtyTabularStack(bool b)
929 {
930         dirty_tabular_stack_ = b;
931 }
932
933
934 bool tabularStackDirty()
935 {
936         return dirty_tabular_stack_;
937 }
938
939
940 } // namespace cap
941
942 } // namespace lyx