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