]> git.lyx.org Git - lyx.git/blob - src/CutAndPaste.cpp
Cleanup: Replace a bunch of Cursor arguments with DocIterators.
[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, Text const & text,
434         pit_type startpit, pit_type endpit,
435         int start, int end, DocumentClass const * const dc, CutStack & cutstack)
436 {
437         ParagraphList const & pars = text.paragraphs();
438
439         LASSERT(0 <= start && start <= pars[startpit].size(), /**/);
440         LASSERT(0 <= end && end <= pars[endpit].size(), /**/);
441         LASSERT(startpit != endpit || start <= end, /**/);
442
443         // Clone the paragraphs within the selection.
444         ParagraphList copy_pars(boost::next(pars.begin(), startpit),
445                                 boost::next(pars.begin(), endpit + 1));
446
447         // Remove the end of the last paragraph; afterwards, remove the
448         // beginning of the first paragraph. Keep this order - there may only
449         // be one paragraph!  Do not track deletions here; this is an internal
450         // action not visible to the user
451
452         Paragraph & back = copy_pars.back();
453         back.eraseChars(end, back.size(), false);
454         Paragraph & front = copy_pars.front();
455         front.eraseChars(0, start, false);
456
457         ParagraphList::iterator it = copy_pars.begin();
458         ParagraphList::iterator it_end = copy_pars.end();
459
460         for (; it != it_end; it++) {
461                 // Since we have a copy of the paragraphs, the insets
462                 // do not have a proper buffer reference. It makes
463                 // sense to add them temporarily, because the
464                 // operations below depend on that (acceptChanges included).
465                 it->setBuffer(const_cast<Buffer &>(buf));
466                 // PassThru paragraphs have the Language
467                 // latex_language. This is invalid for others, so we
468                 // need to change it to the buffer language.
469                 if (text.inset().getLayout().isPassThru())
470                         it->changeLanguage(buf.params(), 
471                                            latex_language, buf.language());
472         }
473
474         // do not copy text (also nested in insets) which is marked as
475         // deleted, unless the whole selection was deleted
476         if (!isFullyDeleted(copy_pars))
477                 acceptChanges(copy_pars, buf.params());
478
479
480         // do some final cleanup now, to make sure that the paragraphs
481         // are not linked to something else.
482         it = copy_pars.begin();
483         for (; it != it_end; it++) {
484                 it->setBuffer(*static_cast<Buffer *>(0));
485                 it->setInsetOwner(0);
486         }
487
488         DocumentClass * d = const_cast<DocumentClass *>(dc);
489         cutstack.push(make_pair(copy_pars, d));
490 }
491
492 } // namespace anon
493
494
495
496
497 namespace cap {
498
499 void region(CursorSlice const & i1, CursorSlice const & i2,
500             Inset::row_type & r1, Inset::row_type & r2,
501             Inset::col_type & c1, Inset::col_type & c2)
502 {
503         Inset & p = i1.inset();
504         c1 = p.col(i1.idx());
505         c2 = p.col(i2.idx());
506         if (c1 > c2)
507                 swap(c1, c2);
508         r1 = p.row(i1.idx());
509         r2 = p.row(i2.idx());
510         if (r1 > r2)
511                 swap(r1, r2);
512 }
513
514
515 docstring grabAndEraseSelection(Cursor & cur)
516 {
517         if (!cur.selection())
518                 return docstring();
519         docstring res = grabSelection(cur);
520         eraseSelection(cur);
521         return res;
522 }
523
524
525 bool reduceSelectionToOneCell(Cursor & cur)
526 {
527         if (!cur.selection() || !cur.inMathed())
528                 return false;
529
530         CursorSlice i1 = cur.selBegin();
531         CursorSlice i2 = cur.selEnd();
532         if (!i1.inset().asInsetMath())
533                 return false;
534
535         // the easy case: do nothing if only one cell is selected
536         if (i1.idx() == i2.idx())
537                 return true;
538         
539         cur.top().pos() = 0;
540         cur.resetAnchor();
541         cur.top().pos() = cur.top().lastpos();
542         
543         return true;
544 }
545
546
547 bool multipleCellsSelected(Cursor const & cur)
548 {
549         if (!cur.selection() || !cur.inMathed())
550                 return false;
551         
552         CursorSlice i1 = cur.selBegin();
553         CursorSlice i2 = cur.selEnd();
554         if (!i1.inset().asInsetMath())
555                 return false;
556         
557         if (i1.idx() == i2.idx())
558                 return false;
559         
560         return true;
561 }
562
563
564 void switchBetweenClasses(DocumentClass const * const oldone, 
565                 DocumentClass const * const newone, InsetText & in, ErrorList & errorlist)
566 {
567         errorlist.clear();
568
569         LASSERT(!in.paragraphs().empty(), /**/);
570         if (oldone == newone)
571                 return;
572         
573         DocumentClass const & oldtc = *oldone;
574         DocumentClass const & newtc = *newone;
575
576         // layouts
577         ParIterator end = par_iterator_end(in);
578         for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
579                 docstring const name = it->layout().name();
580
581                 // the pasted text will keep their own layout name. If this layout does
582                 // not exist in the new document, it will behave like a standard layout.
583                 newtc.addLayoutIfNeeded(name);
584
585                 if (in.usePlainLayout())
586                         it->setLayout(newtc.plainLayout());
587                 else
588                         it->setLayout(newtc[name]);
589         }
590
591         // character styles
592         InsetIterator const i_end = inset_iterator_end(in);
593         for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
594                 if (it->lyxCode() != FLEX_CODE)
595                         // FIXME: Should we verify all InsetCollapsable?
596                         continue;
597                 if (!it->undefined())
598                         continue;
599                 // The flex inset is undefined in newtc
600                 docstring const s = bformat(_(
601                         "Flex inset %1$s is "
602                         "undefined because of class "
603                         "conversion from\n%2$s to %3$s"),
604                         it->name(), from_utf8(oldtc.name()),
605                         from_utf8(newtc.name()));
606                 // To warn the user that something had to be done.
607                 errorlist.push_back(ErrorItem(
608                                 _("Undefined flex inset"),
609                                 s, it.paragraph().id(), it.pos(), it.pos() + 1));
610         }
611 }
612
613
614 vector<docstring> availableSelections(Buffer const * buf)
615 {
616         vector<docstring> selList;
617         if (!buf)
618                 return selList;
619
620         CutStack::const_iterator cit = theCuts.begin();
621         CutStack::const_iterator end = theCuts.end();
622         for (; cit != end; ++cit) {
623                 // we do not use cit-> here because gcc 2.9x does not
624                 // like it (JMarc)
625                 ParagraphList const & pars = (*cit).first;
626                 docstring asciiSel;
627                 ParagraphList::const_iterator pit = pars.begin();
628                 ParagraphList::const_iterator pend = pars.end();
629                 for (; pit != pend; ++pit) {
630                         Paragraph par(*pit, 0, 26);
631                         // adapt paragraph to current buffer.
632                         par.setBuffer(const_cast<Buffer &>(*buf));
633                         asciiSel += par.asString(AS_STR_INSETS);
634                         if (asciiSel.size() > 25) {
635                                 asciiSel.replace(22, docstring::npos,
636                                                  from_ascii("..."));
637                                 break;
638                         }
639                 }
640
641                 selList.push_back(asciiSel);
642         }
643
644         return selList;
645 }
646
647
648 size_type numberOfSelections()
649 {
650         return theCuts.size();
651 }
652
653
654 void cutSelection(Cursor & cur, bool doclear, bool realcut)
655 {
656         // This doesn't make sense, if there is no selection
657         if (!cur.selection())
658                 return;
659
660         // OK, we have a selection. This is always between cur.selBegin()
661         // and cur.selEnd()
662
663         if (cur.inTexted()) {
664                 Text * text = cur.text();
665                 LASSERT(text, /**/);
666
667                 saveSelection(cur);
668
669                 // make sure that the depth behind the selection are restored, too
670                 cur.recordUndoSelection();
671                 pit_type begpit = cur.selBegin().pit();
672                 pit_type endpit = cur.selEnd().pit();
673
674                 int endpos = cur.selEnd().pos();
675
676                 BufferParams const & bp = cur.buffer()->params();
677                 if (realcut) {
678                         copySelectionHelper(*cur.buffer(),
679                                 *text,
680                                 begpit, endpit,
681                                 cur.selBegin().pos(), endpos,
682                                 bp.documentClassPtr(), theCuts);
683                         // Stuff what we got on the clipboard.
684                         // Even if there is no selection.
685                         putClipboard(theCuts[0].first, theCuts[0].second,
686                                 cur.selectionAsString(true));
687                 }
688
689                 if (begpit != endpit)
690                         cur.updateFlags(Update::Force | Update::FitCursor);
691
692                 boost::tie(endpit, endpos) =
693                         eraseSelectionHelper(bp,
694                                 text->paragraphs(),
695                                 begpit, endpit,
696                                 cur.selBegin().pos(), endpos);
697
698                 // cutSelection can invalidate the cursor so we need to set
699                 // it anew. (Lgb)
700                 // we prefer the end for when tracking changes
701                 cur.pos() = endpos;
702                 cur.pit() = endpit;
703
704                 // sometimes necessary
705                 if (doclear
706                         && text->paragraphs()[begpit].stripLeadingSpaces(bp.trackChanges))
707                         cur.fixIfBroken();
708
709                 // need a valid cursor. (Lgb)
710                 cur.clearSelection();
711                 cur.buffer()->updateLabels();
712
713                 // tell tabular that a recent copy happened
714                 dirtyTabularStack(false);
715         }
716
717         if (cur.inMathed()) {
718                 if (cur.selBegin().idx() != cur.selEnd().idx()) {
719                         // The current selection spans more than one cell.
720                         // Record all cells
721                         cur.recordUndoInset();
722                 } else {
723                         // Record only the current cell to avoid a jumping
724                         // cursor after undo
725                         cur.recordUndo();
726                 }
727                 if (realcut)
728                         copySelection(cur);
729                 eraseSelection(cur);
730         }
731 }
732
733
734 void copySelection(Cursor const & cur)
735 {
736         copySelection(cur, cur.selectionAsString(true));
737 }
738
739
740 void copyInset(Cursor const & cur, Inset * inset, docstring const & plaintext)
741 {
742         ParagraphList pars;
743         Paragraph par;
744         BufferParams const & bp = cur.buffer()->params();
745         par.setLayout(bp.documentClass().plainLayout());
746         par.insertInset(0, inset, Change(Change::UNCHANGED));
747         pars.push_back(par);
748         theCuts.push(make_pair(pars, bp.documentClassPtr()));
749
750         // stuff the selection onto the X clipboard, from an explicit copy request
751         putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
752 }
753
754 namespace {
755
756 void copySelectionToStack(Cursor const & cur, CutStack & cutstack)
757 {
758         // this doesn't make sense, if there is no selection
759         if (!cur.selection())
760                 return;
761
762         // copySelection can not yet handle the case of cross idx selection
763         if (cur.selBegin().idx() != cur.selEnd().idx())
764                 return;
765
766         if (cur.inTexted()) {
767                 Text * text = cur.text();
768                 LASSERT(text, /**/);
769                 // ok we have a selection. This is always between cur.selBegin()
770                 // and sel_end cursor
771
772                 // copy behind a space if there is one
773                 ParagraphList & pars = text->paragraphs();
774                 pos_type pos = cur.selBegin().pos();
775                 pit_type par = cur.selBegin().pit();
776                 while (pos < pars[par].size() &&
777                        pars[par].isLineSeparator(pos) &&
778                        (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
779                         ++pos;
780
781                 copySelectionHelper(*cur.buffer(), *text, par, cur.selEnd().pit(),
782                         pos, cur.selEnd().pos(), 
783                         cur.buffer()->params().documentClassPtr(), cutstack);
784
785                 // Reset the dirty_tabular_stack_ flag only when something
786                 // is copied to the clipboard (not to the selectionBuffer).
787                 if (&cutstack == &theCuts)
788                         dirtyTabularStack(false);
789         }
790
791         if (cur.inMathed()) {
792                 //lyxerr << "copySelection in mathed" << endl;
793                 ParagraphList pars;
794                 Paragraph par;
795                 BufferParams const & bp = cur.buffer()->params();
796                 // FIXME This should be the plain layout...right?
797                 par.setLayout(bp.documentClass().plainLayout());
798                 par.insert(0, grabSelection(cur), Font(), Change(Change::UNCHANGED));
799                 pars.push_back(par);
800                 cutstack.push(make_pair(pars, bp.documentClassPtr()));
801         }
802 }
803
804 }
805
806
807 void copySelectionToStack()
808 {
809         if (!selectionBuffer.empty())
810                 theCuts.push(selectionBuffer[0]);
811 }
812
813
814 void copySelection(Cursor const & cur, docstring const & plaintext)
815 {
816         // In tablemode, because copy and paste actually use special table stack
817         // we do not attempt to get selected paragraphs under cursor. Instead, a
818         // paragraph with the plain text version is generated so that table cells
819         // can be pasted as pure text somewhere else.
820         if (cur.selBegin().idx() != cur.selEnd().idx()) {
821                 ParagraphList pars;
822                 Paragraph par;
823                 BufferParams const & bp = cur.buffer()->params();
824                 par.setLayout(bp.documentClass().plainLayout());
825                 par.insert(0, plaintext, Font(), Change(Change::UNCHANGED));
826                 pars.push_back(par);
827                 theCuts.push(make_pair(pars, bp.documentClassPtr()));
828         } else {
829                 copySelectionToStack(cur, theCuts);
830         }
831
832         // stuff the selection onto the X clipboard, from an explicit copy request
833         putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
834 }
835
836
837 void saveSelection(Cursor const & cur)
838 {
839         // This function is called, not when a selection is formed, but when
840         // a selection is cleared. Therefore, multiple keyboard selection
841         // will not repeatively trigger this function (bug 3877).
842         if (cur.selection() 
843             && cur.selBegin() == cur.bv().cursor().selBegin()
844             && cur.selEnd() == cur.bv().cursor().selEnd()) {
845                 LYXERR(Debug::SELECTION, "saveSelection: '" << cur.selectionAsString(true) << "'");
846                 copySelectionToStack(cur, selectionBuffer);
847         }
848 }
849
850
851 bool selection()
852 {
853         return !selectionBuffer.empty();
854 }
855
856
857 void clearSelection()
858 {
859         selectionBuffer.clear();
860 }
861
862
863 void clearCutStack()
864 {
865         theCuts.clear();
866 }
867
868
869 docstring selection(size_t sel_index)
870 {
871         return sel_index < theCuts.size()
872                 ? theCuts[sel_index].first.back().asString(AS_STR_INSETS | AS_STR_NEWLINES)
873                 : docstring();
874 }
875
876
877 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
878                         DocumentClass const * const docclass, ErrorList & errorList)
879 {
880         if (cur.inTexted()) {
881                 Text * text = cur.text();
882                 LASSERT(text, /**/);
883
884                 pit_type endpit;
885                 PitPosPair ppp;
886
887                 boost::tie(ppp, endpit) =
888                         pasteSelectionHelper(cur, parlist, docclass, errorList);
889                 cur.buffer()->updateLabels();
890                 cur.clearSelection();
891                 text->setCursor(cur, ppp.first, ppp.second);
892         }
893
894         // mathed is handled in InsetMathNest/InsetMathGrid
895         LASSERT(!cur.inMathed(), /**/);
896 }
897
898
899 void pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
900 {
901         // this does not make sense, if there is nothing to paste
902         if (!checkPastePossible(sel_index))
903                 return;
904
905         cur.recordUndo();
906         pasteParagraphList(cur, theCuts[sel_index].first,
907                            theCuts[sel_index].second, errorList);
908         cur.setSelection();
909 }
910
911
912 void pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs)
913 {
914         // Use internal clipboard if it is the most recent one
915         if (theClipboard().isInternal()) {
916                 pasteFromStack(cur, errorList, 0);
917                 return;
918         }
919
920         // First try LyX format
921         if (theClipboard().hasLyXContents()) {
922                 string lyx = theClipboard().getAsLyX();
923                 if (!lyx.empty()) {
924                         // For some strange reason gcc 3.2 and 3.3 do not accept
925                         // Buffer buffer(string(), false);
926                         Buffer buffer("", false);
927                         buffer.setUnnamed(true);
928                         if (buffer.readString(lyx)) {
929                                 cur.recordUndo();
930                                 pasteParagraphList(cur, buffer.paragraphs(),
931                                         buffer.params().documentClassPtr(), errorList);
932                                 cur.setSelection();
933                                 return;
934                         }
935                 }
936         }
937
938         // Then try plain text
939         docstring const text = theClipboard().getAsText();
940         if (text.empty())
941                 return;
942         cur.recordUndo();
943         if (asParagraphs)
944                 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
945         else
946                 cur.text()->insertStringAsLines(cur, text, cur.current_font);
947 }
948
949
950 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
951                             Clipboard::GraphicsType preferedType)
952 {
953         LASSERT(theClipboard().hasGraphicsContents(preferedType), /**/);
954
955         // get picture from clipboard
956         FileName filename = theClipboard().getAsGraphics(cur, preferedType);
957         if (filename.empty())
958                 return;
959
960         // create inset for graphic
961         InsetGraphics * inset = new InsetGraphics(*cur.buffer());
962         InsetGraphicsParams params;
963         params.filename = support::DocFileName(filename.absFilename());
964         inset->setParams(params);
965         cur.recordUndo();
966         cur.insert(inset);
967 }
968
969
970 void pasteSelection(Cursor & cur, ErrorList & errorList)
971 {
972         if (selectionBuffer.empty())
973                 return;
974         cur.recordUndo();
975         pasteParagraphList(cur, selectionBuffer[0].first,
976                            selectionBuffer[0].second, errorList);
977 }
978
979
980 void replaceSelectionWithString(Cursor & cur, docstring const & str, bool backwards)
981 {
982         cur.recordUndo();
983         DocIterator selbeg = cur.selectionBegin();
984
985         // Get font setting before we cut, we need a copy here, not a bare reference.
986         Font const font =
987                 selbeg.paragraph().getFontSettings(cur.buffer()->params(), selbeg.pos());
988
989         // Insert the new string
990         pos_type pos = cur.selEnd().pos();
991         Paragraph & par = cur.selEnd().paragraph();
992         docstring::const_iterator cit = str.begin();
993         docstring::const_iterator end = str.end();
994         for (; cit != end; ++cit, ++pos)
995                 par.insertChar(pos, *cit, font, cur.buffer()->params().trackChanges);
996
997         // Cut the selection
998         cutSelection(cur, true, false);
999
1000         // select the replacement
1001         if (backwards) {
1002                 selbeg.pos() += str.length();
1003                 cur.setSelection(selbeg, -int(str.length()));
1004         } else
1005                 cur.setSelection(selbeg, str.length());
1006 }
1007
1008
1009 void replaceSelection(Cursor & cur)
1010 {
1011         if (cur.selection())
1012                 cutSelection(cur, true, false);
1013 }
1014
1015
1016 void eraseSelection(Cursor & cur)
1017 {
1018         //lyxerr << "cap::eraseSelection begin: " << cur << endl;
1019         CursorSlice const & i1 = cur.selBegin();
1020         CursorSlice const & i2 = cur.selEnd();
1021         if (i1.inset().asInsetMath()) {
1022                 saveSelection(cur);
1023                 cur.top() = i1;
1024                 if (i1.idx() == i2.idx()) {
1025                         i1.cell().erase(i1.pos(), i2.pos());
1026                         // We may have deleted i1.cell(cur.pos()).
1027                         // Make sure that pos is valid.
1028                         if (cur.pos() > cur.lastpos())
1029                                 cur.pos() = cur.lastpos();
1030                 } else {
1031                         InsetMath * p = i1.asInsetMath();
1032                         Inset::row_type r1, r2;
1033                         Inset::col_type c1, c2;
1034                         region(i1, i2, r1, r2, c1, c2);
1035                         for (Inset::row_type row = r1; row <= r2; ++row)
1036                                 for (Inset::col_type col = c1; col <= c2; ++col)
1037                                         p->cell(p->index(row, col)).clear();
1038                         // We've deleted the whole cell. Only pos 0 is valid.
1039                         cur.pos() = 0;
1040                 }
1041                 // need a valid cursor. (Lgb)
1042                 cur.clearSelection();
1043         } else {
1044                 lyxerr << "can't erase this selection 1" << endl;
1045         }
1046         //lyxerr << "cap::eraseSelection end: " << cur << endl;
1047 }
1048
1049
1050 void selDel(Cursor & cur)
1051 {
1052         //lyxerr << "cap::selDel" << endl;
1053         if (cur.selection())
1054                 eraseSelection(cur);
1055 }
1056
1057
1058 void selClearOrDel(Cursor & cur)
1059 {
1060         //lyxerr << "cap::selClearOrDel" << endl;
1061         if (lyxrc.auto_region_delete)
1062                 selDel(cur);
1063         else
1064                 cur.setSelection(false);
1065 }
1066
1067
1068 docstring grabSelection(Cursor const & cur)
1069 {
1070         if (!cur.selection())
1071                 return docstring();
1072
1073 #if 0
1074         // grab selection by glueing multiple cells together. This is not what
1075         // we want because selections spanning multiple cells will get "&" and "\\"
1076         // seperators.
1077         ostringstream os;
1078         for (DocIterator dit = cur.selectionBegin();
1079              dit != cur.selectionEnd(); dit.forwardPos())
1080                 os << asString(dit.cell());
1081         return os.str();
1082 #endif
1083
1084         CursorSlice i1 = cur.selBegin();
1085         CursorSlice i2 = cur.selEnd();
1086
1087         if (i1.idx() == i2.idx()) {
1088                 if (i1.inset().asInsetMath()) {
1089                         MathData::const_iterator it = i1.cell().begin();
1090                         return asString(MathData(it + i1.pos(), it + i2.pos()));
1091                 } else {
1092                         return from_ascii("unknown selection 1");
1093                 }
1094         }
1095
1096         Inset::row_type r1, r2;
1097         Inset::col_type c1, c2;
1098         region(i1, i2, r1, r2, c1, c2);
1099
1100         docstring data;
1101         if (i1.inset().asInsetMath()) {
1102                 for (Inset::row_type row = r1; row <= r2; ++row) {
1103                         if (row > r1)
1104                                 data += "\\\\";
1105                         for (Inset::col_type col = c1; col <= c2; ++col) {
1106                                 if (col > c1)
1107                                         data += '&';
1108                                 data += asString(i1.asInsetMath()->
1109                                         cell(i1.asInsetMath()->index(row, col)));
1110                         }
1111                 }
1112         } else {
1113                 data = from_ascii("unknown selection 2");
1114         }
1115         return data;
1116 }
1117
1118
1119 void dirtyTabularStack(bool b)
1120 {
1121         dirty_tabular_stack_ = b;
1122 }
1123
1124
1125 bool tabularStackDirty()
1126 {
1127         return dirty_tabular_stack_;
1128 }
1129
1130
1131 } // namespace cap
1132 } // namespace lyx