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