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