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