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