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