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