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