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