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