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