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