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