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