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