]> git.lyx.org Git - lyx.git/blob - src/CutAndPaste.C
d94dc4de6e463a9e92ccad29d6b2f2208dbf70f1
[lyx.git] / src / CutAndPaste.C
1 /*
2  * \file CutAndPaste.C
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  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 #include <config.h>
14
15 #include "CutAndPaste.h"
16
17 #include "buffer.h"
18 #include "buffer_funcs.h"
19 #include "bufferparams.h"
20 #include "BufferView.h"
21 #include "cursor.h"
22 #include "errorlist.h"
23 #include "gettext.h"
24 #include "iterators.h"
25 #include "lyxtext.h"
26 #include "lyxtextclasslist.h"
27 #include "paragraph.h"
28 #include "paragraph_funcs.h"
29 #include "ParagraphParameters.h"
30 #include "ParagraphList_fwd.h"
31 #include "undo.h"
32
33 #include "insets/insettabular.h"
34
35 #include "support/lstrings.h"
36
37 #include <boost/tuple/tuple.hpp>
38
39 using lyx::pos_type;
40 using lyx::par_type;
41 using lyx::textclass_type;
42
43 using lyx::support::bformat;
44
45 using std::for_each;
46 using std::make_pair;
47 using std::pair;
48 using std::vector;
49 using std::string;
50
51
52 namespace {
53
54 typedef std::pair<lyx::par_type, int> PitPosPair;
55
56 typedef limited_stack<pair<ParagraphList, textclass_type> > CutStack;
57
58 CutStack cuts(10);
59
60 struct resetOwnerAndChanges : public std::unary_function<Paragraph, void> {
61         void operator()(Paragraph & p) const {
62                 p.cleanChanges();
63                 p.setInsetOwner(0);
64         }
65 };
66
67 } // namespace anon
68
69
70 namespace lyx {
71 namespace cap {
72
73
74 int SwitchLayoutsBetweenClasses(textclass_type c1, textclass_type c2,
75         ParagraphList & pars, ErrorList & errorlist)
76 {
77         BOOST_ASSERT(!pars.empty());
78         int ret = 0;
79         if (c1 == c2)
80                 return ret;
81
82         LyXTextClass const & tclass1 = textclasslist[c1];
83         LyXTextClass const & tclass2 = textclasslist[c2];
84         ParIterator end = ParIterator(pars.size(), pars);
85         for (ParIterator it = ParIterator(0, pars); it != end; ++it) {
86                 string const name = it->layout()->name();
87                 bool hasLayout = tclass2.hasLayout(name);
88
89                 if (hasLayout)
90                         it->layout(tclass2[name]);
91                 else
92                         it->layout(tclass2.defaultLayout());
93
94                 if (!hasLayout && name != tclass1.defaultLayoutName()) {
95                         ++ret;
96                         string const s = bformat(
97                                 _("Layout had to be changed from\n%1$s to %2$s\n"
98                                 "because of class conversion from\n%3$s to %4$s"),
99                          name, it->layout()->name(), tclass1.name(), tclass2.name());
100                         // To warn the user that something had to be done.
101                         errorlist.push_back(ErrorItem("Changed Layout", s,
102                                                       it->id(), 0,
103                                                       it->size()));
104                 }
105         }
106         return ret;
107 }
108
109
110 std::vector<string> const availableSelections(Buffer const & buffer)
111 {
112         vector<string> selList;
113
114         CutStack::const_iterator cit = cuts.begin();
115         CutStack::const_iterator end = cuts.end();
116         for (; cit != end; ++cit) {
117                 // we do not use cit-> here because gcc 2.9x does not
118                 // like it (JMarc)
119                 ParagraphList const & pars = (*cit).first;
120                 string asciiSel;
121                 ParagraphList::const_iterator pit = pars.begin();
122                 ParagraphList::const_iterator pend = pars.end();
123                 for (; pit != pend; ++pit) {
124                         asciiSel += pit->asString(buffer, false);
125                         if (asciiSel.size() > 25) {
126                                 asciiSel.replace(22, string::npos, "...");
127                                 break;
128                         }
129                 }
130
131                 selList.push_back(asciiSel);
132         }
133
134         return selList;
135 }
136
137
138 PitPosPair eraseSelection(BufferParams const & params, ParagraphList & pars,
139         par_type startpit, par_type endpit,
140         int startpos, int endpos, bool doclear)
141 {
142         if (startpit == par_type(pars.size()) ||
143             (startpos > pars[startpit].size()))
144                 return PitPosPair(endpit, endpos);
145
146         if (endpit == par_type(pars.size()) ||
147             startpit == endpit) {
148                 endpos -= pars[startpit].erase(startpos, endpos);
149                 return PitPosPair(endpit, endpos);
150         }
151
152         // clear end/begin fragments of the first/last par in selection
153         bool all_erased = true;
154
155         pars[startpit].erase(startpos, pars[startpit].size());
156         if (pars[startpit].size() != startpos)
157                 all_erased = false;
158
159         endpos -= pars[endpit].erase(0, endpos);
160         if (endpos != 0)
161                 all_erased = false;
162
163         // Loop through the deleted pars if any, erasing as needed
164
165         par_type pit = startpit + 1;
166
167         while (pit != endpit && pit != par_type(pars.size())) {
168                 par_type const next = pit + 1;
169                 // "erase" the contents of the par
170                 pars[pit].erase(0, pars[pit].size());
171                 if (!pars[pit].size()) {
172                         // remove the par if it's now empty
173                         pars.erase(pars.begin() + pit);
174                 } else
175                         all_erased = false;
176                 pit = next;
177         }
178
179 #if 0 // FIXME: why for cut but not copy ?
180         // the cut selection should begin with standard layout
181         if (realcut) {
182                 buf->params().clear();
183                 buf->bibkey = 0;
184                 buf->layout(textclasslist[buffer->params.textclass].defaultLayoutName());
185         }
186 #endif
187
188         if (startpit + 1 == par_type(pars.size()))
189                 return PitPosPair(endpit, endpos);
190
191         if (doclear) {
192                 pars[startpit + 1].stripLeadingSpaces();
193         }
194
195         // paste the paragraphs again, if possible
196         if (all_erased &&
197             (pars[startpit].hasSameLayout(pars[startpit + 1]) ||
198              pars[startpit + 1].empty())) {
199                 mergeParagraph(params, pars, startpit);
200                 // this because endpar gets deleted here!
201                 endpit = startpit;
202                 endpos = startpos;
203         }
204
205         return PitPosPair(endpit, endpos);
206
207 }
208
209
210 bool copySelection(ParagraphList & pars,
211         par_type startpit, par_type endpit,
212         int start, int end, textclass_type tc)
213 {
214         BOOST_ASSERT(0 <= start && start <= pars[startpit].size());
215         BOOST_ASSERT(0 <= end && end <= pars[endpit].size());
216         BOOST_ASSERT(startpit != endpit || start <= end);
217
218         // Clone the paragraphs within the selection.
219         ParagraphList paragraphs(pars.begin() + startpit, pars.begin() + endpit + 1);
220         for_each(paragraphs.begin(), paragraphs.end(), resetOwnerAndChanges());
221
222         // Cut out the end of the last paragraph.
223         Paragraph & back = paragraphs.back();
224         back.erase(end, back.size());
225
226         // Cut out the begin of the first paragraph
227         Paragraph & front = paragraphs.front();
228         front.erase(0, start);
229
230         cuts.push(make_pair(paragraphs, tc));
231
232         return true;
233 }
234
235
236 PitPosPair cutSelection(BufferParams const & params, ParagraphList & pars,
237         par_type startpit, par_type endpit,
238         int startpos, int endpos, textclass_type tc, bool doclear)
239 {
240         copySelection(pars, startpit, endpit, startpos, endpos, tc);
241         return eraseSelection(params, pars, startpit, endpit, startpos,
242                               endpos, doclear);
243 }
244
245
246 pair<PitPosPair, par_type>
247 pasteSelection(Buffer const & buffer, ParagraphList & pars,
248         par_type pit, int pos,
249         textclass_type tc, size_t cut_index, ErrorList & errorlist)
250 {
251         if (!checkPastePossible())
252                 return make_pair(PitPosPair(pit, pos), pit);
253
254         BOOST_ASSERT (pos <= pars[pit].size());
255
256         // Make a copy of the CaP paragraphs.
257         ParagraphList insertion = cuts[cut_index].first;
258         textclass_type const textclass = cuts[cut_index].second;
259
260         // Now remove all out of the pars which is NOT allowed in the
261         // new environment and set also another font if that is required.
262
263         // Make sure there is no class difference.
264         SwitchLayoutsBetweenClasses(textclass, tc, insertion,
265                                     errorlist);
266
267         ParagraphList::iterator tmpbuf = insertion.begin();
268         int depth_delta = pars[pit].params().depth() - tmpbuf->params().depth();
269
270         Paragraph::depth_type max_depth = pars[pit].getMaxDepthAfter();
271
272         for (; tmpbuf != insertion.end(); ++tmpbuf) {
273                 // If we have a negative jump so that the depth would
274                 // go below 0 depth then we have to redo the delta to
275                 // this new max depth level so that subsequent
276                 // paragraphs are aligned correctly to this paragraph
277                 // at level 0.
278                 if (int(tmpbuf->params().depth()) + depth_delta < 0)
279                         depth_delta = 0;
280
281                 // Set the right depth so that we are not too deep or shallow.
282                 tmpbuf->params().depth(tmpbuf->params().depth() + depth_delta);
283                 if (tmpbuf->params().depth() > max_depth)
284                         tmpbuf->params().depth(max_depth);
285
286                 // Only set this from the 2nd on as the 2nd depends
287                 // for maxDepth still on pit.
288                 if (tmpbuf != insertion.begin())
289                         max_depth = tmpbuf->getMaxDepthAfter();
290
291                 // Set the inset owner of this paragraph.
292                 tmpbuf->setInsetOwner(pars[pit].inInset());
293                 for (pos_type i = 0; i < tmpbuf->size(); ++i) {
294                         if (tmpbuf->getChar(i) == Paragraph::META_INSET) {
295                                 if (!pars[pit].insetAllowed(tmpbuf->getInset(i)->lyxCode()))
296                                         tmpbuf->erase(i--);
297                         }
298                 }
299         }
300
301         // Make the buf exactly the same layout as the cursor paragraph.
302         insertion.begin()->makeSameLayout(pars[pit]);
303
304         // Prepare the paragraphs and insets for insertion.
305         // A couple of insets store buffer references so need updating.
306         ParIterator fpit(0, insertion);
307         ParIterator fend(insertion.size(), insertion);
308
309         for (; fpit != fend; ++fpit) {
310                 InsetList::iterator lit = fpit->insetlist.begin();
311                 InsetList::iterator eit = fpit->insetlist.end();
312
313                 for (; lit != eit; ++lit) {
314                         switch (lit->inset->lyxCode()) {
315                         case InsetOld::TABULAR_CODE: {
316                                 InsetTabular * it = static_cast<InsetTabular*>(lit->inset);
317                                 it->buffer(const_cast<Buffer*>(&buffer));
318                                 break;
319                         }
320
321                         default:
322                                 break; // nothing
323                         }
324                 }
325         }
326
327         // Split the paragraph for inserting the buf if necessary.
328         bool did_split = false;
329         if (pars[pit].size() || pit + 1 == par_type(pars.size())) {
330                 breakParagraphConservative(buffer.params(), pars, pit, pos);
331                 did_split = true;
332         }
333
334         // Paste it!
335         pars.insert(pars.begin() + pit + 1, insertion.begin(), insertion.end());
336         par_type last_paste = pit + insertion.size();
337
338         // If we only inserted one paragraph.
339         if (insertion.size() == 1)
340                 last_paste = pit;
341
342         mergeParagraph(buffer.params(), pars, pit);
343
344         // Store the new cursor position.
345         pit = last_paste;
346         pos = pars[last_paste].size();
347
348         // Maybe some pasting.
349         if (did_split && last_paste + 1 != par_type(pars.size())) {
350                 if (pars[last_paste + 1].hasSameLayout(pars[last_paste])) {
351                         mergeParagraph(buffer.params(), pars, last_paste);
352                 } else if (pars[last_paste + 1].empty()) {
353                         pars[last_paste + 1].makeSameLayout(pars[last_paste]);
354                         mergeParagraph(buffer.params(), pars, last_paste);
355                 } else if (pars[last_paste].empty()) {
356                         pars[last_paste].makeSameLayout(pars[last_paste]);
357                         mergeParagraph(buffer.params(), pars, last_paste);
358                 } else
359                         pars[last_paste + 1].stripLeadingSpaces();
360         }
361
362         return make_pair(PitPosPair(pit, pos), pit + insertion.size() + 1);
363 }
364
365
366 pair<PitPosPair, par_type>
367 pasteSelection(Buffer const & buffer, ParagraphList & pars,
368         par_type pit, int pos, textclass_type tc, ErrorList & errorlist)
369 {
370         return pasteSelection(buffer, pars, pit, pos, tc, 0, errorlist);
371 }
372
373
374 int nrOfParagraphs()
375 {
376         return cuts.empty() ? 0 : cuts[0].first.size();
377 }
378
379
380 bool checkPastePossible()
381 {
382         return !cuts.empty() && !cuts[0].first.empty();
383 }
384
385
386 void cutSelection(LCursor & cur, bool doclear, bool realcut)
387 {
388         LyXText * text = cur.text();
389         BOOST_ASSERT(text);
390         // Stuff what we got on the clipboard. Even if there is no selection.
391
392         // There is a problem with having the stuffing here in that the
393         // larger the selection the slower LyX will get. This can be
394         // solved by running the line below only when the selection has
395         // finished. The solution used currently just works, to make it
396         // faster we need to be more clever and probably also have more
397         // calls to stuffClipboard. (Lgb)
398         cur.bv().stuffClipboard(cur.selectionAsString(true));
399
400         // This doesn't make sense, if there is no selection
401         if (!cur.selection())
402                 return;
403
404         // OK, we have a selection. This is always between cur.selBegin()
405         // and cur.selEnd()
406
407         // make sure that the depth behind the selection are restored, too
408         recordUndoSelection(cur);
409         par_type begpit = cur.selBegin().par();
410         par_type endpit = cur.selEnd().par();
411
412         int endpos = cur.selEnd().pos();
413
414         BufferParams const & bufparams = cur.bv().buffer()->params();
415         boost::tie(endpit, endpos) = realcut ?
416                 cutSelection(bufparams,
417                                           text->paragraphs(),
418                                           begpit, endpit,
419                                           cur.selBegin().pos(), endpos,
420                                           bufparams.textclass,
421                                           doclear)
422                 : eraseSelection(bufparams,
423                                               text->paragraphs(),
424                                               begpit, endpit,
425                                               cur.selBegin().pos(), endpos,
426                                               doclear);
427         // sometimes necessary
428         if (doclear)
429                 text->paragraphs()[begpit].stripLeadingSpaces();
430
431         text->redoParagraphs(begpit, begpit + 1);
432         // cutSelection can invalidate the cursor so we need to set
433         // it anew. (Lgb)
434         // we prefer the end for when tracking changes
435         cur.pos() = endpos;
436         cur.par() = endpit;
437
438         // need a valid cursor. (Lgb)
439         cur.clearSelection();
440         text->updateCounters();
441 }
442
443
444 void copySelection(LCursor & cur)
445 {
446         LyXText * text = cur.text();
447         BOOST_ASSERT(text);
448         // stuff the selection onto the X clipboard, from an explicit copy request
449         cur.bv().stuffClipboard(cur.selectionAsString(true));
450
451         // this doesn't make sense, if there is no selection
452         if (!cur.selection())
453                 return;
454
455         // ok we have a selection. This is always between cur.selBegin()
456         // and sel_end cursor
457
458         // copy behind a space if there is one
459         ParagraphList & pars = text->paragraphs();
460         pos_type pos = cur.selBegin().pos();
461         par_type par = cur.selBegin().par();
462         while (pos < pars[par].size()
463                && pars[par].isLineSeparator(pos)
464                && (par != cur.selEnd().par() || pos < cur.selEnd().pos()))
465                 ++pos;
466
467         copySelection(pars, par, cur.selEnd().par(),
468                 pos, cur.selEnd().pos(), cur.bv().buffer()->params().textclass);
469 }
470
471
472 void pasteSelection(LCursor & cur, size_t sel_index)
473 {
474         LyXText * text = cur.text();
475         BOOST_ASSERT(text);
476         // this does not make sense, if there is nothing to paste
477         if (!checkPastePossible())
478                 return;
479
480         recordUndo(cur);
481
482         par_type endpit;
483         PitPosPair ppp;
484
485         ErrorList el;
486
487         boost::tie(ppp, endpit) =
488                 pasteSelection(*cur.bv().buffer(),
489                                             text->paragraphs(),
490                                             cur.par(), cur.pos(),
491                                             cur.bv().buffer()->params().textclass,
492                                             sel_index, el);
493         bufferErrors(*cur.bv().buffer(), el);
494         text->bv()->showErrorList(_("Paste"));
495
496         text->redoParagraphs(cur.par(), endpit);
497
498         cur.clearSelection();
499         cur.resetAnchor();
500         text->setCursor(cur, ppp.first, ppp.second);
501         cur.setSelection();
502         text->updateCounters();
503 }
504
505
506 void setSelectionRange(LCursor & cur, pos_type length)
507 {
508         LyXText * text = cur.text();
509         BOOST_ASSERT(text);
510         if (!length)
511                 return;
512         cur.resetAnchor();
513         while (length--)
514                 text->cursorRight(cur);
515         cur.setSelection();
516 }
517
518
519 // simple replacing. The font of the first selected character is used
520 void replaceSelectionWithString(LCursor & cur, string const & str)
521 {
522         LyXText * text = cur.text();
523         BOOST_ASSERT(text);
524         recordUndo(cur);
525
526         // Get font setting before we cut
527         pos_type pos = cur.selEnd().pos();
528         LyXFont const font = text->getPar(cur.selBegin().par()).
529                 getFontSettings(cur.bv().buffer()->params(), cur.selBegin().pos());
530
531         // Insert the new string
532         string::const_iterator cit = str.begin();
533         string::const_iterator end = str.end();
534         for (; cit != end; ++cit, ++pos)
535                 text->getPar(cur.selEnd().par()).insertChar(pos, (*cit), font);
536
537         // Cut the selection
538         cutSelection(cur, true, false);
539 }
540
541
542 void replaceSelection(LCursor & cur)
543 {
544         if (cur.selection())
545                 cutSelection(cur, true, false);
546 }
547
548
549 // only used by the spellchecker
550 void replaceWord(LCursor & cur, string const & replacestring)
551 {
552         LyXText * text = cur.text();
553         BOOST_ASSERT(text);
554
555         replaceSelectionWithString(cur, replacestring);
556         setSelectionRange(cur, replacestring.length());
557
558         // Go back so that replacement string is also spellchecked
559         for (string::size_type i = 0; i < replacestring.length() + 1; ++i)
560                 text->cursorLeft(cur);
561 }
562
563
564 } // namespace cap
565 } // namespace lyx