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