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