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