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