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