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