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