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