]> git.lyx.org Git - lyx.git/blob - src/CutAndPaste.cpp
add new lyx funcs introduced in r34598 to doxy
[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 "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/updateBuffer 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/updateBuffer 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 updateBuffer() 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         else
543                 rejectChanges(copy_pars, buf.params());
544
545
546         // do some final cleanup now, to make sure that the paragraphs
547         // are not linked to something else.
548         it = copy_pars.begin();
549         for (; it != it_end; it++) {
550                 it->setBuffer(*static_cast<Buffer *>(0));
551                 it->setInsetOwner(0);
552         }
553
554         DocumentClass * d = const_cast<DocumentClass *>(dc);
555         cutstack.push(make_pair(copy_pars, d));
556 }
557
558 } // namespace anon
559
560
561
562
563 namespace cap {
564
565 void region(CursorSlice const & i1, CursorSlice const & i2,
566             Inset::row_type & r1, Inset::row_type & r2,
567             Inset::col_type & c1, Inset::col_type & c2)
568 {
569         Inset & p = i1.inset();
570         c1 = p.col(i1.idx());
571         c2 = p.col(i2.idx());
572         if (c1 > c2)
573                 swap(c1, c2);
574         r1 = p.row(i1.idx());
575         r2 = p.row(i2.idx());
576         if (r1 > r2)
577                 swap(r1, r2);
578 }
579
580
581 docstring grabAndEraseSelection(Cursor & cur)
582 {
583         if (!cur.selection())
584                 return docstring();
585         docstring res = grabSelection(cur);
586         eraseSelection(cur);
587         return res;
588 }
589
590
591 bool reduceSelectionToOneCell(Cursor & cur)
592 {
593         if (!cur.selection() || !cur.inMathed())
594                 return false;
595
596         CursorSlice i1 = cur.selBegin();
597         CursorSlice i2 = cur.selEnd();
598         if (!i1.inset().asInsetMath())
599                 return false;
600
601         // the easy case: do nothing if only one cell is selected
602         if (i1.idx() == i2.idx())
603                 return true;
604         
605         cur.top().pos() = 0;
606         cur.resetAnchor();
607         cur.top().pos() = cur.top().lastpos();
608         
609         return true;
610 }
611
612
613 bool multipleCellsSelected(Cursor const & cur)
614 {
615         if (!cur.selection() || !cur.inMathed())
616                 return false;
617         
618         CursorSlice i1 = cur.selBegin();
619         CursorSlice i2 = cur.selEnd();
620         if (!i1.inset().asInsetMath())
621                 return false;
622         
623         if (i1.idx() == i2.idx())
624                 return false;
625         
626         return true;
627 }
628
629
630 void switchBetweenClasses(DocumentClass const * const oldone, 
631                 DocumentClass const * const newone, InsetText & in, ErrorList & errorlist)
632 {
633         errorlist.clear();
634
635         LASSERT(!in.paragraphs().empty(), /**/);
636         if (oldone == newone)
637                 return;
638         
639         DocumentClass const & oldtc = *oldone;
640         DocumentClass const & newtc = *newone;
641
642         // layouts
643         ParIterator end = par_iterator_end(in);
644         for (ParIterator it = par_iterator_begin(in); it != end; ++it) {
645                 docstring const name = it->layout().name();
646
647                 // the pasted text will keep their own layout name. If this layout does
648                 // not exist in the new document, it will behave like a standard layout.
649                 newtc.addLayoutIfNeeded(name);
650
651                 if (in.usePlainLayout())
652                         it->setLayout(newtc.plainLayout());
653                 else
654                         it->setLayout(newtc[name]);
655         }
656
657         // character styles
658         InsetIterator const i_end = inset_iterator_end(in);
659         for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
660                 if (it->lyxCode() != FLEX_CODE)
661                         // FIXME: Should we verify all InsetCollapsable?
662                         continue;
663                 docstring const & n = newone->insetLayout(it->name()).name();
664                 bool const is_undefined = n.empty() ||
665                         n == DocumentClass::plainInsetLayout().name();
666                 if (!is_undefined)
667                         continue;
668                 // The flex inset is undefined in newtc
669                 docstring const s = bformat(_(
670                         "Flex inset %1$s is "
671                         "undefined because of class "
672                         "conversion from\n%2$s to %3$s"),
673                         it->name(), from_utf8(oldtc.name()),
674                         from_utf8(newtc.name()));
675                 // To warn the user that something had to be done.
676                 errorlist.push_back(ErrorItem(
677                                 _("Undefined flex inset"),
678                                 s, it.paragraph().id(), it.pos(), it.pos() + 1));
679         }
680 }
681
682
683 vector<docstring> availableSelections(Buffer const * buf)
684 {
685         vector<docstring> selList;
686         if (!buf)
687                 return selList;
688
689         CutStack::const_iterator cit = theCuts.begin();
690         CutStack::const_iterator end = theCuts.end();
691         for (; cit != end; ++cit) {
692                 // we do not use cit-> here because gcc 2.9x does not
693                 // like it (JMarc)
694                 ParagraphList const & pars = (*cit).first;
695                 docstring asciiSel;
696                 ParagraphList::const_iterator pit = pars.begin();
697                 ParagraphList::const_iterator pend = pars.end();
698                 for (; pit != pend; ++pit) {
699                         Paragraph par(*pit, 0, 26);
700                         // adapt paragraph to current buffer.
701                         par.setBuffer(const_cast<Buffer &>(*buf));
702                         asciiSel += par.asString(AS_STR_INSETS);
703                         if (asciiSel.size() > 25) {
704                                 asciiSel.replace(22, docstring::npos,
705                                                  from_ascii("..."));
706                                 break;
707                         }
708                 }
709
710                 selList.push_back(asciiSel);
711         }
712
713         return selList;
714 }
715
716
717 size_type numberOfSelections()
718 {
719         return theCuts.size();
720 }
721
722
723 void cutSelection(Cursor & cur, bool doclear, bool realcut)
724 {
725         // This doesn't make sense, if there is no selection
726         if (!cur.selection())
727                 return;
728
729         // OK, we have a selection. This is always between cur.selBegin()
730         // and cur.selEnd()
731
732         if (cur.inTexted()) {
733                 Text * text = cur.text();
734                 LASSERT(text, /**/);
735
736                 saveSelection(cur);
737
738                 // make sure that the depth behind the selection are restored, too
739                 cur.recordUndoSelection();
740                 pit_type begpit = cur.selBegin().pit();
741                 pit_type endpit = cur.selEnd().pit();
742
743                 int endpos = cur.selEnd().pos();
744
745                 BufferParams const & bp = cur.buffer()->params();
746                 if (realcut) {
747                         copySelectionHelper(*cur.buffer(),
748                                 *text,
749                                 begpit, endpit,
750                                 cur.selBegin().pos(), endpos,
751                                 bp.documentClassPtr(), theCuts);
752                         // Stuff what we got on the clipboard.
753                         // Even if there is no selection.
754                         putClipboard(theCuts[0].first, theCuts[0].second,
755                                 cur.selectionAsString(true));
756                 }
757
758                 if (begpit != endpit)
759                         cur.updateFlags(Update::Force | Update::FitCursor);
760
761                 boost::tie(endpit, endpos) =
762                         eraseSelectionHelper(bp,
763                                 text->paragraphs(),
764                                 begpit, endpit,
765                                 cur.selBegin().pos(), endpos);
766
767                 // cutSelection can invalidate the cursor so we need to set
768                 // it anew. (Lgb)
769                 // we prefer the end for when tracking changes
770                 cur.pos() = endpos;
771                 cur.pit() = endpit;
772
773                 // sometimes necessary
774                 if (doclear
775                         && text->paragraphs()[begpit].stripLeadingSpaces(bp.trackChanges))
776                         cur.fixIfBroken();
777
778                 // need a valid cursor. (Lgb)
779                 cur.clearSelection();
780                 cur.buffer()->updateBuffer();
781
782                 // tell tabular that a recent copy happened
783                 dirtyTabularStack(false);
784         }
785
786         if (cur.inMathed()) {
787                 if (cur.selBegin().idx() != cur.selEnd().idx()) {
788                         // The current selection spans more than one cell.
789                         // Record all cells
790                         cur.recordUndoInset();
791                 } else {
792                         // Record only the current cell to avoid a jumping
793                         // cursor after undo
794                         cur.recordUndo();
795                 }
796                 if (realcut)
797                         copySelection(cur);
798                 eraseSelection(cur);
799         }
800 }
801
802
803 void copySelection(Cursor const & cur)
804 {
805         copySelection(cur, cur.selectionAsString(true));
806 }
807
808
809 void copyInset(Cursor const & cur, Inset * inset, docstring const & plaintext)
810 {
811         ParagraphList pars;
812         Paragraph par;
813         BufferParams const & bp = cur.buffer()->params();
814         par.setLayout(bp.documentClass().plainLayout());
815         par.insertInset(0, inset, Change(Change::UNCHANGED));
816         pars.push_back(par);
817         theCuts.push(make_pair(pars, bp.documentClassPtr()));
818
819         // stuff the selection onto the X clipboard, from an explicit copy request
820         putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
821 }
822
823 namespace {
824
825 void copySelectionToStack(Cursor const & cur, CutStack & cutstack)
826 {
827         // this doesn't make sense, if there is no selection
828         if (!cur.selection())
829                 return;
830
831         // copySelection can not yet handle the case of cross idx selection
832         if (cur.selBegin().idx() != cur.selEnd().idx())
833                 return;
834
835         if (cur.inTexted()) {
836                 Text * text = cur.text();
837                 LASSERT(text, /**/);
838                 // ok we have a selection. This is always between cur.selBegin()
839                 // and sel_end cursor
840
841                 // copy behind a space if there is one
842                 ParagraphList & pars = text->paragraphs();
843                 pos_type pos = cur.selBegin().pos();
844                 pit_type par = cur.selBegin().pit();
845                 while (pos < pars[par].size() &&
846                        pars[par].isLineSeparator(pos) &&
847                        (par != cur.selEnd().pit() || pos < cur.selEnd().pos()))
848                         ++pos;
849
850                 copySelectionHelper(*cur.buffer(), *text, par, cur.selEnd().pit(),
851                         pos, cur.selEnd().pos(), 
852                         cur.buffer()->params().documentClassPtr(), cutstack);
853
854                 // Reset the dirty_tabular_stack_ flag only when something
855                 // is copied to the clipboard (not to the selectionBuffer).
856                 if (&cutstack == &theCuts)
857                         dirtyTabularStack(false);
858         }
859
860         if (cur.inMathed()) {
861                 //lyxerr << "copySelection in mathed" << endl;
862                 ParagraphList pars;
863                 Paragraph par;
864                 BufferParams const & bp = cur.buffer()->params();
865                 // FIXME This should be the plain layout...right?
866                 par.setLayout(bp.documentClass().plainLayout());
867                 par.insert(0, grabSelection(cur), Font(), Change(Change::UNCHANGED));
868                 pars.push_back(par);
869                 cutstack.push(make_pair(pars, bp.documentClassPtr()));
870         }
871 }
872
873 }
874
875
876 void copySelectionToStack()
877 {
878         if (!selectionBuffer.empty())
879                 theCuts.push(selectionBuffer[0]);
880 }
881
882
883 void copySelection(Cursor const & cur, docstring const & plaintext)
884 {
885         // In tablemode, because copy and paste actually use special table stack
886         // we do not attempt to get selected paragraphs under cursor. Instead, a
887         // paragraph with the plain text version is generated so that table cells
888         // can be pasted as pure text somewhere else.
889         if (cur.selBegin().idx() != cur.selEnd().idx()) {
890                 ParagraphList pars;
891                 Paragraph par;
892                 BufferParams const & bp = cur.buffer()->params();
893                 par.setLayout(bp.documentClass().plainLayout());
894                 par.insert(0, plaintext, Font(), Change(Change::UNCHANGED));
895                 pars.push_back(par);
896                 theCuts.push(make_pair(pars, bp.documentClassPtr()));
897         } else {
898                 copySelectionToStack(cur, theCuts);
899         }
900
901         // stuff the selection onto the X clipboard, from an explicit copy request
902         putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
903 }
904
905
906 void saveSelection(Cursor const & cur)
907 {
908         // This function is called, not when a selection is formed, but when
909         // a selection is cleared. Therefore, multiple keyboard selection
910         // will not repeatively trigger this function (bug 3877).
911         if (cur.selection() 
912             && cur.selBegin() == cur.bv().cursor().selBegin()
913             && cur.selEnd() == cur.bv().cursor().selEnd()) {
914                 LYXERR(Debug::SELECTION, "saveSelection: '" << cur.selectionAsString(true) << "'");
915                 copySelectionToStack(cur, selectionBuffer);
916         }
917 }
918
919
920 bool selection()
921 {
922         return !selectionBuffer.empty();
923 }
924
925
926 void clearSelection()
927 {
928         selectionBuffer.clear();
929 }
930
931
932 void clearCutStack()
933 {
934         theCuts.clear();
935 }
936
937
938 docstring selection(size_t sel_index)
939 {
940         return sel_index < theCuts.size()
941                 ? theCuts[sel_index].first.back().asString(AS_STR_INSETS | AS_STR_NEWLINES)
942                 : docstring();
943 }
944
945
946 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
947                         DocumentClass const * const docclass, ErrorList & errorList)
948 {
949         if (cur.inTexted()) {
950                 Text * text = cur.text();
951                 LASSERT(text, /**/);
952
953                 pit_type endpit;
954                 PitPosPair ppp;
955
956                 boost::tie(ppp, endpit) =
957                         pasteSelectionHelper(cur, parlist, docclass, errorList);
958                 cur.buffer()->updateBuffer();
959                 cur.clearSelection();
960                 text->setCursor(cur, ppp.first, ppp.second);
961         }
962
963         // mathed is handled in InsetMathNest/InsetMathGrid
964         LASSERT(!cur.inMathed(), /**/);
965 }
966
967
968 void pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
969 {
970         // this does not make sense, if there is nothing to paste
971         if (!checkPastePossible(sel_index))
972                 return;
973
974         cur.recordUndo();
975         pasteParagraphList(cur, theCuts[sel_index].first,
976                            theCuts[sel_index].second, errorList);
977         cur.setSelection();
978 }
979
980
981 void pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs)
982 {
983         // Use internal clipboard if it is the most recent one
984         if (theClipboard().isInternal()) {
985                 pasteFromStack(cur, errorList, 0);
986                 return;
987         }
988
989         // First try LyX format
990         if (theClipboard().hasLyXContents()) {
991                 string lyx = theClipboard().getAsLyX();
992                 if (!lyx.empty()) {
993                         // For some strange reason gcc 3.2 and 3.3 do not accept
994                         // Buffer buffer(string(), false);
995                         Buffer buffer("", false);
996                         buffer.setUnnamed(true);
997                         if (buffer.readString(lyx)) {
998                                 cur.recordUndo();
999                                 pasteParagraphList(cur, buffer.paragraphs(),
1000                                         buffer.params().documentClassPtr(), errorList);
1001                                 cur.setSelection();
1002                                 return;
1003                         }
1004                 }
1005         }
1006
1007         // Then try plain text
1008         docstring const text = theClipboard().getAsText();
1009         if (text.empty())
1010                 return;
1011         cur.recordUndo();
1012         if (asParagraphs)
1013                 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1014         else
1015                 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1016 }
1017
1018
1019 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
1020                             Clipboard::GraphicsType preferedType)
1021 {
1022         LASSERT(theClipboard().hasGraphicsContents(preferedType), /**/);
1023
1024         // get picture from clipboard
1025         FileName filename = theClipboard().getAsGraphics(cur, preferedType);
1026         if (filename.empty())
1027                 return;
1028
1029         // create inset for graphic
1030         InsetGraphics * inset = new InsetGraphics(cur.buffer());
1031         InsetGraphicsParams params;
1032         params.filename = support::DocFileName(filename.absFileName());
1033         inset->setParams(params);
1034         cur.recordUndo();
1035         cur.insert(inset);
1036 }
1037
1038
1039 void pasteSelection(Cursor & cur, ErrorList & errorList)
1040 {
1041         if (selectionBuffer.empty())
1042                 return;
1043         cur.recordUndo();
1044         pasteParagraphList(cur, selectionBuffer[0].first,
1045                            selectionBuffer[0].second, errorList);
1046 }
1047
1048
1049 void replaceSelectionWithString(Cursor & cur, docstring const & str, bool backwards)
1050 {
1051         cur.recordUndo();
1052         DocIterator selbeg = cur.selectionBegin();
1053
1054         // Get font setting before we cut, we need a copy here, not a bare reference.
1055         Font const font =
1056                 selbeg.paragraph().getFontSettings(cur.buffer()->params(), selbeg.pos());
1057
1058         // Insert the new string
1059         pos_type pos = cur.selEnd().pos();
1060         Paragraph & par = cur.selEnd().paragraph();
1061         docstring::const_iterator cit = str.begin();
1062         docstring::const_iterator end = str.end();
1063         for (; cit != end; ++cit, ++pos)
1064                 par.insertChar(pos, *cit, font, cur.buffer()->params().trackChanges);
1065
1066         // Cut the selection
1067         cutSelection(cur, true, false);
1068
1069         // select the replacement
1070         if (backwards) {
1071                 selbeg.pos() += str.length();
1072                 cur.setSelection(selbeg, -int(str.length()));
1073         } else
1074                 cur.setSelection(selbeg, str.length());
1075 }
1076
1077
1078 void replaceSelection(Cursor & cur)
1079 {
1080         if (cur.selection())
1081                 cutSelection(cur, true, false);
1082 }
1083
1084
1085 void eraseSelection(Cursor & cur)
1086 {
1087         //lyxerr << "cap::eraseSelection begin: " << cur << endl;
1088         CursorSlice const & i1 = cur.selBegin();
1089         CursorSlice const & i2 = cur.selEnd();
1090         if (i1.inset().asInsetMath()) {
1091                 saveSelection(cur);
1092                 cur.top() = i1;
1093                 if (i1.idx() == i2.idx()) {
1094                         i1.cell().erase(i1.pos(), i2.pos());
1095                         // We may have deleted i1.cell(cur.pos()).
1096                         // Make sure that pos is valid.
1097                         if (cur.pos() > cur.lastpos())
1098                                 cur.pos() = cur.lastpos();
1099                 } else {
1100                         InsetMath * p = i1.asInsetMath();
1101                         Inset::row_type r1, r2;
1102                         Inset::col_type c1, c2;
1103                         region(i1, i2, r1, r2, c1, c2);
1104                         for (Inset::row_type row = r1; row <= r2; ++row)
1105                                 for (Inset::col_type col = c1; col <= c2; ++col)
1106                                         p->cell(p->index(row, col)).clear();
1107                         // We've deleted the whole cell. Only pos 0 is valid.
1108                         cur.pos() = 0;
1109                 }
1110                 // need a valid cursor. (Lgb)
1111                 cur.clearSelection();
1112         } else {
1113                 lyxerr << "can't erase this selection 1" << endl;
1114         }
1115         //lyxerr << "cap::eraseSelection end: " << cur << endl;
1116 }
1117
1118
1119 void selDel(Cursor & cur)
1120 {
1121         //lyxerr << "cap::selDel" << endl;
1122         if (cur.selection())
1123                 eraseSelection(cur);
1124 }
1125
1126
1127 void selClearOrDel(Cursor & cur)
1128 {
1129         //lyxerr << "cap::selClearOrDel" << endl;
1130         if (lyxrc.auto_region_delete)
1131                 selDel(cur);
1132         else
1133                 cur.setSelection(false);
1134 }
1135
1136
1137 docstring grabSelection(Cursor const & cur)
1138 {
1139         if (!cur.selection())
1140                 return docstring();
1141
1142 #if 0
1143         // grab selection by glueing multiple cells together. This is not what
1144         // we want because selections spanning multiple cells will get "&" and "\\"
1145         // seperators.
1146         ostringstream os;
1147         for (DocIterator dit = cur.selectionBegin();
1148              dit != cur.selectionEnd(); dit.forwardPos())
1149                 os << asString(dit.cell());
1150         return os.str();
1151 #endif
1152
1153         CursorSlice i1 = cur.selBegin();
1154         CursorSlice i2 = cur.selEnd();
1155
1156         if (i1.idx() == i2.idx()) {
1157                 if (i1.inset().asInsetMath()) {
1158                         MathData::const_iterator it = i1.cell().begin();
1159                         Buffer * buf = cur.buffer();
1160                         return asString(MathData(buf, it + i1.pos(), it + i2.pos()));
1161                 } else {
1162                         return from_ascii("unknown selection 1");
1163                 }
1164         }
1165
1166         Inset::row_type r1, r2;
1167         Inset::col_type c1, c2;
1168         region(i1, i2, r1, r2, c1, c2);
1169
1170         docstring data;
1171         if (i1.inset().asInsetMath()) {
1172                 for (Inset::row_type row = r1; row <= r2; ++row) {
1173                         if (row > r1)
1174                                 data += "\\\\";
1175                         for (Inset::col_type col = c1; col <= c2; ++col) {
1176                                 if (col > c1)
1177                                         data += '&';
1178                                 data += asString(i1.asInsetMath()->
1179                                         cell(i1.asInsetMath()->index(row, col)));
1180                         }
1181                 }
1182         } else {
1183                 data = from_ascii("unknown selection 2");
1184         }
1185         return data;
1186 }
1187
1188
1189 void dirtyTabularStack(bool b)
1190 {
1191         dirty_tabular_stack_ = b;
1192 }
1193
1194
1195 bool tabularStackDirty()
1196 {
1197         return dirty_tabular_stack_;
1198 }
1199
1200
1201 } // namespace cap
1202 } // namespace lyx