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