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