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