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