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