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