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