]> git.lyx.org Git - lyx.git/blob - src/CutAndPaste.cpp
Merge branch 'master' of git.lyx.org:lyx
[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/lyxalgo.h"
64 #include "support/TempFile.h"
65 #include "support/unique_ptr.h"
66
67 #include "frontends/alert.h"
68 #include "frontends/Clipboard.h"
69 #include "frontends/Selection.h"
70
71 #include <string>
72 #include <tuple>
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_pit, pos_type r_pos, bool r_nu) :
104           pit(r_pit), pos(r_pos), needupdate(r_nu)
105         {}
106
107         pit_type pit;
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(lyx::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(lyx::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 Buffer * copyToTempBuffer(ParagraphList const & paragraphs, DocumentClassConstPtr docclass)
484 {
485         // This used to need to be static to avoid a memory leak. It no longer needs
486         // to be so, but the alternative is to construct a new one of these (with a
487         // new temporary directory, etc) every time, and then to destroy it. So maybe
488         // it's worth just keeping this one around.
489         // FIXME THREAD
490         static TempFile tempfile("clipboard.internal");
491         tempfile.setAutoRemove(false);
492         static Buffer * staticbuffer = theBufferList().newInternalBuffer(
493                         tempfile.name().absFileName());
494
495         // These two things only really need doing the first time.
496         staticbuffer->setUnnamed(true);
497         staticbuffer->inset().setBuffer(*staticbuffer);
498
499         // Use a clone for the complicated stuff so that we do not need to clean
500         // up in order to avoid a crash.
501         Buffer * buffer = staticbuffer->cloneBufferOnly();
502         LASSERT(buffer, return 0);
503
504         // This needs doing every time.
505         // Since setDocumentClass() causes deletion of the old document class
506         // we need to reset all layout pointers in paragraphs (otherwise they
507         // would be dangling).
508         ParIterator const end = buffer->par_iterator_end();
509         for (ParIterator it = buffer->par_iterator_begin(); it != end; ++it) {
510                 docstring const name = it->layout().name();
511                 if (docclass->hasLayout(name))
512                         it->setLayout((*docclass)[name]);
513                 else
514                         it->setPlainOrDefaultLayout(*docclass);
515         }
516         buffer->params().setDocumentClass(docclass);
517
518         // we will use pasteSelectionHelper to copy the paragraphs into the
519         // temporary Buffer, since it does a lot of things to fix them up.
520         DocIterator dit = doc_iterator_begin(buffer, &buffer->inset());
521         ErrorList el;
522         pasteSelectionHelper(dit, paragraphs, docclass, buffer, el);
523
524         return buffer;
525 }
526
527
528 void putClipboard(ParagraphList const & paragraphs, 
529         DocumentClassConstPtr docclass, docstring const & plaintext)
530 {
531         Buffer * buffer = copyToTempBuffer(paragraphs, docclass);
532         if (!buffer) // already asserted in copyToTempBuffer()
533                 return;
534
535         // We don't want to produce images that are not used. Therefore,
536         // output formulas as MathML. Even if this is not understood by all
537         // applications, the number that can parse it should go up in the future.
538         buffer->params().html_math_output = BufferParams::MathML;
539
540         // Make sure MarkAsExporting is deleted before buffer is
541         {
542                 // The Buffer is being used to export. This is necessary so that the
543                 // updateMacros call will record the needed information.
544                 MarkAsExporting mex(buffer);
545
546                 buffer->updateBuffer(Buffer::UpdateMaster, OutputUpdate);
547                 buffer->updateMacros();
548                 buffer->updateMacroInstances(OutputUpdate);
549
550                 // LyX's own format
551                 string lyx;
552                 ostringstream oslyx;
553                 if (buffer->write(oslyx))
554                         lyx = oslyx.str();
555
556                 // XHTML format
557                 odocstringstream oshtml;
558                 OutputParams runparams(encodings.fromLyXName("utf8"));
559                 // We do not need to produce images, etc.
560                 runparams.dryrun = true;
561                 // We are not interested in errors (bug 8866)
562                 runparams.silent = true;
563                 buffer->writeLyXHTMLSource(oshtml, runparams, Buffer::FullSource);
564
565                 theClipboard().put(lyx, oshtml.str(), plaintext);
566         }
567
568         // Save that memory
569         delete buffer;
570 }
571
572
573 /// return true if the whole ParagraphList is deleted
574 static bool isFullyDeleted(ParagraphList const & pars)
575 {
576         pit_type const pars_size = static_cast<pit_type>(pars.size());
577
578         // check all paragraphs
579         for (pit_type pit = 0; pit < pars_size; ++pit) {
580                 if (!pars[pit].empty())   // prevent assertion failure
581                         if (!pars[pit].isDeleted(0, pars[pit].size()))
582                                 return false;
583         }
584         return true;
585 }
586
587
588 void copySelectionHelper(Buffer const & buf, Text const & text,
589         pit_type startpit, pit_type endpit,
590         int start, int end, DocumentClassConstPtr dc, CutStack & cutstack)
591 {
592         ParagraphList const & pars = text.paragraphs();
593
594         // In most of these cases, we can try to recover.
595         LASSERT(0 <= start, start = 0);
596         LASSERT(start <= pars[startpit].size(), start = pars[startpit].size());
597         LASSERT(0 <= end, end = 0);
598         LASSERT(end <= pars[endpit].size(), end = pars[endpit].size());
599         LASSERT(startpit != endpit || start <= end, return);
600
601         // Clone the paragraphs within the selection.
602         ParagraphList copy_pars(lyx::next(pars.begin(), startpit),
603                                 lyx::next(pars.begin(), endpit + 1));
604
605         // Remove the end of the last paragraph; afterwards, remove the
606         // beginning of the first paragraph. Keep this order - there may only
607         // be one paragraph!  Do not track deletions here; this is an internal
608         // action not visible to the user
609
610         Paragraph & back = copy_pars.back();
611         back.eraseChars(end, back.size(), false);
612         Paragraph & front = copy_pars.front();
613         front.eraseChars(0, start, false);
614
615         ParagraphList::iterator it = copy_pars.begin();
616         ParagraphList::iterator it_end = copy_pars.end();
617
618         for (; it != it_end; ++it) {
619                 // Since we have a copy of the paragraphs, the insets
620                 // do not have a proper buffer reference. It makes
621                 // sense to add them temporarily, because the
622                 // operations below depend on that (acceptChanges included).
623                 it->setBuffer(const_cast<Buffer &>(buf));
624                 // PassThru paragraphs have the Language
625                 // latex_language. This is invalid for others, so we
626                 // need to change it to the buffer language.
627                 if (it->isPassThru())
628                         it->changeLanguage(buf.params(), 
629                                            latex_language, buf.language());
630         }
631
632         // do not copy text (also nested in insets) which is marked as
633         // deleted, unless the whole selection was deleted
634         if (!isFullyDeleted(copy_pars))
635                 acceptChanges(copy_pars, buf.params());
636         else
637                 rejectChanges(copy_pars, buf.params());
638
639
640         // do some final cleanup now, to make sure that the paragraphs
641         // are not linked to something else.
642         it = copy_pars.begin();
643         for (; it != it_end; ++it) {
644                 it->setBuffer(*static_cast<Buffer *>(0));
645                 it->setInsetOwner(0);
646         }
647
648         cutstack.push(make_pair(copy_pars, dc));
649 }
650
651 } // namespace anon
652
653
654
655
656 namespace cap {
657
658 void region(CursorSlice const & i1, CursorSlice const & i2,
659             Inset::row_type & r1, Inset::row_type & r2,
660             Inset::col_type & c1, Inset::col_type & c2)
661 {
662         Inset & p = i1.inset();
663         c1 = p.col(i1.idx());
664         c2 = p.col(i2.idx());
665         if (c1 > c2)
666                 swap(c1, c2);
667         r1 = p.row(i1.idx());
668         r2 = p.row(i2.idx());
669         if (r1 > r2)
670                 swap(r1, r2);
671 }
672
673
674 docstring grabAndEraseSelection(Cursor & cur)
675 {
676         if (!cur.selection())
677                 return docstring();
678         docstring res = grabSelection(cur);
679         eraseSelection(cur);
680         return res;
681 }
682
683
684 bool reduceSelectionToOneCell(Cursor & cur)
685 {
686         if (!cur.selection() || !cur.inMathed())
687                 return false;
688
689         CursorSlice i1 = cur.selBegin();
690         CursorSlice i2 = cur.selEnd();
691         if (!i1.inset().asInsetMath())
692                 return false;
693
694         // the easy case: do nothing if only one cell is selected
695         if (i1.idx() == i2.idx())
696                 return true;
697         
698         cur.top().pos() = 0;
699         cur.resetAnchor();
700         cur.top().pos() = cur.top().lastpos();
701         
702         return true;
703 }
704
705
706 bool multipleCellsSelected(Cursor const & cur)
707 {
708         if (!cur.selection() || !cur.inMathed())
709                 return false;
710         
711         CursorSlice i1 = cur.selBegin();
712         CursorSlice i2 = cur.selEnd();
713         if (!i1.inset().asInsetMath())
714                 return false;
715         
716         if (i1.idx() == i2.idx())
717                 return false;
718         
719         return true;
720 }
721
722
723 void switchBetweenClasses(DocumentClassConstPtr oldone,
724                 DocumentClassConstPtr newone, InsetText & in, ErrorList & errorlist)
725 {
726         errorlist.clear();
727
728         LBUFERR(!in.paragraphs().empty());
729         if (oldone == newone)
730                 return;
731         
732         DocumentClass const & oldtc = *oldone;
733         DocumentClass const & newtc = *newone;
734
735         // layouts
736         ParIterator it = par_iterator_begin(in);
737         ParIterator end = par_iterator_end(in);
738         // for remembering which layouts we've had to add
739         set<docstring> newlayouts;
740         for (; it != end; ++it) {
741                 docstring const name = it->layout().name();
742
743                 // the pasted text will keep their own layout name. If this layout does
744                 // not exist in the new document, it will behave like a standard layout.
745                 bool const added_one = newtc.addLayoutIfNeeded(name);
746                 if (added_one)
747                         newlayouts.insert(name);
748
749                 if (added_one || newlayouts.find(name) != newlayouts.end()) {
750                         // Warn the user.
751                         docstring const s = bformat(_("Layout `%1$s' was not found."), name);
752                         errorlist.push_back(
753                                 ErrorItem(_("Layout Not Found"), s, it->id(), 0, it->size()));
754                 }
755
756                 if (in.usePlainLayout())
757                         it->setLayout(newtc.plainLayout());
758                 else
759                         it->setLayout(newtc[name]);
760         }
761
762         // character styles and hidden table cells
763         InsetIterator const i_end = inset_iterator_end(in);
764         for (InsetIterator it = inset_iterator_begin(in); it != i_end; ++it) {
765                 InsetCode const code = it->lyxCode();
766                 if (code == FLEX_CODE) {
767                         // FIXME: Should we verify all InsetCollapsable?
768                         docstring const layoutName = it->layoutName();
769                         docstring const & n = newone->insetLayout(layoutName).name();
770                         bool const is_undefined = n.empty() ||
771                                 n == DocumentClass::plainInsetLayout().name();
772                         if (!is_undefined)
773                                 continue;
774         
775                         // The flex inset is undefined in newtc
776                         docstring const oldname = from_utf8(oldtc.name());
777                         docstring const newname = from_utf8(newtc.name());
778                         docstring s;
779                         if (oldname == newname)
780                                 s = bformat(_("Flex inset %1$s is undefined after "
781                                         "reloading `%2$s' layout."), layoutName, oldname);
782                         else
783                                 s = bformat(_("Flex inset %1$s is undefined because of "
784                                         "conversion from `%2$s' layout to `%3$s'."),
785                                         layoutName, oldname, newname);
786                         // To warn the user that something had to be done.
787                         errorlist.push_back(ErrorItem(
788                                         _("Undefined flex inset"),
789                                         s, it.paragraph().id(), it.pos(), it.pos() + 1));
790                 } else if (code == TABULAR_CODE) {
791                         // The recursion above does not catch paragraphs in "hidden" cells,
792                         // i.e., ones that are part of a multirow or multicolum. So we need
793                         // to handle those separately.
794                         // This is the cause of bug #9049.
795                         InsetTabular * table = it->asInsetTabular();
796                         table->setLayoutForHiddenCells(newtc);
797                 }
798         }
799 }
800
801
802 vector<docstring> availableSelections(Buffer const * buf)
803 {
804         vector<docstring> selList;
805         if (!buf)
806                 return selList;
807
808         CutStack::const_iterator cit = theCuts.begin();
809         CutStack::const_iterator end = theCuts.end();
810         for (; cit != end; ++cit) {
811                 // we do not use cit-> here because gcc 2.9x does not
812                 // like it (JMarc)
813                 ParagraphList const & pars = (*cit).first;
814                 docstring textSel;
815                 ParagraphList::const_iterator pit = pars.begin();
816                 ParagraphList::const_iterator pend = pars.end();
817                 for (; pit != pend; ++pit) {
818                         Paragraph par(*pit, 0, 46);
819                         // adapt paragraph to current buffer.
820                         par.setBuffer(const_cast<Buffer &>(*buf));
821                         textSel += par.asString(AS_STR_INSETS);
822                         if (textSel.size() > 45) {
823                                 support::truncateWithEllipsis(textSel,45);
824                                 break;
825                         }
826                 }
827                 selList.push_back(textSel);
828         }
829
830         return selList;
831 }
832
833
834 size_type numberOfSelections()
835 {
836         return theCuts.size();
837 }
838
839
840 void cutSelection(Cursor & cur, bool doclear, bool realcut)
841 {
842         // This doesn't make sense, if there is no selection
843         if (!cur.selection())
844                 return;
845
846         // OK, we have a selection. This is always between cur.selBegin()
847         // and cur.selEnd()
848
849         if (cur.inTexted()) {
850                 Text * text = cur.text();
851                 LBUFERR(text);
852
853                 saveSelection(cur);
854
855                 // make sure that the depth behind the selection are restored, too
856                 cur.recordUndoSelection();
857                 pit_type begpit = cur.selBegin().pit();
858                 pit_type endpit = cur.selEnd().pit();
859
860                 int endpos = cur.selEnd().pos();
861
862                 BufferParams const & bp = cur.buffer()->params();
863                 if (realcut) {
864                         copySelectionHelper(*cur.buffer(),
865                                 *text,
866                                 begpit, endpit,
867                                 cur.selBegin().pos(), endpos,
868                                 bp.documentClassPtr(), theCuts);
869                         // Stuff what we got on the clipboard.
870                         // Even if there is no selection.
871                         putClipboard(theCuts[0].first, theCuts[0].second,
872                                 cur.selectionAsString(true));
873                 }
874
875                 if (begpit != endpit)
876                         cur.screenUpdateFlags(Update::Force | Update::FitCursor);
877
878                 tie(endpit, endpos) =
879                         eraseSelectionHelper(bp, text->paragraphs(), begpit, endpit,
880                                              cur.selBegin().pos(), endpos);
881
882                 // cutSelection can invalidate the cursor so we need to set
883                 // it anew. (Lgb)
884                 // we prefer the end for when tracking changes
885                 cur.pos() = endpos;
886                 cur.pit() = endpit;
887
888                 // sometimes necessary
889                 if (doclear
890                         && text->paragraphs()[begpit].stripLeadingSpaces(bp.track_changes))
891                         cur.fixIfBroken();
892
893                 // need a valid cursor. (Lgb)
894                 cur.clearSelection();
895
896                 // After a cut operation, we must make sure that the Buffer is updated
897                 // because some further operation might need updated label information for
898                 // example. So we cannot just use "cur.forceBufferUpdate()" here.
899                 // This fixes #7071.
900                 cur.buffer()->updateBuffer();
901
902                 // tell tabular that a recent copy happened
903                 dirtyTabularStack(false);
904         }
905
906         if (cur.inMathed()) {
907                 if (cur.selBegin().idx() != cur.selEnd().idx()) {
908                         // The current selection spans more than one cell.
909                         // Record all cells
910                         cur.recordUndoInset();
911                 } else {
912                         // Record only the current cell to avoid a jumping
913                         // cursor after undo
914                         cur.recordUndo();
915                 }
916                 if (realcut)
917                         copySelection(cur);
918                 eraseSelection(cur);
919         }
920 }
921
922
923 void copySelection(Cursor const & cur)
924 {
925         copySelection(cur, cur.selectionAsString(true));
926 }
927
928
929 void copyInset(Cursor const & cur, Inset * inset, docstring const & plaintext)
930 {
931         ParagraphList pars;
932         Paragraph par;
933         BufferParams const & bp = cur.buffer()->params();
934         par.setLayout(bp.documentClass().plainLayout());
935         Font font(inherit_font, bp.language);
936         par.insertInset(0, inset, font, Change(Change::UNCHANGED));
937         pars.push_back(par);
938         theCuts.push(make_pair(pars, bp.documentClassPtr()));
939
940         // stuff the selection onto the X clipboard, from an explicit copy request
941         putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
942 }
943
944
945 namespace {
946
947 void copySelectionToStack(Cursor const & cur, CutStack & cutstack)
948 {
949         // this doesn't make sense, if there is no selection
950         if (!cur.selection())
951                 return;
952
953         // copySelection can not yet handle the case of cross idx selection
954         if (cur.selBegin().idx() != cur.selEnd().idx())
955                 return;
956
957         if (cur.inTexted()) {
958                 Text * text = cur.text();
959                 LBUFERR(text);
960                 // ok we have a selection. This is always between cur.selBegin()
961                 // and sel_end cursor
962                 copySelectionHelper(*cur.buffer(), *text,
963                                     cur.selBegin().pit(), cur.selEnd().pit(),
964                                     cur.selBegin().pos(), cur.selEnd().pos(), 
965                                     cur.buffer()->params().documentClassPtr(),
966                                     cutstack);
967                 // Reset the dirty_tabular_stack_ flag only when something
968                 // is copied to the clipboard (not to the selectionBuffer).
969                 if (&cutstack == &theCuts)
970                         dirtyTabularStack(false);
971         }
972
973         if (cur.inMathed()) {
974                 //lyxerr << "copySelection in mathed" << endl;
975                 ParagraphList pars;
976                 Paragraph par;
977                 BufferParams const & bp = cur.buffer()->params();
978                 // FIXME This should be the plain layout...right?
979                 par.setLayout(bp.documentClass().plainLayout());
980                 par.insert(0, grabSelection(cur), Font(), Change(Change::UNCHANGED));
981                 pars.push_back(par);
982                 cutstack.push(make_pair(pars, bp.documentClassPtr()));
983         }
984 }
985
986 }
987
988
989 void copySelectionToStack()
990 {
991         if (!selectionBuffer.empty())
992                 theCuts.push(selectionBuffer[0]);
993 }
994
995
996 void copySelection(Cursor const & cur, docstring const & plaintext)
997 {
998         // In tablemode, because copy and paste actually use special table stack
999         // we do not attempt to get selected paragraphs under cursor. Instead, a
1000         // paragraph with the plain text version is generated so that table cells
1001         // can be pasted as pure text somewhere else.
1002         if (cur.selBegin().idx() != cur.selEnd().idx()) {
1003                 ParagraphList pars;
1004                 Paragraph par;
1005                 BufferParams const & bp = cur.buffer()->params();
1006                 par.setLayout(bp.documentClass().plainLayout());
1007                 par.insert(0, plaintext, Font(), Change(Change::UNCHANGED));
1008                 pars.push_back(par);
1009                 theCuts.push(make_pair(pars, bp.documentClassPtr()));
1010         } else {
1011                 copySelectionToStack(cur, theCuts);
1012         }
1013
1014         // stuff the selection onto the X clipboard, from an explicit copy request
1015         putClipboard(theCuts[0].first, theCuts[0].second, plaintext);
1016 }
1017
1018
1019 void saveSelection(Cursor const & cur)
1020 {
1021         // This function is called, not when a selection is formed, but when
1022         // a selection is cleared. Therefore, multiple keyboard selection
1023         // will not repeatively trigger this function (bug 3877).
1024         if (cur.selection() 
1025             && cur.selBegin() == cur.bv().cursor().selBegin()
1026             && cur.selEnd() == cur.bv().cursor().selEnd()) {
1027                 LYXERR(Debug::SELECTION, "saveSelection: '" << cur.selectionAsString(true) << "'");
1028                 copySelectionToStack(cur, selectionBuffer);
1029         }
1030 }
1031
1032
1033 bool selection()
1034 {
1035         return !selectionBuffer.empty();
1036 }
1037
1038
1039 void clearSelection()
1040 {
1041         selectionBuffer.clear();
1042 }
1043
1044
1045 void clearCutStack()
1046 {
1047         theCuts.clear();
1048 }
1049
1050
1051 docstring selection(size_t sel_index, DocumentClassConstPtr docclass)
1052 {
1053         if (sel_index >= theCuts.size())
1054                 return docstring();
1055
1056         unique_ptr<Buffer> buffer(copyToTempBuffer(theCuts[sel_index].first,
1057                                                    docclass));
1058         if (!buffer)
1059                 return docstring();
1060
1061         return buffer->paragraphs().back().asString(AS_STR_INSETS | AS_STR_NEWLINES);
1062 }
1063
1064
1065 void pasteParagraphList(Cursor & cur, ParagraphList const & parlist,
1066                         DocumentClassConstPtr docclass, ErrorList & errorList)
1067 {
1068         if (cur.inTexted()) {
1069                 Text * text = cur.text();
1070                 LBUFERR(text);
1071
1072                 PasteReturnValue prv =
1073                         pasteSelectionHelper(cur, parlist, docclass, 0, errorList);
1074                 cur.forceBufferUpdate();
1075                 cur.clearSelection();
1076                 text->setCursor(cur, prv.pit, prv.pos);
1077         }
1078
1079         // mathed is handled in InsetMathNest/InsetMathGrid
1080         LATTEST(!cur.inMathed());
1081 }
1082
1083
1084 bool pasteFromStack(Cursor & cur, ErrorList & errorList, size_t sel_index)
1085 {
1086         // this does not make sense, if there is nothing to paste
1087         if (!checkPastePossible(sel_index))
1088                 return false;
1089
1090         cur.recordUndo();
1091         pasteParagraphList(cur, theCuts[sel_index].first,
1092                            theCuts[sel_index].second, errorList);
1093         return true;
1094 }
1095
1096
1097 bool pasteClipboardText(Cursor & cur, ErrorList & errorList, bool asParagraphs,
1098                         Clipboard::TextType type)
1099 {
1100         // Use internal clipboard if it is the most recent one
1101         // This overrides asParagraphs and type on purpose!
1102         if (theClipboard().isInternal())
1103                 return pasteFromStack(cur, errorList, 0);
1104
1105         // First try LyX format
1106         if ((type == Clipboard::LyXTextType ||
1107              type == Clipboard::LyXOrPlainTextType ||
1108              type == Clipboard::AnyTextType) &&
1109             theClipboard().hasTextContents(Clipboard::LyXTextType)) {
1110                 string lyx = theClipboard().getAsLyX();
1111                 if (!lyx.empty()) {
1112                         // For some strange reason gcc 3.2 and 3.3 do not accept
1113                         // Buffer buffer(string(), false);
1114                         Buffer buffer("", false);
1115                         buffer.setUnnamed(true);
1116                         if (buffer.readString(lyx)) {
1117                                 cur.recordUndo();
1118                                 pasteParagraphList(cur, buffer.paragraphs(),
1119                                         buffer.params().documentClassPtr(), errorList);
1120                                 return true;
1121                         }
1122                 }
1123         }
1124
1125         // Then try TeX and HTML
1126         Clipboard::TextType types[2] = {Clipboard::HtmlTextType, Clipboard::LaTeXTextType};
1127         string names[2] = {"html", "latexclipboard"};
1128         for (int i = 0; i < 2; ++i) {
1129                 if (type != types[i] && type != Clipboard::AnyTextType)
1130                         continue;
1131                 bool available = theClipboard().hasTextContents(types[i]);
1132
1133                 // If a specific type was explicitly requested, try to
1134                 // interpret plain text: The user told us that the clipboard
1135                 // contents is in the desired format
1136                 if (!available && type == types[i]) {
1137                         types[i] = Clipboard::PlainTextType;
1138                         available = theClipboard().hasTextContents(types[i]);
1139                 }
1140
1141                 if (available) {
1142                         docstring text = theClipboard().getAsText(types[i]);
1143                         available = !text.empty();
1144                         if (available) {
1145                                 // For some strange reason gcc 3.2 and 3.3 do not accept
1146                                 // Buffer buffer(string(), false);
1147                                 Buffer buffer("", false);
1148                                 buffer.setUnnamed(true);
1149                                 available = buffer.importString(names[i], text, errorList);
1150                                 if (available)
1151                                         available = !buffer.paragraphs().empty();
1152                                 if (available && !buffer.paragraphs()[0].empty()) {
1153                                         cur.recordUndo();
1154                                         pasteParagraphList(cur, buffer.paragraphs(),
1155                                                 buffer.params().documentClassPtr(), errorList);
1156                                         return true;
1157                                 }
1158                         }
1159                 }
1160         }
1161
1162         // Then try plain text
1163         docstring const text = theClipboard().getAsText(Clipboard::PlainTextType);
1164         if (text.empty())
1165                 return false;
1166         cur.recordUndo();
1167         if (asParagraphs)
1168                 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1169         else
1170                 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1171         return true;
1172 }
1173
1174
1175 void pasteSimpleText(Cursor & cur, bool asParagraphs)
1176 {
1177         docstring text;
1178         // Use internal clipboard if it is the most recent one
1179         if (theClipboard().isInternal()) {
1180                 if (!checkPastePossible(0))
1181                         return;
1182
1183                 ParagraphList const & pars = theCuts[0].first;
1184                 ParagraphList::const_iterator it = pars.begin();
1185                 for (; it != pars.end(); ++it) {
1186                         if (it != pars.begin())
1187                                 text += "\n";
1188                         text += (*it).asString();
1189                 }
1190                 asParagraphs = false;
1191         } else {
1192                 // Then try plain text
1193                 text = theClipboard().getAsText(Clipboard::PlainTextType);
1194         }
1195
1196         if (text.empty())
1197                 return;
1198
1199         cur.recordUndo();
1200         cutSelection(cur, true, false);
1201         if (asParagraphs)
1202                 cur.text()->insertStringAsParagraphs(cur, text, cur.current_font);
1203         else
1204                 cur.text()->insertStringAsLines(cur, text, cur.current_font);
1205 }
1206
1207
1208 void pasteClipboardGraphics(Cursor & cur, ErrorList & /* errorList */,
1209                             Clipboard::GraphicsType preferedType)
1210 {
1211         LASSERT(theClipboard().hasGraphicsContents(preferedType), return);
1212
1213         // get picture from clipboard
1214         FileName filename = theClipboard().getAsGraphics(cur, preferedType);
1215         if (filename.empty())
1216                 return;
1217
1218         // create inset for graphic
1219         InsetGraphics * inset = new InsetGraphics(cur.buffer());
1220         InsetGraphicsParams params;
1221         params.filename = support::DocFileName(filename.absFileName(), false);
1222         inset->setParams(params);
1223         cur.recordUndo();
1224         cur.insert(inset);
1225 }
1226
1227
1228 void pasteSelection(Cursor & cur, ErrorList & errorList)
1229 {
1230         if (selectionBuffer.empty())
1231                 return;
1232         cur.recordUndo();
1233         pasteParagraphList(cur, selectionBuffer[0].first,
1234                            selectionBuffer[0].second, errorList);
1235 }
1236
1237
1238 void replaceSelectionWithString(Cursor & cur, docstring const & str)
1239 {
1240         cur.recordUndo();
1241         DocIterator selbeg = cur.selectionBegin();
1242
1243         // Get font setting before we cut, we need a copy here, not a bare reference.
1244         Font const font =
1245                 selbeg.paragraph().getFontSettings(cur.buffer()->params(), selbeg.pos());
1246
1247         // Insert the new string
1248         pos_type pos = cur.selEnd().pos();
1249         Paragraph & par = cur.selEnd().paragraph();
1250         docstring::const_iterator cit = str.begin();
1251         docstring::const_iterator end = str.end();
1252         for (; cit != end; ++cit, ++pos)
1253                 par.insertChar(pos, *cit, font, cur.buffer()->params().track_changes);
1254
1255         // Cut the selection
1256         cutSelection(cur, true, false);
1257 }
1258
1259
1260 void replaceSelection(Cursor & cur)
1261 {
1262         if (cur.selection())
1263                 cutSelection(cur, true, false);
1264 }
1265
1266
1267 void eraseSelection(Cursor & cur)
1268 {
1269         //lyxerr << "cap::eraseSelection begin: " << cur << endl;
1270         CursorSlice const & i1 = cur.selBegin();
1271         CursorSlice const & i2 = cur.selEnd();
1272         if (!i1.asInsetMath()) {
1273                 LYXERR0("Can't erase this selection");
1274                 return;
1275         }
1276
1277         saveSelection(cur);
1278         cur.top() = i1;
1279         InsetMath * p = i1.asInsetMath();
1280         if (i1.idx() == i2.idx()) {
1281                 i1.cell().erase(i1.pos(), i2.pos());
1282                 // We may have deleted i1.cell(cur.pos()).
1283                 // Make sure that pos is valid.
1284                 if (cur.pos() > cur.lastpos())
1285                         cur.pos() = cur.lastpos();
1286         } else if (p->nrows() > 0 && p->ncols() > 0) {
1287                 // This is a grid, delete a nice square region
1288                 Inset::row_type r1, r2;
1289                 Inset::col_type c1, c2;
1290                 region(i1, i2, r1, r2, c1, c2);
1291                 for (Inset::row_type row = r1; row <= r2; ++row)
1292                         for (Inset::col_type col = c1; col <= c2; ++col)
1293                                 p->cell(p->index(row, col)).clear();
1294                 // We've deleted the whole cell. Only pos 0 is valid.
1295                 cur.pos() = 0;
1296         } else {
1297                 Inset::idx_type idx1 = i1.idx();
1298                 Inset::idx_type idx2 = i2.idx();
1299                 if (idx1 > idx2)
1300                         swap(idx1, idx2);
1301                 for (Inset::idx_type idx = idx1 ; idx <= idx2; ++idx)
1302                         p->cell(idx).clear();
1303                 // We've deleted the whole cell. Only pos 0 is valid.
1304                 cur.pos() = 0;
1305         }
1306
1307         // need a valid cursor. (Lgb)
1308         cur.clearSelection();
1309         //lyxerr << "cap::eraseSelection end: " << cur << endl;
1310 }
1311
1312
1313 void selDel(Cursor & cur)
1314 {
1315         //lyxerr << "cap::selDel" << endl;
1316         if (cur.selection())
1317                 eraseSelection(cur);
1318 }
1319
1320
1321 void selClearOrDel(Cursor & cur)
1322 {
1323         //lyxerr << "cap::selClearOrDel" << endl;
1324         if (lyxrc.auto_region_delete)
1325                 selDel(cur);
1326         else
1327                 cur.selection(false);
1328 }
1329
1330
1331 docstring grabSelection(Cursor const & cur)
1332 {
1333         if (!cur.selection())
1334                 return docstring();
1335
1336 #if 0
1337         // grab selection by glueing multiple cells together. This is not what
1338         // we want because selections spanning multiple cells will get "&" and "\\"
1339         // seperators.
1340         ostringstream os;
1341         for (DocIterator dit = cur.selectionBegin();
1342              dit != cur.selectionEnd(); dit.forwardPos())
1343                 os << asString(dit.cell());
1344         return os.str();
1345 #endif
1346
1347         CursorSlice i1 = cur.selBegin();
1348         CursorSlice i2 = cur.selEnd();
1349
1350         if (i1.idx() == i2.idx()) {
1351                 if (i1.inset().asInsetMath()) {
1352                         MathData::const_iterator it = i1.cell().begin();
1353                         Buffer * buf = cur.buffer();
1354                         return asString(MathData(buf, it + i1.pos(), it + i2.pos()));
1355                 } else {
1356                         return from_ascii("unknown selection 1");
1357                 }
1358         }
1359
1360         Inset::row_type r1, r2;
1361         Inset::col_type c1, c2;
1362         region(i1, i2, r1, r2, c1, c2);
1363
1364         docstring data;
1365         if (i1.inset().asInsetMath()) {
1366                 for (Inset::row_type row = r1; row <= r2; ++row) {
1367                         if (row > r1)
1368                                 data += "\\\\";
1369                         for (Inset::col_type col = c1; col <= c2; ++col) {
1370                                 if (col > c1)
1371                                         data += '&';
1372                                 data += asString(i1.asInsetMath()->
1373                                         cell(i1.asInsetMath()->index(row, col)));
1374                         }
1375                 }
1376         } else {
1377                 data = from_ascii("unknown selection 2");
1378         }
1379         return data;
1380 }
1381
1382
1383 void dirtyTabularStack(bool b)
1384 {
1385         dirty_tabular_stack_ = b;
1386 }
1387
1388
1389 bool tabularStackDirty()
1390 {
1391         return dirty_tabular_stack_;
1392 }
1393
1394
1395 } // namespace cap
1396 } // namespace lyx