]> git.lyx.org Git - lyx.git/blob - src/Text3.cpp
93812f370e44e138a4d4faa02b6156d5bbdf2918
[lyx.git] / src / Text3.cpp
1 /**
2  * \file Text3.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Asger Alstrup
7  * \author Lars Gullik Bjønnes
8  * \author Alfredo Braunstein
9  * \author Angus Leeming
10  * \author John Levon
11  * \author André Pönitz
12  *
13  * Full author contact details are available in file CREDITS.
14  */
15
16 #include <config.h>
17
18 #include "Text.h"
19
20 #include "Bidi.h"
21 #include "BranchList.h"
22 #include "FloatList.h"
23 #include "FuncStatus.h"
24 #include "Buffer.h"
25 #include "buffer_funcs.h"
26 #include "BufferParams.h"
27 #include "BufferView.h"
28 #include "Changes.h"
29 #include "Cursor.h"
30 #include "CutAndPaste.h"
31 #include "DispatchResult.h"
32 #include "ErrorList.h"
33 #include "factory.h"
34 #include "FuncRequest.h"
35 #include "InsetList.h"
36 #include "Intl.h"
37 #include "Language.h"
38 #include "Layout.h"
39 #include "LyXAction.h"
40 #include "LyXFunc.h"
41 #include "Lexer.h"
42 #include "LyXRC.h"
43 #include "Paragraph.h"
44 #include "ParagraphParameters.h"
45 #include "TextClass.h"
46 #include "TextMetrics.h"
47 #include "VSpace.h"
48
49 #include "frontends/Application.h"
50 #include "frontends/Clipboard.h"
51 #include "frontends/Selection.h"
52
53 #include "insets/InsetCollapsable.h"
54 #include "insets/InsetCommand.h"
55 #include "insets/InsetExternal.h"
56 #include "insets/InsetFloat.h"
57 #include "insets/InsetFloatList.h"
58 #include "insets/InsetGraphics.h"
59 #include "insets/InsetGraphicsParams.h"
60 #include "insets/InsetNewline.h"
61 #include "insets/InsetQuotes.h"
62 #include "insets/InsetSpecialChar.h"
63 #include "insets/InsetText.h"
64 #include "insets/InsetWrap.h"
65
66 #include "support/convert.h"
67 #include "support/debug.h"
68 #include "support/gettext.h"
69 #include "support/lstrings.h"
70 #include "support/lyxtime.h"
71 #include "support/os.h"
72
73 #include "mathed/InsetMathHull.h"
74 #include "mathed/MathMacroTemplate.h"
75
76 #include <boost/next_prior.hpp>
77
78 #include <clocale>
79 #include <sstream>
80
81 using namespace std;
82 using namespace lyx::support;
83
84 namespace lyx {
85
86 using cap::copySelection;
87 using cap::cutSelection;
88 using cap::pasteFromStack;
89 using cap::pasteClipboardText;
90 using cap::pasteClipboardGraphics;
91 using cap::replaceSelection;
92 using cap::grabAndEraseSelection;
93 using cap::selClearOrDel;
94
95 // globals...
96 static Font freefont(ignore_font, ignore_language);
97 static bool toggleall = false;
98
99 static void toggleAndShow(Cursor & cur, Text * text,
100         Font const & font, bool toggleall = true)
101 {
102         text->toggleFree(cur, font, toggleall);
103
104         if (font.language() != ignore_language ||
105             font.fontInfo().number() != FONT_IGNORE) {
106                 TextMetrics const & tm = cur.bv().textMetrics(text);
107                 if (cur.boundary() != tm.isRTLBoundary(cur.pit(), cur.pos(),
108                                                        cur.real_current_font))
109                         text->setCursor(cur, cur.pit(), cur.pos(),
110                                         false, !cur.boundary());
111         }
112 }
113
114
115 static void moveCursor(Cursor & cur, bool selecting)
116 {
117         if (selecting || cur.mark())
118                 cur.setSelection();
119 }
120
121
122 static void finishChange(Cursor & cur, bool selecting)
123 {
124         cur.finishUndo();
125         moveCursor(cur, selecting);
126 }
127
128
129 static void mathDispatch(Cursor & cur, FuncRequest const & cmd, bool display)
130 {
131         cur.recordUndo();
132         docstring sel = cur.selectionAsString(false);
133
134         // It may happen that sel is empty but there is a selection
135         replaceSelection(cur);
136
137         // Is this a valid formula?
138         bool valid = true;
139
140         if (sel.empty()) {
141 #ifdef ENABLE_ASSERTIONS
142                 const int old_pos = cur.pos();
143 #endif
144                 cur.insert(new InsetMathHull(cur.buffer(), hullSimple));
145 #ifdef ENABLE_ASSERTIONS
146                 LASSERT(old_pos == cur.pos(), /**/);
147 #endif
148                 cur.nextInset()->edit(cur, true);
149                 // don't do that also for LFUN_MATH_MODE
150                 // unless you want end up with always changing
151                 // to mathrm when opening an inlined inset --
152                 // I really hate "LyXfunc overloading"...
153                 if (display)
154                         cur.dispatch(FuncRequest(LFUN_MATH_DISPLAY));
155                 // Avoid an unnecessary undo step if cmd.argument
156                 // is empty
157                 if (!cmd.argument().empty())
158                         cur.dispatch(FuncRequest(LFUN_MATH_INSERT,
159                                                  cmd.argument()));
160         } else {
161                 // create a macro if we see "\\newcommand"
162                 // somewhere, and an ordinary formula
163                 // otherwise
164                 if (sel.find(from_ascii("\\newcommand")) == string::npos
165                                 && sel.find(from_ascii("\\newlyxcommand")) == string::npos
166                                 && sel.find(from_ascii("\\def")) == string::npos)
167                 {
168                         InsetMathHull * formula = new InsetMathHull(cur.buffer());
169                         string const selstr = to_utf8(sel);
170                         istringstream is(selstr);
171                         Lexer lex;
172                         lex.setStream(is);
173                         if (!formula->readQuiet(lex)) {
174                                 // No valid formula, let's try with delims
175                                 is.str("$" + selstr + "$");
176                                 lex.setStream(is);
177                                 if (!formula->readQuiet(lex)) {
178                                         // Still not valid, leave it as is
179                                         valid = false;
180                                         delete formula;
181                                         cur.insert(sel);
182                                 } else
183                                         cur.insert(formula);
184                         } else
185                                 cur.insert(formula);
186                 } else {
187                         cur.insert(new MathMacroTemplate(cur.buffer(), sel));
188                 }
189         }
190         if (valid)
191                 cur.message(from_utf8(N_("Math editor mode")));
192         else
193                 cur.message(from_utf8(N_("No valid math formula")));
194 }
195
196
197 void regexpDispatch(Cursor & cur, FuncRequest const & cmd)
198 {
199         BOOST_ASSERT(cmd.action == LFUN_REGEXP_MODE);
200         if (cur.inRegexped()) {
201                 cur.message(_("Already in regexp mode"));
202                 return;
203         }
204         cur.recordUndo();
205         docstring sel = cur.selectionAsString(false);
206
207         // It may happen that sel is empty but there is a selection
208         replaceSelection(cur);
209
210         cur.insert(new InsetMathHull(cur.buffer(), hullRegexp));
211         cur.nextInset()->edit(cur, true);
212         cur.niceInsert(sel);
213
214         cur.message(_("Regexp editor mode"));
215 }
216
217
218 static void specialChar(Cursor & cur, InsetSpecialChar::Kind kind)
219 {
220         cur.recordUndo();
221         cap::replaceSelection(cur);
222         cur.insert(new InsetSpecialChar(kind));
223         cur.posForward();
224 }
225
226
227 static bool doInsertInset(Cursor & cur, Text * text,
228         FuncRequest const & cmd, bool edit, bool pastesel)
229 {
230         Buffer & buffer = cur.bv().buffer();
231         BufferParams const & bparams = buffer.params();
232         Inset * inset = createInset(&buffer, cmd);
233         if (!inset)
234                 return false;
235
236         if (InsetCollapsable * ci = inset->asInsetCollapsable())
237                 ci->setButtonLabel();
238
239         cur.recordUndo();
240         if (cmd.action == LFUN_INDEX_INSERT) {
241                 docstring ds = subst(text->getStringToIndex(cur), '\n', ' ');
242                 text->insertInset(cur, inset);
243                 if (edit)
244                         inset->edit(cur, true);
245                 // Now put this into inset
246                 cur.text()->insertStringAsLines(cur, ds, cur.current_font);
247                 cur.leaveInset(*inset);
248                 return true;
249         }
250
251         bool gotsel = false;
252         if (cur.selection()) {
253                 cutSelection(cur, false, pastesel);
254                 cur.clearSelection();
255                 gotsel = true;
256         }
257         text->insertInset(cur, inset);
258
259         if (edit)
260                 inset->edit(cur, true);
261
262         if (!gotsel || !pastesel)
263                 return true;
264
265         pasteFromStack(cur, cur.buffer()->errorList("Paste"), 0);
266         cur.buffer()->errors("Paste");
267         cur.clearSelection(); // bug 393
268         cur.finishUndo();
269         InsetText * insetText = dynamic_cast<InsetText *>(inset);
270         if (insetText && (!insetText->allowMultiPar() || cur.lastpit() == 0)) {
271                 // reset first par to default
272                 cur.text()->paragraphs().begin()
273                         ->setPlainOrDefaultLayout(bparams.documentClass());
274                 cur.pos() = 0;
275                 cur.pit() = 0;
276                 // Merge multiple paragraphs -- hack
277                 while (cur.lastpit() > 0)
278                         mergeParagraph(bparams, cur.text()->paragraphs(), 0);
279                 cur.leaveInset(*inset);
280         } else {
281                 cur.leaveInset(*inset);
282                 // reset surrounding par to default
283                 DocumentClass const & dc = bparams.documentClass();
284                 docstring const layoutname = inset->usePlainLayout()
285                         ? dc.plainLayoutName()
286                         : dc.defaultLayoutName();
287                 text->setLayout(cur, layoutname);
288         }
289
290         return true;
291 }
292
293
294 string const freefont2string()
295 {
296         return freefont.toString(toggleall);
297 }
298
299
300 static void dragMove(Cursor & cur, int moveid, int movetoid)
301 {
302         // Create pointers to buffers
303         Buffer & buf_move = *cur.buffer();
304         DocIterator dit_move = buf_move.getParFromID(moveid);
305         DocIterator dit_dest = buf_move.getParFromID(movetoid);
306
307         pit_type & pit_move = dit_move.pit();
308         pit_type & pit_dest = dit_dest.pit();
309         ParagraphList & pars = dit_move.text()->paragraphs();
310
311         // Create references to the paragraphs to be moved
312         ParagraphList::iterator const bgn = pars.begin();
313         ParagraphList::iterator dest_start = boost::next(bgn, pit_dest);
314
315         // The first paragraph of the area to be copied:
316         ParagraphList::iterator start = boost::next(bgn, pit_move);
317         // The final paragraph of area to be copied:
318         ParagraphList::iterator finish = start;
319         ParagraphList::iterator const end = pars.end();
320
321         // Move out (down) from this section header
322         if (finish != end)
323                 ++finish;
324
325         // Seek the one (on same level) below
326         int const thistoclevel = start->layout().toclevel;
327         for (; finish != end; ++finish) {
328                 int const toclevel = finish->layout().toclevel;
329                 if (toclevel != Layout::NOT_IN_TOC
330                     && toclevel <= thistoclevel)
331                         break;
332         }
333
334         if (start == pars.begin() || start == dest_start)
335                 // Nothing to move
336                 return;
337
338         pars.insert(dest_start, start, finish);
339         pars.erase(start, finish);
340
341         // FIXME: This only really needs doing for the newly
342         // introduced paragraphs. Something like:
343         //      pit_type const numpars = distance(start, finish);
344         //      start = boost::next(bgn, pit);
345         //      finish = boost::next(start, numpars);
346         //      for (; start != finish; ++start)
347         //              start->setBuffer(buf);
348         // But while this seems to work, it is kind of fragile.
349         buf_move.inset().setBuffer(buf_move);
350 }
351
352
353 /// the type of outline operation
354 enum OutlineOp {
355         OutlineUp, // Move this header with text down
356         OutlineDown,   // Move this header with text up
357         OutlineIn, // Make this header deeper
358         OutlineOut // Make this header shallower
359 };
360
361
362 static void outline(OutlineOp mode, Cursor & cur)
363 {
364         Buffer & buf = *cur.buffer();
365         pit_type & pit = cur.pit();
366         ParagraphList & pars = buf.text().paragraphs();
367         ParagraphList::iterator const bgn = pars.begin();
368         // The first paragraph of the area to be copied:
369         ParagraphList::iterator start = boost::next(bgn, pit);
370         // The final paragraph of area to be copied:
371         ParagraphList::iterator finish = start;
372         ParagraphList::iterator const end = pars.end();
373
374         DocumentClass const & tc = buf.params().documentClass();
375
376         int const thistoclevel = start->layout().toclevel;
377         int toclevel;
378
379         // Move out (down) from this section header
380         if (finish != end)
381                 ++finish;
382
383         // Seek the one (on same level) below
384         for (; finish != end; ++finish) {
385                 toclevel = finish->layout().toclevel;
386                 if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
387                         break;
388         }
389
390         switch (mode) {
391                 case OutlineUp: {
392                         if (start == pars.begin())
393                                 // Nothing to move.
394                                 return;
395                         ParagraphList::iterator dest = start;
396                         // Move out (up) from this header
397                         if (dest == bgn)
398                                 return;
399                         // Search previous same-level header above
400                         do {
401                                 --dest;
402                                 toclevel = dest->layout().toclevel;
403                         } while(dest != bgn
404                                 && (toclevel == Layout::NOT_IN_TOC
405                                     || toclevel > thistoclevel));
406                         // Not found; do nothing
407                         if (toclevel == Layout::NOT_IN_TOC || toclevel > thistoclevel)
408                                 return;
409                         pit_type const newpit = distance(bgn, dest);
410                         pit_type const len = distance(start, finish);
411                         pit_type const deletepit = pit + len;
412                         buf.undo().recordUndo(cur, ATOMIC_UNDO, newpit, deletepit - 1);
413                         pars.splice(dest, start, finish);
414                         cur.pit() = newpit;
415                         break;
416                 }
417                 case OutlineDown: {
418                         if (finish == end)
419                                 // Nothing to move.
420                                 return;
421                         // Go one down from *this* header:
422                         ParagraphList::iterator dest = boost::next(finish, 1);
423                         // Go further down to find header to insert in front of:
424                         for (; dest != end; ++dest) {
425                                 toclevel = dest->layout().toclevel;
426                                 if (toclevel != Layout::NOT_IN_TOC
427                                       && toclevel <= thistoclevel)
428                                         break;
429                         }
430                         // One such was found:
431                         pit_type newpit = distance(bgn, dest);
432                         buf.undo().recordUndo(cur, ATOMIC_UNDO, pit, newpit - 1);
433                         pit_type const len = distance(start, finish);
434                         pars.splice(dest, start, finish);
435                         cur.pit() = newpit - len;
436                         break;
437                 }
438                 case OutlineIn: {
439                         pit_type const len = distance(start, finish);
440                         buf.undo().recordUndo(cur, ATOMIC_UNDO, pit, pit + len - 1);
441                         for (; start != finish; ++start) {
442                                 toclevel = start->layout().toclevel;
443                                 if (toclevel == Layout::NOT_IN_TOC)
444                                         continue;
445                                 DocumentClass::const_iterator lit = tc.begin();
446                                 DocumentClass::const_iterator len = tc.end();
447                                 for (; lit != len; ++lit) {
448                                         if (lit->toclevel == toclevel + 1 &&
449                                             start->layout().labeltype == lit->labeltype) {
450                                                 start->setLayout(*lit);
451                                                 break;
452                                         }
453                                 }
454                         }
455                         break;
456                 }
457                 case OutlineOut: {
458                         pit_type const len = distance(start, finish);
459                         buf.undo().recordUndo(cur, ATOMIC_UNDO, pit, pit + len - 1);
460                         for (; start != finish; ++start) {
461                                 toclevel = start->layout().toclevel;
462                                 if (toclevel == Layout::NOT_IN_TOC)
463                                         continue;
464                                 DocumentClass::const_iterator lit = tc.begin();
465                                 DocumentClass::const_iterator len = tc.end();
466                                 for (; lit != len; ++lit) {
467                                         if (lit->toclevel == toclevel - 1 &&
468                                                 start->layout().labeltype == lit->labeltype) {
469                                                         start->setLayout(*lit);
470                                                         break;
471                                         }
472                                 }
473                         }
474                         break;
475                 }
476         }
477 }
478
479
480 void Text::number(Cursor & cur)
481 {
482         FontInfo font = ignore_font;
483         font.setNumber(FONT_TOGGLE);
484         toggleAndShow(cur, this, Font(font, ignore_language));
485 }
486
487
488 bool Text::isRTL(Paragraph const & par) const
489 {
490         Buffer const & buffer = owner_->buffer();
491         return par.isRTL(buffer.params());
492 }
493
494
495 void Text::dispatch(Cursor & cur, FuncRequest & cmd)
496 {
497         LYXERR(Debug::ACTION, "Text::dispatch: cmd: " << cmd);
498
499         // Dispatch if the cursor is inside the text. It is not the
500         // case for context menus (bug 5797).
501         if (cur.text() != this) {
502                 cur.undispatched();
503                 return;
504         }
505
506         BufferView * bv = &cur.bv();
507         TextMetrics * tm = &bv->textMetrics(this);
508         if (!tm->contains(cur.pit())) {
509                 lyx::dispatch(FuncRequest(LFUN_SCREEN_SHOW_CURSOR));
510                 tm = &bv->textMetrics(this);
511         }
512
513         // FIXME: We use the update flag to indicates wether a singlePar or a
514         // full screen update is needed. We reset it here but shall we restore it
515         // at the end?
516         cur.noUpdate();
517
518         LASSERT(cur.text() == this, /**/);
519         CursorSlice oldTopSlice = cur.top();
520         bool oldBoundary = cur.boundary();
521         bool sel = cur.selection();
522         // Signals that, even if needsUpdate == false, an update of the
523         // cursor paragraph is required
524         bool singleParUpdate = lyxaction.funcHasFlag(cmd.action,
525                 LyXAction::SingleParUpdate);
526         // Signals that a full-screen update is required
527         bool needsUpdate = !(lyxaction.funcHasFlag(cmd.action,
528                 LyXAction::NoUpdate) || singleParUpdate);
529
530         switch (cmd.action) {
531
532         case LFUN_PARAGRAPH_MOVE_DOWN: {
533                 pit_type const pit = cur.pit();
534                 recUndo(cur, pit, pit + 1);
535                 cur.finishUndo();
536                 pars_.swap(pit, pit + 1);
537                 cur.buffer()->updateLabels();
538                 needsUpdate = true;
539                 ++cur.pit();
540                 break;
541         }
542
543         case LFUN_PARAGRAPH_MOVE_UP: {
544                 pit_type const pit = cur.pit();
545                 recUndo(cur, pit - 1, pit);
546                 cur.finishUndo();
547                 pars_.swap(pit, pit - 1);
548                 cur.buffer()->updateLabels();
549                 --cur.pit();
550                 needsUpdate = true;
551                 break;
552         }
553
554         case LFUN_APPENDIX: {
555                 Paragraph & par = cur.paragraph();
556                 bool start = !par.params().startOfAppendix();
557
558 // FIXME: The code below only makes sense at top level.
559 // Should LFUN_APPENDIX be restricted to top-level paragraphs?
560                 // ensure that we have only one start_of_appendix in this document
561                 // FIXME: this don't work for multipart document!
562                 for (pit_type tmp = 0, end = pars_.size(); tmp != end; ++tmp) {
563                         if (pars_[tmp].params().startOfAppendix()) {
564                                 recUndo(cur, tmp);
565                                 pars_[tmp].params().startOfAppendix(false);
566                                 break;
567                         }
568                 }
569
570                 cur.recordUndo();
571                 par.params().startOfAppendix(start);
572
573                 // we can set the refreshing parameters now
574                 cur.buffer()->updateLabels();
575                 break;
576         }
577
578         case LFUN_WORD_DELETE_FORWARD:
579                 if (cur.selection())
580                         cutSelection(cur, true, false);
581                 else
582                         deleteWordForward(cur);
583                 finishChange(cur, false);
584                 break;
585
586         case LFUN_WORD_DELETE_BACKWARD:
587                 if (cur.selection())
588                         cutSelection(cur, true, false);
589                 else
590                         deleteWordBackward(cur);
591                 finishChange(cur, false);
592                 break;
593
594         case LFUN_LINE_DELETE:
595                 if (cur.selection())
596                         cutSelection(cur, true, false);
597                 else
598                         tm->deleteLineForward(cur);
599                 finishChange(cur, false);
600                 break;
601
602         case LFUN_BUFFER_BEGIN:
603         case LFUN_BUFFER_BEGIN_SELECT:
604                 needsUpdate |= cur.selHandle(cmd.action == LFUN_BUFFER_BEGIN_SELECT);
605                 if (cur.depth() == 1)
606                         needsUpdate |= cursorTop(cur);
607                 else
608                         cur.undispatched();
609                 cur.updateFlags(Update::FitCursor);
610                 break;
611
612         case LFUN_BUFFER_END:
613         case LFUN_BUFFER_END_SELECT:
614                 needsUpdate |= cur.selHandle(cmd.action == LFUN_BUFFER_END_SELECT);
615                 if (cur.depth() == 1)
616                         needsUpdate |= cursorBottom(cur);
617                 else
618                         cur.undispatched();
619                 cur.updateFlags(Update::FitCursor);
620                 break;
621
622         case LFUN_INSET_BEGIN:
623         case LFUN_INSET_BEGIN_SELECT:
624                 needsUpdate |= cur.selHandle(cmd.action == LFUN_INSET_BEGIN_SELECT);
625                 if (cur.depth() == 1 || !cur.top().at_begin())
626                         needsUpdate |= cursorTop(cur);
627                 else
628                         cur.undispatched();
629                 cur.updateFlags(Update::FitCursor);
630                 break;
631
632         case LFUN_INSET_END:
633         case LFUN_INSET_END_SELECT:
634                 needsUpdate |= cur.selHandle(cmd.action == LFUN_INSET_END_SELECT);
635                 if (cur.depth() == 1 || !cur.top().at_end())
636                         needsUpdate |= cursorBottom(cur);
637                 else
638                         cur.undispatched();
639                 cur.updateFlags(Update::FitCursor);
640                 break;
641
642         case LFUN_INSET_SELECT_ALL:
643                 if (cur.depth() == 1 || !cur.selection() || !cur.selBegin().at_begin()
644                           || !cur.selEnd().at_end()) {
645                         needsUpdate |= cur.selHandle(false);
646                         needsUpdate |= cursorTop(cur);
647                         needsUpdate |= cur.selHandle(true);
648                         needsUpdate |= cursorBottom(cur);
649                 } else 
650                         cur.undispatched();
651                 cur.updateFlags(Update::FitCursor);
652                 break;
653
654         case LFUN_CHAR_FORWARD:
655         case LFUN_CHAR_FORWARD_SELECT:
656                 //LYXERR0(" LFUN_CHAR_FORWARD[SEL]:\n" << cur);
657                 needsUpdate |= cur.selHandle(cmd.action == LFUN_CHAR_FORWARD_SELECT);
658                 needsUpdate |= cursorForward(cur);
659
660                 if (!needsUpdate && oldTopSlice == cur.top()
661                                 && cur.boundary() == oldBoundary) {
662                         cur.undispatched();
663                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
664                 
665                         // we will probably be moving out the inset, so we should execute
666                         // the depm-mechanism, but only when the cursor has a place to 
667                         // go outside this inset, i.e. in a slice above.
668                         if (cur.depth() > 1 && cur.pos() == cur.lastpos() 
669                                   && cur.pit() == cur.lastpit()) {
670                                 // The cursor hasn't changed yet. To give the 
671                                 // DEPM the possibility of doing something we must
672                                 // provide it with two different cursors.
673                                 Cursor dummy = cur;
674                                 dummy.pos() = dummy.pit() = 0;
675                                 cur.bv().checkDepm(dummy, cur);
676                         }
677                 }
678                 break;
679
680         case LFUN_CHAR_BACKWARD:
681         case LFUN_CHAR_BACKWARD_SELECT:
682                 //lyxerr << "handle LFUN_CHAR_BACKWARD[_SELECT]:\n" << cur << endl;
683                 needsUpdate |= cur.selHandle(cmd.action == LFUN_CHAR_BACKWARD_SELECT);
684                 needsUpdate |= cursorBackward(cur);
685
686                 if (!needsUpdate && oldTopSlice == cur.top()
687                         && cur.boundary() == oldBoundary) {
688                         cur.undispatched();
689                         cmd = FuncRequest(LFUN_FINISHED_BACKWARD);
690
691                         // we will probably be moving out the inset, so we should execute
692                         // the depm-mechanism, but only when the cursor has a place to 
693                         // go outside this inset, i.e. in a slice above.
694                         if (cur.depth() > 1 && cur.pos() == 0 && cur.pit() == 0) {
695                                 // The cursor hasn't changed yet. To give the 
696                                 // DEPM the possibility of doing something we must
697                                 // provide it with two different cursors.
698                                 Cursor dummy = cur;
699                                 dummy.pos() = cur.lastpos();
700                                 dummy.pit() = cur.lastpit();
701                                 cur.bv().checkDepm(dummy, cur);
702                         }
703                 }
704                 break;
705
706         case LFUN_CHAR_LEFT:
707         case LFUN_CHAR_LEFT_SELECT:
708                 if (lyxrc.visual_cursor) {
709                         needsUpdate |= cur.selHandle(cmd.action == LFUN_CHAR_LEFT_SELECT);
710                         needsUpdate |= cursorVisLeft(cur);
711                         if (!needsUpdate && oldTopSlice == cur.top()
712                                         && cur.boundary() == oldBoundary) {
713                                 cur.undispatched();
714                                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
715                         }
716                 } else {
717                         if (reverseDirectionNeeded(cur)) {
718                                 cmd.action = cmd.action == LFUN_CHAR_LEFT_SELECT ?
719                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD;
720                         } else {
721                                 cmd.action = cmd.action == LFUN_CHAR_LEFT_SELECT ?
722                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD;
723                         }
724                         dispatch(cur, cmd);
725                         return;
726                 }
727                 break;
728
729         case LFUN_CHAR_RIGHT:
730         case LFUN_CHAR_RIGHT_SELECT:
731                 if (lyxrc.visual_cursor) {
732                         needsUpdate |= cur.selHandle(cmd.action == LFUN_CHAR_RIGHT_SELECT);
733                         needsUpdate |= cursorVisRight(cur);
734                         if (!needsUpdate && oldTopSlice == cur.top()
735                                         && cur.boundary() == oldBoundary) {
736                                 cur.undispatched();
737                                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
738                         }
739                 } else {
740                         if (reverseDirectionNeeded(cur)) {
741                                 cmd.action = cmd.action == LFUN_CHAR_RIGHT_SELECT ?
742                                         LFUN_CHAR_BACKWARD_SELECT : LFUN_CHAR_BACKWARD;
743                         } else {
744                                 cmd.action = cmd.action == LFUN_CHAR_RIGHT_SELECT ?
745                                         LFUN_CHAR_FORWARD_SELECT : LFUN_CHAR_FORWARD;
746                         }
747                         dispatch(cur, cmd);
748                         return;
749                 }
750                 break;
751
752
753         case LFUN_UP_SELECT:
754         case LFUN_DOWN_SELECT:
755         case LFUN_UP:
756         case LFUN_DOWN: {
757                 // stop/start the selection
758                 bool select = cmd.action == LFUN_DOWN_SELECT ||
759                         cmd.action == LFUN_UP_SELECT;
760
761                 // move cursor up/down
762                 bool up = cmd.action == LFUN_UP_SELECT || cmd.action == LFUN_UP;
763                 bool const atFirstOrLastRow = cur.atFirstOrLastRow(up);
764
765                 if (!atFirstOrLastRow) {
766                         needsUpdate |= cur.selHandle(select);   
767                         cur.selHandle(select);
768                         cur.upDownInText(up, needsUpdate);
769                         needsUpdate |= cur.beforeDispatchCursor().inMathed();
770                 } else {
771                         // if the cursor cannot be moved up or down do not remove
772                         // the selection right now, but wait for the next dispatch.
773                         if (select)
774                                 needsUpdate |= cur.selHandle(select);   
775                         cur.upDownInText(up, needsUpdate);
776                         cur.undispatched();
777                 }
778
779                 break;
780         }
781
782         case LFUN_PARAGRAPH_UP:
783         case LFUN_PARAGRAPH_UP_SELECT:
784                 needsUpdate |= cur.selHandle(cmd.action == LFUN_PARAGRAPH_UP_SELECT);
785                 needsUpdate |= cursorUpParagraph(cur);
786                 break;
787
788         case LFUN_PARAGRAPH_DOWN:
789         case LFUN_PARAGRAPH_DOWN_SELECT:
790                 needsUpdate |= cur.selHandle(cmd.action == LFUN_PARAGRAPH_DOWN_SELECT);
791                 needsUpdate |= cursorDownParagraph(cur);
792                 break;
793
794         case LFUN_LINE_BEGIN:
795         case LFUN_LINE_BEGIN_SELECT:
796                 needsUpdate |= cur.selHandle(cmd.action == LFUN_LINE_BEGIN_SELECT);
797                 needsUpdate |= tm->cursorHome(cur);
798                 break;
799
800         case LFUN_LINE_END:
801         case LFUN_LINE_END_SELECT:
802                 needsUpdate |= cur.selHandle(cmd.action == LFUN_LINE_END_SELECT);
803                 needsUpdate |= tm->cursorEnd(cur);
804                 break;
805
806         case LFUN_SECTION_SELECT: {
807                 Buffer const & buf = *cur.buffer();
808                 pit_type const pit = cur.pit();
809                 ParagraphList & pars = buf.text().paragraphs();
810                 ParagraphList::iterator bgn = pars.begin();
811                 // The first paragraph of the area to be selected:
812                 ParagraphList::iterator start = boost::next(bgn, pit);
813                 // The final paragraph of area to be selected:
814                 ParagraphList::iterator finish = start;
815                 ParagraphList::iterator end = pars.end();
816
817                 int const thistoclevel = start->layout().toclevel;
818                 if (thistoclevel == Layout::NOT_IN_TOC)
819                         break;
820
821                 cur.pos() = 0;
822                 Cursor const old_cur = cur;
823                 needsUpdate |= cur.selHandle(true);
824
825                 // Move out (down) from this section header
826                 if (finish != end)
827                         ++finish;
828
829                 // Seek the one (on same level) below
830                 for (; finish != end; ++finish, ++cur.pit()) {
831                         int const toclevel = finish->layout().toclevel;
832                         if (toclevel != Layout::NOT_IN_TOC && toclevel <= thistoclevel)
833                                 break;
834                 }
835                 cur.pos() = cur.lastpos();
836                 
837                 needsUpdate |= cur != old_cur;
838                 break;
839         }
840
841         case LFUN_WORD_RIGHT:
842         case LFUN_WORD_RIGHT_SELECT:
843                 if (lyxrc.visual_cursor) {
844                         needsUpdate |= cur.selHandle(cmd.action == LFUN_WORD_RIGHT_SELECT);
845                         needsUpdate |= cursorVisRightOneWord(cur);
846                         if (!needsUpdate && oldTopSlice == cur.top()
847                                         && cur.boundary() == oldBoundary) {
848                                 cur.undispatched();
849                                 cmd = FuncRequest(LFUN_FINISHED_RIGHT);
850                         }
851                 } else {
852                         if (reverseDirectionNeeded(cur)) {
853                                 cmd.action = cmd.action == LFUN_WORD_RIGHT_SELECT ?
854                                                 LFUN_WORD_BACKWARD_SELECT : LFUN_WORD_BACKWARD;
855                         } else {
856                                 cmd.action = cmd.action == LFUN_WORD_RIGHT_SELECT ?
857                                                 LFUN_WORD_FORWARD_SELECT : LFUN_WORD_FORWARD;
858                         }
859                         dispatch(cur, cmd);
860                         return;
861                 }
862                 break;
863
864         case LFUN_WORD_FORWARD:
865         case LFUN_WORD_FORWARD_SELECT:
866                 needsUpdate |= cur.selHandle(cmd.action == LFUN_WORD_FORWARD_SELECT);
867                 needsUpdate |= cursorForwardOneWord(cur);
868                 break;
869
870         case LFUN_WORD_LEFT:
871         case LFUN_WORD_LEFT_SELECT:
872                 if (lyxrc.visual_cursor) {
873                         needsUpdate |= cur.selHandle(cmd.action == LFUN_WORD_LEFT_SELECT);
874                         needsUpdate |= cursorVisLeftOneWord(cur);
875                         if (!needsUpdate && oldTopSlice == cur.top()
876                                         && cur.boundary() == oldBoundary) {
877                                 cur.undispatched();
878                                 cmd = FuncRequest(LFUN_FINISHED_LEFT);
879                         }
880                 } else {
881                         if (reverseDirectionNeeded(cur)) {
882                                 cmd.action = cmd.action == LFUN_WORD_LEFT_SELECT ?
883                                                 LFUN_WORD_FORWARD_SELECT : LFUN_WORD_FORWARD;
884                         } else {
885                                 cmd.action = cmd.action == LFUN_WORD_LEFT_SELECT ?
886                                                 LFUN_WORD_BACKWARD_SELECT : LFUN_WORD_BACKWARD;
887                         }
888                         dispatch(cur, cmd);
889                         return;
890                 }
891                 break;
892
893         case LFUN_WORD_BACKWARD:
894         case LFUN_WORD_BACKWARD_SELECT:
895                 needsUpdate |= cur.selHandle(cmd.action == LFUN_WORD_BACKWARD_SELECT);
896                 needsUpdate |= cursorBackwardOneWord(cur);
897                 break;
898
899         case LFUN_WORD_SELECT: {
900                 selectWord(cur, WHOLE_WORD);
901                 finishChange(cur, true);
902                 break;
903         }
904
905         case LFUN_NEWLINE_INSERT: {
906                 InsetNewlineParams inp;
907                 docstring arg = cmd.argument();
908                 // this avoids a double undo
909                 // FIXME: should not be needed, ideally
910                 if (!cur.selection())
911                         cur.recordUndo();
912                 cap::replaceSelection(cur);
913                 if (arg == "linebreak")
914                         inp.kind = InsetNewlineParams::LINEBREAK;
915                 else
916                         inp.kind = InsetNewlineParams::NEWLINE;
917                 cur.insert(new InsetNewline(inp));
918                 cur.posForward();
919                 moveCursor(cur, false);
920                 break;
921         }
922
923         case LFUN_TAB_INSERT: {
924                 bool const multi_par_selection = cur.selection() &&
925                         cur.selBegin().pit() != cur.selEnd().pit();
926                 if (multi_par_selection) {
927                         // If there is a multi-paragraph selection, a tab is inserted
928                         // at the beginning of each paragraph.
929                         cur.recordUndoSelection();
930                         pit_type const pit_end = cur.selEnd().pit();
931                         for (pit_type pit = cur.selBegin().pit(); pit <= pit_end; pit++) {
932                                 pars_[pit].insertChar(0, '\t', 
933                                                       bv->buffer().params().trackChanges);
934                                 // Update the selection pos to make sure the selection does not
935                                 // change as the inserted tab will increase the logical pos.
936                                 if (cur.anchor_.pit() == pit)
937                                         cur.anchor_.forwardPos();
938                                 if (cur.pit() == pit)
939                                         cur.forwardPos();
940                         }
941                         cur.finishUndo();
942                 } else {
943                         // Maybe we shouldn't allow tabs within a line, because they
944                         // are not (yet) aligned as one might do expect.
945                         FuncRequest cmd(LFUN_SELF_INSERT, from_ascii("\t"));
946                         dispatch(cur, cmd);     
947                 }
948                 break;
949         }
950
951         case LFUN_TAB_DELETE: {
952                 bool const tc = bv->buffer().params().trackChanges;
953                 if (cur.selection()) {
954                         // If there is a selection, a tab (if present) is removed from
955                         // the beginning of each paragraph.
956                         cur.recordUndoSelection();
957                         pit_type const pit_end = cur.selEnd().pit();
958                         for (pit_type pit = cur.selBegin().pit(); pit <= pit_end; pit++) {
959                                 Paragraph & par = paragraphs()[pit];
960                                 if (par.getChar(0) == '\t') {
961                                         if (cur.pit() == pit)
962                                                 cur.posBackward();
963                                         if (cur.anchor_.pit() == pit && cur.anchor_.pos() > 0 )
964                                                 cur.anchor_.backwardPos();
965                                         
966                                         par.eraseChar(0, tc);
967                                 } else 
968                                         // If no tab was present, try to remove up to four spaces.
969                                         for (int n_spaces = 0;
970                                              par.getChar(0) == ' ' && n_spaces < 4; ++n_spaces) {
971                                                 if (cur.pit() == pit)
972                                                         cur.posBackward();
973                                                 if (cur.anchor_.pit() == pit && cur.anchor_.pos() > 0 )
974                                                         cur.anchor_.backwardPos();
975                                                 
976                                                 par.eraseChar(0, tc);
977                                         }
978                         }
979                         cur.finishUndo();
980                 } else {
981                         // If there is no selection, try to remove a tab or some spaces 
982                         // before the position of the cursor.
983                         Paragraph & par = paragraphs()[cur.pit()];
984                         pos_type const pos = cur.pos();
985                         
986                         if (pos == 0)
987                                 break;
988                         
989                         char_type const c = par.getChar(pos - 1);
990                         cur.recordUndo();
991                         if (c == '\t') {
992                                 cur.posBackward();
993                                 par.eraseChar(cur.pos(), tc);
994                         } else
995                                 for (int n_spaces = 0; 
996                                      cur.pos() > 0
997                                              && par.getChar(cur.pos() - 1) == ' ' 
998                                              && n_spaces < 4;
999                                      ++n_spaces) {
1000                                         cur.posBackward();
1001                                         par.eraseChar(cur.pos(), tc);
1002                                 }
1003                         cur.finishUndo();
1004                 }
1005                 break;
1006         }
1007
1008         case LFUN_CHAR_DELETE_FORWARD:
1009                 if (!cur.selection()) {
1010                         if (cur.pos() == cur.paragraph().size())
1011                                 // Par boundary, force full-screen update
1012                                 singleParUpdate = false;
1013                         needsUpdate |= erase(cur);
1014                         cur.resetAnchor();
1015                         // It is possible to make it a lot faster still
1016                         // just comment out the line below...
1017                 } else {
1018                         cutSelection(cur, true, false);
1019                         singleParUpdate = false;
1020                 }
1021                 moveCursor(cur, false);
1022                 break;
1023
1024         case LFUN_CHAR_DELETE_BACKWARD:
1025                 if (!cur.selection()) {
1026                         if (bv->getIntl().getTransManager().backspace()) {
1027                                 // Par boundary, full-screen update
1028                                 if (cur.pos() == 0)
1029                                         singleParUpdate = false;
1030                                 needsUpdate |= backspace(cur);
1031                                 cur.resetAnchor();
1032                                 // It is possible to make it a lot faster still
1033                                 // just comment out the line below...
1034                         }
1035                 } else {
1036                         cutSelection(cur, true, false);
1037                         singleParUpdate = false;
1038                 }
1039                 break;
1040
1041         case LFUN_BREAK_PARAGRAPH:
1042                 cap::replaceSelection(cur);
1043                 breakParagraph(cur, cmd.argument() == "inverse");
1044                 cur.resetAnchor();
1045                 break;
1046
1047         case LFUN_INSET_INSERT: {
1048                 cur.recordUndo();
1049
1050                 // We have to avoid triggering InstantPreview loading
1051                 // before inserting into the document. See bug #5626.
1052                 bool loaded = bv->buffer().isFullyLoaded();
1053                 bv->buffer().setFullyLoaded(false);
1054                 Inset * inset = createInset(&bv->buffer(), cmd);
1055                 bv->buffer().setFullyLoaded(loaded);
1056
1057                 if (inset) {
1058                         // FIXME (Abdel 01/02/2006):
1059                         // What follows would be a partial fix for bug 2154:
1060                         //   http://bugzilla.lyx.org/show_bug.cgi?id=2154
1061                         // This automatically put the label inset _after_ a
1062                         // numbered section. It should be possible to extend the mechanism
1063                         // to any kind of LateX environement.
1064                         // The correct way to fix that bug would be at LateX generation.
1065                         // I'll let the code here for reference as it could be used for some
1066                         // other feature like "automatic labelling".
1067                         /*
1068                         Paragraph & par = pars_[cur.pit()];
1069                         if (inset->lyxCode() == LABEL_CODE
1070                                 && par.layout().labeltype == LABEL_COUNTER) {
1071                                 // Go to the end of the paragraph
1072                                 // Warning: Because of Change-Tracking, the last
1073                                 // position is 'size()' and not 'size()-1':
1074                                 cur.pos() = par.size();
1075                                 // Insert a new paragraph
1076                                 FuncRequest fr(LFUN_BREAK_PARAGRAPH);
1077                                 dispatch(cur, fr);
1078                         }
1079                         */
1080                         if (cur.selection())
1081                                 cutSelection(cur, true, false);
1082                         cur.insert(inset);
1083                         cur.posForward();
1084
1085                         // trigger InstantPreview now
1086                         if (inset->lyxCode() == EXTERNAL_CODE) {
1087                                 InsetExternal & ins =
1088                                         static_cast<InsetExternal &>(*inset);
1089                                 ins.updatePreview();
1090                         }
1091                 }
1092
1093                 break;
1094         }
1095
1096         case LFUN_INSET_DISSOLVE: {
1097                 if (dissolveInset(cur))
1098                         needsUpdate = true;
1099                 break;
1100         }
1101
1102         case LFUN_SET_GRAPHICS_GROUP: {
1103                 InsetGraphics * ins = graphics::getCurrentGraphicsInset(cur);
1104                 if (!ins)
1105                         break;
1106
1107                 cur.recordUndo();
1108
1109                 string id = to_utf8(cmd.argument());
1110                 string grp = graphics::getGroupParams(bv->buffer(), id);
1111                 InsetGraphicsParams tmp, inspar = ins->getParams();
1112
1113                 if (id.empty())
1114                         inspar.groupId = to_utf8(cmd.argument());
1115                 else {
1116                         InsetGraphics::string2params(grp, bv->buffer(), tmp);
1117                         tmp.filename = inspar.filename;
1118                         inspar = tmp;
1119                 }
1120
1121                 ins->setParams(inspar);
1122         }
1123
1124         case LFUN_SPACE_INSERT:
1125                 if (cur.paragraph().layout().free_spacing)
1126                         insertChar(cur, ' ');
1127                 else {
1128                         doInsertInset(cur, this, cmd, false, false);
1129                         cur.posForward();
1130                 }
1131                 moveCursor(cur, false);
1132                 break;
1133
1134         case LFUN_SPECIALCHAR_INSERT: {
1135                 string const name = to_utf8(cmd.argument());
1136                 if (name == "hyphenation")
1137                         specialChar(cur, InsetSpecialChar::HYPHENATION);
1138                 else if (name == "ligature-break")
1139                         specialChar(cur, InsetSpecialChar::LIGATURE_BREAK);
1140                 else if (name == "slash")
1141                         specialChar(cur, InsetSpecialChar::SLASH);
1142                 else if (name == "nobreakdash")
1143                         specialChar(cur, InsetSpecialChar::NOBREAKDASH);
1144                 else if (name == "dots")
1145                         specialChar(cur, InsetSpecialChar::LDOTS);
1146                 else if (name == "end-of-sentence")
1147                         specialChar(cur, InsetSpecialChar::END_OF_SENTENCE);
1148                 else if (name == "menu-separator")
1149                         specialChar(cur, InsetSpecialChar::MENU_SEPARATOR);
1150                 else if (name.empty())
1151                         lyxerr << "LyX function 'specialchar-insert' needs an argument." << endl;
1152                 else
1153                         lyxerr << "Wrong argument for LyX function 'specialchar-insert'." << endl;
1154                 break;
1155         }
1156
1157         case LFUN_WORD_UPCASE:
1158                 changeCase(cur, text_uppercase);
1159                 break;
1160
1161         case LFUN_WORD_LOWCASE:
1162                 changeCase(cur, text_lowercase);
1163                 break;
1164
1165         case LFUN_WORD_CAPITALIZE:
1166                 changeCase(cur, text_capitalization);
1167                 break;
1168
1169         case LFUN_CHARS_TRANSPOSE:
1170                 charsTranspose(cur);
1171                 break;
1172
1173         case LFUN_PASTE: {
1174                 cur.message(_("Paste"));
1175                 LASSERT(cur.selBegin().idx() == cur.selEnd().idx(), /**/);
1176                 cap::replaceSelection(cur);
1177
1178                 // without argument?
1179                 string const arg = to_utf8(cmd.argument());
1180                 if (arg.empty()) {
1181                         if (theClipboard().isInternal())
1182                                 pasteFromStack(cur, bv->buffer().errorList("Paste"), 0);
1183                         else if (theClipboard().hasGraphicsContents() 
1184                                      && !theClipboard().hasTextContents())
1185                                 pasteClipboardGraphics(cur, bv->buffer().errorList("Paste"));
1186                         else
1187                                 pasteClipboardText(cur, bv->buffer().errorList("Paste"));
1188                 } else if (isStrUnsignedInt(arg)) {
1189                         // we have a numerical argument
1190                         pasteFromStack(cur, bv->buffer().errorList("Paste"),
1191                                        convert<unsigned int>(arg));
1192                 } else {
1193                         Clipboard::GraphicsType type = Clipboard::AnyGraphicsType;
1194                         if (arg == "pdf")
1195                                 type = Clipboard::PdfGraphicsType;
1196                         else if (arg == "png")
1197                                 type = Clipboard::PngGraphicsType;
1198                         else if (arg == "jpeg")
1199                                 type = Clipboard::JpegGraphicsType;
1200                         else if (arg == "linkback")
1201                                 type = Clipboard::LinkBackGraphicsType;
1202                         else if (arg == "emf")
1203                                 type = Clipboard::EmfGraphicsType;
1204                         else if (arg == "wmf")
1205                                 type = Clipboard::WmfGraphicsType;
1206
1207                         else
1208                                 LASSERT(false, /**/);
1209
1210                         pasteClipboardGraphics(cur, bv->buffer().errorList("Paste"), type);
1211                 }
1212
1213                 bv->buffer().errors("Paste");
1214                 cur.clearSelection(); // bug 393
1215                 cur.finishUndo();
1216                 break;
1217         }
1218
1219         case LFUN_CUT:
1220                 cutSelection(cur, true, true);
1221                 cur.message(_("Cut"));
1222                 break;
1223
1224         case LFUN_COPY:
1225                 copySelection(cur);
1226                 cur.message(_("Copy"));
1227                 break;
1228
1229         case LFUN_SERVER_GET_XY:
1230                 cur.message(from_utf8(
1231                         convert<string>(tm->cursorX(cur.top(), cur.boundary()))
1232                         + ' ' + convert<string>(tm->cursorY(cur.top(), cur.boundary()))));
1233                 break;
1234
1235         case LFUN_SERVER_SET_XY: {
1236                 int x = 0;
1237                 int y = 0;
1238                 istringstream is(to_utf8(cmd.argument()));
1239                 is >> x >> y;
1240                 if (!is)
1241                         lyxerr << "SETXY: Could not parse coordinates in '"
1242                                << to_utf8(cmd.argument()) << endl;
1243                 else
1244                         tm->setCursorFromCoordinates(cur, x, y);
1245                 break;
1246         }
1247
1248         case LFUN_SERVER_GET_LAYOUT:
1249                 cur.message(cur.paragraph().layout().name());
1250                 break;
1251
1252         case LFUN_LAYOUT: {
1253                 docstring layout = cmd.argument();
1254                 LYXERR(Debug::INFO, "LFUN_LAYOUT: (arg) " << to_utf8(layout));
1255
1256                 Paragraph const & para = cur.paragraph();
1257                 docstring const old_layout = para.layout().name();
1258                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1259
1260                 if (layout.empty())
1261                         layout = tclass.defaultLayoutName();
1262
1263                 if (owner_->forcePlainLayout())
1264                         // in this case only the empty layout is allowed
1265                         layout = tclass.plainLayoutName();
1266                 else if (para.usePlainLayout()) {
1267                         // in this case, default layout maps to empty layout
1268                         if (layout == tclass.defaultLayoutName())
1269                                 layout = tclass.plainLayoutName();
1270                 } else {
1271                         // otherwise, the empty layout maps to the default
1272                         if (layout == tclass.plainLayoutName())
1273                                 layout = tclass.defaultLayoutName();
1274                 }
1275
1276                 bool hasLayout = tclass.hasLayout(layout);
1277
1278                 // If the entry is obsolete, use the new one instead.
1279                 if (hasLayout) {
1280                         docstring const & obs = tclass[layout].obsoleted_by();
1281                         if (!obs.empty())
1282                                 layout = obs;
1283                 }
1284
1285                 if (!hasLayout) {
1286                         cur.errorMessage(from_utf8(N_("Layout ")) + cmd.argument() +
1287                                 from_utf8(N_(" not known")));
1288                         break;
1289                 }
1290
1291                 bool change_layout = (old_layout != layout);
1292
1293                 if (!change_layout && cur.selection() &&
1294                         cur.selBegin().pit() != cur.selEnd().pit())
1295                 {
1296                         pit_type spit = cur.selBegin().pit();
1297                         pit_type epit = cur.selEnd().pit() + 1;
1298                         while (spit != epit) {
1299                                 if (pars_[spit].layout().name() != old_layout) {
1300                                         change_layout = true;
1301                                         break;
1302                                 }
1303                                 ++spit;
1304                         }
1305                 }
1306
1307                 if (change_layout)
1308                         setLayout(cur, layout);
1309
1310                 break;
1311         }
1312
1313         case LFUN_CLIPBOARD_PASTE:
1314                 cur.clearSelection();
1315                 pasteClipboardText(cur, bv->buffer().errorList("Paste"),
1316                                cmd.argument() == "paragraph");
1317                 bv->buffer().errors("Paste");
1318                 break;
1319
1320         case LFUN_PRIMARY_SELECTION_PASTE:
1321                 pasteString(cur, theSelection().get(),
1322                             cmd.argument() == "paragraph");
1323                 break;
1324
1325         case LFUN_SELECTION_PASTE:
1326                 // Copy the selection buffer to the clipboard stack,
1327                 // because we want it to appear in the "Edit->Paste
1328                 // recent" menu.
1329                 cap::copySelectionToStack();
1330                 cap::pasteSelection(bv->cursor(), bv->buffer().errorList("Paste"));
1331                 bv->buffer().errors("Paste");
1332                 break;
1333
1334         case LFUN_UNICODE_INSERT: {
1335                 if (cmd.argument().empty())
1336                         break;
1337                 docstring hexstring = cmd.argument();
1338                 if (isHex(hexstring)) {
1339                         char_type c = hexToInt(hexstring);
1340                         if (c >= 32 && c < 0x10ffff) {
1341                                 lyxerr << "Inserting c: " << c << endl;
1342                                 docstring s = docstring(1, c);
1343                                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, s));
1344                         }
1345                 }
1346                 break;
1347         }
1348
1349         case LFUN_QUOTE_INSERT: {
1350                 Paragraph & par = cur.paragraph();
1351                 pos_type pos = cur.pos();
1352                 BufferParams const & bufparams = bv->buffer().params();
1353                 Layout const & style = par.layout();
1354                 InsetLayout const & ilayout = cur.inset().getLayout();
1355                 if (!style.pass_thru && !ilayout.isPassThru()
1356                     && par.getFontSettings(bufparams, pos).language()->lang() != "hebrew") {
1357                         // this avoids a double undo
1358                         // FIXME: should not be needed, ideally
1359                         if (!cur.selection())
1360                                 cur.recordUndo();
1361                         cap::replaceSelection(cur);
1362                         pos = cur.pos();
1363                         char_type c;
1364                         if (pos == 0)
1365                                 c = ' ';
1366                         else if (cur.prevInset() && cur.prevInset()->isSpace())
1367                                 c = ' ';
1368                         else
1369                                 c = par.getChar(pos - 1);
1370                         string arg = to_utf8(cmd.argument());
1371                         cur.insert(new InsetQuotes(cur.buffer(), c, (arg == "single")
1372                                 ? InsetQuotes::SingleQuotes : InsetQuotes::DoubleQuotes));
1373                         cur.posForward();
1374                 }
1375                 else
1376                         lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, "\""));
1377                 break;
1378         }
1379
1380         case LFUN_DATE_INSERT: {
1381                 string const format = cmd.argument().empty()
1382                         ? lyxrc.date_insert_format : to_utf8(cmd.argument());
1383                 string const time = formatted_time(current_time(), format);
1384                 lyx::dispatch(FuncRequest(LFUN_SELF_INSERT, time));
1385                 break;
1386         }
1387
1388         case LFUN_MOUSE_TRIPLE:
1389                 if (cmd.button() == mouse_button::button1) {
1390                         tm->cursorHome(cur);
1391                         cur.resetAnchor();
1392                         tm->cursorEnd(cur);
1393                         cur.setSelection();
1394                         bv->cursor() = cur;
1395                 }
1396                 break;
1397
1398         case LFUN_MOUSE_DOUBLE:
1399                 if (cmd.button() == mouse_button::button1) {
1400                         selectWord(cur, WHOLE_WORD_STRICT);
1401                         bv->cursor() = cur;
1402                 }
1403                 break;
1404
1405         // Single-click on work area
1406         case LFUN_MOUSE_PRESS:
1407                 // We are not marking a selection with the keyboard in any case.
1408                 cur.bv().cursor().setMark(false);
1409                 switch (cmd.button()) {
1410                 case mouse_button::button1:
1411                         // Set the cursor
1412                         if (!bv->mouseSetCursor(cur, cmd.argument() == "region-select"))
1413                                 cur.updateFlags(Update::SinglePar | Update::FitCursor);
1414                         break;
1415
1416                 case mouse_button::button2:
1417                         // Middle mouse pasting.
1418                         bv->mouseSetCursor(cur);
1419                         lyx::dispatch(
1420                                 FuncRequest(LFUN_COMMAND_ALTERNATIVES,
1421                                             "selection-paste ; primary-selection-paste paragraph"));
1422                         cur.noUpdate();
1423                         break;
1424
1425                 case mouse_button::button3: {
1426                         Cursor const & bvcur = cur.bv().cursor();
1427                         // Don't do anything if we right-click a
1428                         // selection, a context menu will popup.
1429                         if (bvcur.selection() && cur >= bvcur.selectionBegin()
1430                             && cur < bvcur.selectionEnd()) {
1431                                 cur.noUpdate();
1432                                 return;
1433                         }
1434                         if (!bv->mouseSetCursor(cur, false))
1435                                 cur.updateFlags(Update::SinglePar | Update::FitCursor);
1436                         break;
1437                 }
1438
1439                 default:
1440                         break;
1441                 } // switch (cmd.button())
1442                 break;
1443
1444         case LFUN_MOUSE_MOTION: {
1445                 // Mouse motion with right or middle mouse do nothing for now.
1446                 if (cmd.button() != mouse_button::button1) {
1447                         cur.noUpdate();
1448                         return;
1449                 }
1450                 // ignore motions deeper nested than the real anchor
1451                 Cursor & bvcur = cur.bv().cursor();
1452                 if (!bvcur.anchor_.hasPart(cur)) {
1453                         cur.undispatched();
1454                         break;
1455                 }
1456                 CursorSlice old = bvcur.top();
1457
1458                 int const wh = bv->workHeight();
1459                 int const y = max(0, min(wh - 1, cmd.y));
1460
1461                 tm->setCursorFromCoordinates(cur, cmd.x, y);
1462                 cur.setTargetX(cmd.x);
1463                 if (cmd.y >= wh)
1464                         lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1465                 else if (cmd.y < 0)
1466                         lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1467                 // This is to allow jumping over large insets
1468                 if (cur.top() == old) {
1469                         if (cmd.y >= wh)
1470                                 lyx::dispatch(FuncRequest(LFUN_DOWN_SELECT));
1471                         else if (cmd.y < 0)
1472                                 lyx::dispatch(FuncRequest(LFUN_UP_SELECT));
1473                 }
1474                 // We continue with our existing selection or start a new one, so don't
1475                 // reset the anchor.
1476                 bvcur.setCursor(cur);
1477                 bvcur.setSelection(true);
1478                 if (cur.top() == old) {
1479                         // We didn't move one iota, so no need to update the screen.
1480                         cur.updateFlags(Update::SinglePar | Update::FitCursor);
1481                         //cur.noUpdate();
1482                         return;
1483                 }
1484                 break;
1485         }
1486
1487         case LFUN_MOUSE_RELEASE:
1488                 switch (cmd.button()) {
1489                 case mouse_button::button1:
1490                         // Cursor was set at LFUN_MOUSE_PRESS or LFUN_MOUSE_MOTION time.
1491                         // If there is a new selection, update persistent selection;
1492                         // otherwise, single click does not clear persistent selection
1493                         // buffer.
1494                         if (cur.selection()) {
1495                                 // Finish selection. If double click,
1496                                 // cur is moved to the end of word by
1497                                 // selectWord but bvcur is current
1498                                 // mouse position.
1499                                 cur.bv().cursor().setSelection();
1500                                 // We might have removed an empty but drawn selection
1501                                 // (probably a margin)
1502                                 cur.updateFlags(Update::SinglePar | Update::FitCursor);
1503                         } else
1504                                 cur.noUpdate();
1505                         // FIXME: We could try to handle drag and drop of selection here.
1506                         return;
1507
1508                 case mouse_button::button2:
1509                         // Middle mouse pasting is handled at mouse press time,
1510                         // see LFUN_MOUSE_PRESS.
1511                         cur.noUpdate();
1512                         return;
1513
1514                 case mouse_button::button3:
1515                         // Cursor was set at LFUN_MOUSE_PRESS time.
1516                         // FIXME: If there is a selection we could try to handle a special
1517                         // drag & drop context menu.
1518                         cur.noUpdate();
1519                         return;
1520
1521                 case mouse_button::none:
1522                 case mouse_button::button4:
1523                 case mouse_button::button5:
1524                         break;
1525                 } // switch (cmd.button())
1526
1527                 break;
1528
1529         case LFUN_SELF_INSERT: {
1530                 if (cmd.argument().empty())
1531                         break;
1532
1533                 // Automatically delete the currently selected
1534                 // text and replace it with what is being
1535                 // typed in now. Depends on lyxrc settings
1536                 // "auto_region_delete", which defaults to
1537                 // true (on).
1538
1539                 if (lyxrc.auto_region_delete && cur.selection())
1540                         cutSelection(cur, false, false);
1541
1542                 cur.clearSelection();
1543
1544                 docstring::const_iterator cit = cmd.argument().begin();
1545                 docstring::const_iterator const end = cmd.argument().end();
1546                 for (; cit != end; ++cit)
1547                         bv->translateAndInsert(*cit, this, cur);
1548
1549                 cur.resetAnchor();
1550                 moveCursor(cur, false);
1551                 bv->bookmarkEditPosition();
1552                 break;
1553         }
1554
1555         case LFUN_HYPERLINK_INSERT: {
1556                 InsetCommandParams p(HYPERLINK_CODE);
1557                 docstring content;
1558                 if (cur.selection()) {
1559                         content = cur.selectionAsString(false);
1560                         cutSelection(cur, true, false);
1561                 }
1562                 p["target"] = (cmd.argument().empty()) ?
1563                         content : cmd.argument();
1564                 string const data = InsetCommand::params2string("href", p);
1565                 if (p["target"].empty()) {
1566                         bv->showDialog("href", data);
1567                 } else {
1568                         FuncRequest fr(LFUN_INSET_INSERT, data);
1569                         dispatch(cur, fr);
1570                 }
1571                 break;
1572         }
1573
1574         case LFUN_LABEL_INSERT: {
1575                 InsetCommandParams p(LABEL_CODE);
1576                 // Try to generate a valid label
1577                 p["name"] = (cmd.argument().empty()) ?
1578                         cur.getPossibleLabel() :
1579                         cmd.argument();
1580                 string const data = InsetCommand::params2string("label", p);
1581
1582                 if (cmd.argument().empty()) {
1583                         bv->showDialog("label", data);
1584                 } else {
1585                         FuncRequest fr(LFUN_INSET_INSERT, data);
1586                         dispatch(cur, fr);
1587                 }
1588                 break;
1589         }
1590
1591         case LFUN_INFO_INSERT: {
1592                 Inset * inset;
1593                 if (cmd.argument().empty() && cur.selection()) {
1594                         // if command argument is empty use current selection as parameter.
1595                         docstring ds = cur.selectionAsString(false);
1596                         cutSelection(cur, true, false);
1597                         FuncRequest cmd0(cmd, ds);
1598                         inset = createInset(cur.buffer(), cmd0);
1599                 } else {
1600                         inset = createInset(cur.buffer(), cmd);
1601                 }
1602                 if (!inset)
1603                         break;
1604                 cur.recordUndo();
1605                 insertInset(cur, inset);
1606                 cur.posForward();
1607                 break;
1608         }
1609         case LFUN_CAPTION_INSERT:
1610         case LFUN_FOOTNOTE_INSERT:
1611         case LFUN_NOTE_INSERT:
1612         case LFUN_FLEX_INSERT:
1613         case LFUN_BOX_INSERT:
1614         case LFUN_BRANCH_INSERT:
1615         case LFUN_PHANTOM_INSERT:
1616         case LFUN_ERT_INSERT:
1617         case LFUN_LISTING_INSERT:
1618         case LFUN_MARGINALNOTE_INSERT:
1619         case LFUN_OPTIONAL_INSERT:
1620         case LFUN_INDEX_INSERT:
1621                 // Open the inset, and move the current selection
1622                 // inside it.
1623                 doInsertInset(cur, this, cmd, true, true);
1624                 cur.posForward();
1625                 // Some insets are numbered, others are shown in the outline pane so
1626                 // let's update the labels and the toc backend.
1627                 bv->buffer().updateLabels();
1628                 break;
1629
1630         case LFUN_TABULAR_INSERT:
1631                 // if there were no arguments, just open the dialog
1632                 if (doInsertInset(cur, this, cmd, false, true))
1633                         cur.posForward();
1634                 else
1635                         bv->showDialog("tabularcreate");
1636
1637                 break;
1638
1639         case LFUN_FLOAT_INSERT:
1640         case LFUN_FLOAT_WIDE_INSERT:
1641         case LFUN_WRAP_INSERT: {
1642                 // will some text be moved into the inset?
1643                 bool content = cur.selection();
1644
1645                 doInsertInset(cur, this, cmd, true, true);
1646                 cur.posForward();
1647
1648                 // If some text is moved into the inset, doInsertInset 
1649                 // puts the cursor outside the inset. To insert the
1650                 // caption we put it back into the inset.
1651                 if (content)
1652                         cur.backwardPos();
1653
1654                 ParagraphList & pars = cur.text()->paragraphs();
1655
1656                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1657
1658                 // add a separate paragraph for the caption inset
1659                 pars.push_back(Paragraph());
1660                 pars.back().setInsetOwner(&cur.text()->inset());
1661                 pars.back().setPlainOrDefaultLayout(tclass);
1662                 int cap_pit = pars.size() - 1;
1663
1664                 // if an empty inset was created, we create an additional empty
1665                 // paragraph at the bottom so that the user can choose where to put
1666                 // the graphics (or table).
1667                 if (!content) {
1668                         pars.push_back(Paragraph());
1669                         pars.back().setInsetOwner(&cur.text()->inset());
1670                         pars.back().setPlainOrDefaultLayout(tclass);
1671                 }
1672
1673                 // reposition the cursor to the caption
1674                 cur.pit() = cap_pit;
1675                 cur.pos() = 0;
1676                 // FIXME: This Text/Cursor dispatch handling is a mess!
1677                 // We cannot use Cursor::dispatch here it needs access to up to
1678                 // date metrics.
1679                 FuncRequest cmd_caption(LFUN_CAPTION_INSERT);
1680                 doInsertInset(cur, cur.text(), cmd_caption, true, false);
1681                 bv->buffer().updateLabels();
1682                 cur.updateFlags(Update::Force);
1683                 // FIXME: When leaving the Float (or Wrap) inset we should
1684                 // delete any empty paragraph left above or below the
1685                 // caption.
1686                 break;
1687         }
1688
1689         case LFUN_NOMENCL_INSERT: {
1690                 InsetCommandParams p(NOMENCL_CODE);
1691                 if (cmd.argument().empty())
1692                         p["symbol"] = bv->cursor().innerText()->getStringToIndex(bv->cursor());
1693                 else
1694                         p["symbol"] = cmd.argument();
1695                 string const data = InsetCommand::params2string("nomenclature", p);
1696                 bv->showDialog("nomenclature", data);
1697                 break;
1698         }
1699
1700         case LFUN_INDEX_PRINT: {
1701                 InsetCommandParams p(INDEX_PRINT_CODE);
1702                 if (cmd.argument().empty())
1703                         p["type"] = from_ascii("idx");
1704                 else
1705                         p["type"] = cmd.argument();
1706                 string const data = InsetCommand::params2string("index_print", p);
1707                 FuncRequest fr(LFUN_INSET_INSERT, data);
1708                 dispatch(cur, fr);
1709                 break;
1710         }
1711         
1712         case LFUN_NOMENCL_PRINT:
1713         case LFUN_TOC_INSERT:
1714         case LFUN_LINE_INSERT:
1715         case LFUN_NEWPAGE_INSERT:
1716                 // do nothing fancy
1717                 doInsertInset(cur, this, cmd, false, false);
1718                 cur.posForward();
1719                 break;
1720
1721         case LFUN_DEPTH_DECREMENT:
1722                 changeDepth(cur, DEC_DEPTH);
1723                 break;
1724
1725         case LFUN_DEPTH_INCREMENT:
1726                 changeDepth(cur, INC_DEPTH);
1727                 break;
1728
1729         case LFUN_MATH_DISPLAY:
1730                 mathDispatch(cur, cmd, true);
1731                 break;
1732
1733         case LFUN_REGEXP_MODE:
1734                 regexpDispatch(cur, cmd);
1735                 break;
1736
1737         case LFUN_MATH_MODE:
1738                 if (cmd.argument() == "on")
1739                         // don't pass "on" as argument
1740                         mathDispatch(cur, FuncRequest(LFUN_MATH_MODE), false);
1741                 else
1742                         mathDispatch(cur, cmd, false);
1743                 break;
1744
1745         case LFUN_MATH_MACRO:
1746                 if (cmd.argument().empty())
1747                         cur.errorMessage(from_utf8(N_("Missing argument")));
1748                 else {
1749                         string s = to_utf8(cmd.argument());
1750                         string const s1 = token(s, ' ', 1);
1751                         int const nargs = s1.empty() ? 0 : convert<int>(s1);
1752                         string const s2 = token(s, ' ', 2);
1753                         MacroType type = MacroTypeNewcommand;
1754                         if (s2 == "def")
1755                                 type = MacroTypeDef;
1756                         MathMacroTemplate * inset = new MathMacroTemplate(cur.buffer(),
1757                                 from_utf8(token(s, ' ', 0)), nargs, false, type);
1758                         inset->setBuffer(bv->buffer());
1759                         insertInset(cur, inset);
1760
1761                         // enter macro inset and select the name
1762                         cur.push(*inset);
1763                         cur.top().pos() = cur.top().lastpos();
1764                         cur.resetAnchor();
1765                         cur.setSelection(true);
1766                         cur.top().pos() = 0;
1767                 }
1768                 break;
1769
1770         // passthrough hat and underscore outside mathed:
1771         case LFUN_MATH_SUBSCRIPT:
1772                 mathDispatch(cur, FuncRequest(LFUN_SELF_INSERT, "_"), false);
1773                 break;
1774         case LFUN_MATH_SUPERSCRIPT:
1775                 mathDispatch(cur, FuncRequest(LFUN_SELF_INSERT, "^"), false);
1776                 break;
1777
1778         case LFUN_MATH_INSERT:
1779         case LFUN_MATH_AMS_MATRIX:
1780         case LFUN_MATH_MATRIX:
1781         case LFUN_MATH_DELIM:
1782         case LFUN_MATH_BIGDELIM: {
1783                 cur.recordUndo();
1784                 cap::replaceSelection(cur);
1785                 cur.insert(new InsetMathHull(cur.buffer(), hullSimple));
1786                 checkAndActivateInset(cur, true);
1787                 LASSERT(cur.inMathed(), /**/);
1788                 cur.dispatch(cmd);
1789                 break;
1790         }
1791
1792         case LFUN_FONT_EMPH: {
1793                 Font font(ignore_font, ignore_language);
1794                 font.fontInfo().setEmph(FONT_TOGGLE);
1795                 toggleAndShow(cur, this, font);
1796                 break;
1797         }
1798
1799         case LFUN_FONT_ITAL: {
1800                 Font font(ignore_font, ignore_language);
1801                 font.fontInfo().setShape(ITALIC_SHAPE);
1802                 toggleAndShow(cur, this, font);
1803                 break;
1804         }
1805
1806         case LFUN_FONT_BOLD:
1807         case LFUN_FONT_BOLDSYMBOL: {
1808                 Font font(ignore_font, ignore_language);
1809                 font.fontInfo().setSeries(BOLD_SERIES);
1810                 toggleAndShow(cur, this, font);
1811                 break;
1812         }
1813
1814         case LFUN_FONT_NOUN: {
1815                 Font font(ignore_font, ignore_language);
1816                 font.fontInfo().setNoun(FONT_TOGGLE);
1817                 toggleAndShow(cur, this, font);
1818                 break;
1819         }
1820
1821         case LFUN_FONT_TYPEWRITER: {
1822                 Font font(ignore_font, ignore_language);
1823                 font.fontInfo().setFamily(TYPEWRITER_FAMILY); // no good
1824                 toggleAndShow(cur, this, font);
1825                 break;
1826         }
1827
1828         case LFUN_FONT_SANS: {
1829                 Font font(ignore_font, ignore_language);
1830                 font.fontInfo().setFamily(SANS_FAMILY);
1831                 toggleAndShow(cur, this, font);
1832                 break;
1833         }
1834
1835         case LFUN_FONT_ROMAN: {
1836                 Font font(ignore_font, ignore_language);
1837                 font.fontInfo().setFamily(ROMAN_FAMILY);
1838                 toggleAndShow(cur, this, font);
1839                 break;
1840         }
1841
1842         case LFUN_FONT_DEFAULT: {
1843                 Font font(inherit_font, ignore_language);
1844                 toggleAndShow(cur, this, font);
1845                 break;
1846         }
1847
1848         case LFUN_FONT_STRIKEOUT: {
1849                 Font font(ignore_font, ignore_language);
1850                 font.fontInfo().setStrikeout(FONT_TOGGLE);
1851                 toggleAndShow(cur, this, font);
1852                 break;
1853         }
1854
1855         case LFUN_FONT_UULINE: {
1856                 Font font(ignore_font, ignore_language);
1857                 font.fontInfo().setUuline(FONT_TOGGLE);
1858                 toggleAndShow(cur, this, font);
1859                 break;
1860         }
1861
1862         case LFUN_FONT_UWAVE: {
1863                 Font font(ignore_font, ignore_language);
1864                 font.fontInfo().setUwave(FONT_TOGGLE);
1865                 toggleAndShow(cur, this, font);
1866                 break;
1867         }
1868
1869         case LFUN_FONT_UNDERLINE: {
1870                 Font font(ignore_font, ignore_language);
1871                 font.fontInfo().setUnderbar(FONT_TOGGLE);
1872                 toggleAndShow(cur, this, font);
1873                 break;
1874         }
1875
1876         case LFUN_FONT_SIZE: {
1877                 Font font(ignore_font, ignore_language);
1878                 setLyXSize(to_utf8(cmd.argument()), font.fontInfo());
1879                 toggleAndShow(cur, this, font);
1880                 break;
1881         }
1882
1883         case LFUN_LANGUAGE: {
1884                 Language const * lang = languages.getLanguage(to_utf8(cmd.argument()));
1885                 if (!lang)
1886                         break;
1887                 Font font(ignore_font, lang);
1888                 toggleAndShow(cur, this, font);
1889                 break;
1890         }
1891
1892         case LFUN_TEXTSTYLE_APPLY:
1893                 toggleAndShow(cur, this, freefont, toggleall);
1894                 cur.message(_("Character set"));
1895                 break;
1896
1897         // Set the freefont using the contents of \param data dispatched from
1898         // the frontends and apply it at the current cursor location.
1899         case LFUN_TEXTSTYLE_UPDATE: {
1900                 Font font;
1901                 bool toggle;
1902                 if (font.fromString(to_utf8(cmd.argument()), toggle)) {
1903                         freefont = font;
1904                         toggleall = toggle;
1905                         toggleAndShow(cur, this, freefont, toggleall);
1906                         cur.message(_("Character set"));
1907                 } else {
1908                         lyxerr << "Argument not ok";
1909                 }
1910                 break;
1911         }
1912
1913         case LFUN_FINISHED_LEFT:
1914                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_LEFT:\n" << cur);
1915                 // We're leaving an inset, going left. If the inset is LTR, we're
1916                 // leaving from the front, so we should not move (remain at --- but
1917                 // not in --- the inset). If the inset is RTL, move left, without
1918                 // entering the inset itself; i.e., move to after the inset.
1919                 if (cur.paragraph().getFontSettings(
1920                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
1921                         cursorVisLeft(cur, true);
1922                 break;
1923
1924         case LFUN_FINISHED_RIGHT:
1925                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_RIGHT:\n" << cur);
1926                 // We're leaving an inset, going right. If the inset is RTL, we're
1927                 // leaving from the front, so we should not move (remain at --- but
1928                 // not in --- the inset). If the inset is LTR, move right, without
1929                 // entering the inset itself; i.e., move to after the inset.
1930                 if (!cur.paragraph().getFontSettings(
1931                                 cur.bv().buffer().params(), cur.pos()).isRightToLeft())
1932                         cursorVisRight(cur, true);
1933                 break;
1934
1935         case LFUN_FINISHED_BACKWARD:
1936                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_BACKWARD:\n" << cur);
1937                 break;
1938
1939         case LFUN_FINISHED_FORWARD:
1940                 LYXERR(Debug::DEBUG, "handle LFUN_FINISHED_FORWARD:\n" << cur);
1941                 ++cur.pos();
1942                 cur.setCurrentFont();
1943                 break;
1944
1945         case LFUN_LAYOUT_PARAGRAPH: {
1946                 string data;
1947                 params2string(cur.paragraph(), data);
1948                 data = "show\n" + data;
1949                 bv->showDialog("paragraph", data);
1950                 break;
1951         }
1952
1953         case LFUN_PARAGRAPH_UPDATE: {
1954                 string data;
1955                 params2string(cur.paragraph(), data);
1956
1957                 // Will the paragraph accept changes from the dialog?
1958                 bool const accept =
1959                         cur.inset().allowParagraphCustomization(cur.idx());
1960
1961                 data = "update " + convert<string>(accept) + '\n' + data;
1962                 bv->updateDialog("paragraph", data);
1963                 break;
1964         }
1965
1966         case LFUN_ACCENT_UMLAUT:
1967         case LFUN_ACCENT_CIRCUMFLEX:
1968         case LFUN_ACCENT_GRAVE:
1969         case LFUN_ACCENT_ACUTE:
1970         case LFUN_ACCENT_TILDE:
1971         case LFUN_ACCENT_CEDILLA:
1972         case LFUN_ACCENT_MACRON:
1973         case LFUN_ACCENT_DOT:
1974         case LFUN_ACCENT_UNDERDOT:
1975         case LFUN_ACCENT_UNDERBAR:
1976         case LFUN_ACCENT_CARON:
1977         case LFUN_ACCENT_BREVE:
1978         case LFUN_ACCENT_TIE:
1979         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
1980         case LFUN_ACCENT_CIRCLE:
1981         case LFUN_ACCENT_OGONEK:
1982                 theApp()->handleKeyFunc(cmd.action);
1983                 if (!cmd.argument().empty())
1984                         // FIXME: Are all these characters encoded in one byte in utf8?
1985                         bv->translateAndInsert(cmd.argument()[0], this, cur);
1986                 break;
1987
1988         case LFUN_FLOAT_LIST_INSERT: {
1989                 DocumentClass const & tclass = bv->buffer().params().documentClass();
1990                 if (tclass.floats().typeExist(to_utf8(cmd.argument()))) {
1991                         cur.recordUndo();
1992                         if (cur.selection())
1993                                 cutSelection(cur, true, false);
1994                         breakParagraph(cur);
1995
1996                         if (cur.lastpos() != 0) {
1997                                 cursorBackward(cur);
1998                                 breakParagraph(cur);
1999                         }
2000
2001                         docstring const laystr = cur.inset().usePlainLayout() ?
2002                                 tclass.plainLayoutName() :
2003                                 tclass.defaultLayoutName();
2004                         setLayout(cur, laystr);
2005                         ParagraphParameters p;
2006                         // FIXME If this call were replaced with one to clearParagraphParams(),
2007                         // then we could get rid of this method altogether.
2008                         setParagraphs(cur, p);
2009                         // FIXME This should be simplified when InsetFloatList takes a
2010                         // Buffer in its constructor.
2011                         InsetFloatList * ifl = new InsetFloatList(to_utf8(cmd.argument()));
2012                         ifl->setBuffer(bv->buffer());
2013                         insertInset(cur, ifl);
2014                         cur.posForward();
2015                 } else {
2016                         lyxerr << "Non-existent float type: "
2017                                << to_utf8(cmd.argument()) << endl;
2018                 }
2019                 break;
2020         }
2021
2022         case LFUN_CHANGE_ACCEPT: {
2023                 acceptOrRejectChanges(cur, ACCEPT);
2024                 break;
2025         }
2026
2027         case LFUN_CHANGE_REJECT: {
2028                 acceptOrRejectChanges(cur, REJECT);
2029                 break;
2030         }
2031
2032         case LFUN_THESAURUS_ENTRY: {
2033                 docstring arg = cmd.argument();
2034                 if (arg.empty()) {
2035                         arg = cur.selectionAsString(false);
2036                         // FIXME
2037                         if (arg.size() > 100 || arg.empty()) {
2038                                 // Get word or selection
2039                                 selectWordWhenUnderCursor(cur, WHOLE_WORD);
2040                                 arg = cur.selectionAsString(false);
2041                                 arg += " lang=" + from_ascii(cur.getFont().language()->lang());
2042                         }
2043                 }
2044                 bv->showDialog("thesaurus", to_utf8(arg));
2045                 break;
2046         }
2047
2048         case LFUN_PARAGRAPH_PARAMS_APPLY: {
2049                 // Given data, an encoding of the ParagraphParameters
2050                 // generated in the Paragraph dialog, this function sets
2051                 // the current paragraph, or currently selected paragraphs,
2052                 // appropriately.
2053                 // NOTE: This function overrides all existing settings.
2054                 setParagraphs(cur, cmd.argument());
2055                 cur.message(_("Paragraph layout set"));
2056                 break;
2057         }
2058
2059         case LFUN_PARAGRAPH_PARAMS: {
2060                 // Given data, an encoding of the ParagraphParameters as we'd
2061                 // find them in a LyX file, this function modifies the current paragraph,
2062                 // or currently selected paragraphs.
2063                 // NOTE: This function only modifies, and does not override, existing
2064                 // settings.
2065                 setParagraphs(cur, cmd.argument(), true);
2066                 cur.message(_("Paragraph layout set"));
2067                 break;
2068         }
2069
2070         case LFUN_ESCAPE:
2071                 if (cur.selection()) {
2072                         cur.setSelection(false);
2073                 } else {
2074                         cur.undispatched();
2075                         // This used to be LFUN_FINISHED_RIGHT, I think FORWARD is more
2076                         // correct, but I'm not 100% sure -- dov, 071019
2077                         cmd = FuncRequest(LFUN_FINISHED_FORWARD);
2078                 }
2079                 break;
2080
2081         case LFUN_OUTLINE_UP:
2082                 outline(OutlineUp, cur);
2083                 setCursor(cur, cur.pit(), 0);
2084                 cur.buffer()->updateLabels();
2085                 needsUpdate = true;
2086                 break;
2087
2088         case LFUN_OUTLINE_DOWN:
2089                 outline(OutlineDown, cur);
2090                 setCursor(cur, cur.pit(), 0);
2091                 cur.buffer()->updateLabels();
2092                 needsUpdate = true;
2093                 break;
2094
2095         case LFUN_OUTLINE_IN:
2096                 outline(OutlineIn, cur);
2097                 cur.buffer()->updateLabels();
2098                 needsUpdate = true;
2099                 break;
2100
2101         case LFUN_OUTLINE_OUT:
2102                 outline(OutlineOut, cur);
2103                 cur.buffer()->updateLabels();
2104                 needsUpdate = true;
2105                 break;
2106         
2107         case LFUN_OUTLINE_DRAGMOVE: {
2108                 int const move_id = convert<int>(cmd.getArg(0));
2109                 int const move_to_id = convert<int>(cmd.getArg(1));
2110                 dragMove(cur, move_id, move_to_id);
2111                 setCursor(cur, cur.pit(), 0);
2112                 cur.buffer()->updateLabels();
2113                 needsUpdate = true;
2114                 break;
2115         }
2116
2117         default:
2118                 LYXERR(Debug::ACTION, "Command " << cmd << " not DISPATCHED by Text");
2119                 cur.undispatched();
2120                 break;
2121         }
2122
2123         needsUpdate |= (cur.pos() != cur.lastpos()) && cur.selection();
2124
2125         // FIXME: The cursor flag is reset two lines below
2126         // so we need to check here if some of the LFUN did touch that.
2127         // for now only Text::erase() and Text::backspace() do that.
2128         // The plan is to verify all the LFUNs and then to remove this
2129         // singleParUpdate boolean altogether.
2130         if (cur.result().update() & Update::Force) {
2131                 singleParUpdate = false;
2132                 needsUpdate = true;
2133         }
2134
2135         // FIXME: the following code should go in favor of fine grained
2136         // update flag treatment.
2137         if (singleParUpdate) {
2138                 // Inserting characters does not change par height in general. So, try
2139                 // to update _only_ this paragraph. BufferView will detect if a full
2140                 // metrics update is needed anyway.
2141                 cur.updateFlags(Update::SinglePar | Update::FitCursor);
2142                 return;
2143         }
2144
2145         if (!needsUpdate
2146             && &oldTopSlice.inset() == &cur.inset()
2147             && oldTopSlice.idx() == cur.idx()
2148             && !sel // sel is a backup of cur.selection() at the beginning of the function.
2149             && !cur.selection())
2150                 // FIXME: it would be better if we could just do this
2151                 //
2152                 //if (cur.result().update() != Update::FitCursor)
2153                 //      cur.noUpdate();
2154                 //
2155                 // But some LFUNs do not set Update::FitCursor when needed, so we
2156                 // do it for all. This is not very harmfull as FitCursor will provoke
2157                 // a full redraw only if needed but still, a proper review of all LFUN
2158                 // should be done and this needsUpdate boolean can then be removed.
2159                 cur.updateFlags(Update::FitCursor);
2160         else
2161                 cur.updateFlags(Update::Force | Update::FitCursor);
2162 }
2163
2164
2165 bool Text::getStatus(Cursor & cur, FuncRequest const & cmd,
2166                         FuncStatus & flag) const
2167 {
2168         LASSERT(cur.text() == this, /**/);
2169
2170         FontInfo const & fontinfo = cur.real_current_font.fontInfo();
2171         bool enable = true;
2172         InsetCode code = NO_CODE;
2173
2174         switch (cmd.action) {
2175
2176         case LFUN_DEPTH_DECREMENT:
2177                 enable = changeDepthAllowed(cur, DEC_DEPTH);
2178                 break;
2179
2180         case LFUN_DEPTH_INCREMENT:
2181                 enable = changeDepthAllowed(cur, INC_DEPTH);
2182                 break;
2183
2184         case LFUN_APPENDIX:
2185                 flag.setOnOff(cur.paragraph().params().startOfAppendix());
2186                 break;
2187
2188         case LFUN_DIALOG_SHOW_NEW_INSET:
2189                 if (cmd.argument() == "bibitem")
2190                         code = BIBITEM_CODE;
2191                 else if (cmd.argument() == "bibtex") {
2192                         code = BIBTEX_CODE;
2193                         // not allowed in description items
2194                         enable = !inDescriptionItem(cur);
2195                 }
2196                 else if (cmd.argument() == "box")
2197                         code = BOX_CODE;
2198                 else if (cmd.argument() == "branch")
2199                         code = BRANCH_CODE;
2200                 else if (cmd.argument() == "citation")
2201                         code = CITE_CODE;
2202                 else if (cmd.argument() == "ert")
2203                         code = ERT_CODE;
2204                 else if (cmd.argument() == "external")
2205                         code = EXTERNAL_CODE;
2206                 else if (cmd.argument() == "float")
2207                         code = FLOAT_CODE;
2208                 else if (cmd.argument() == "graphics")
2209                         code = GRAPHICS_CODE;
2210                 else if (cmd.argument() == "href")
2211                         code = HYPERLINK_CODE;
2212                 else if (cmd.argument() == "include")
2213                         code = INCLUDE_CODE;
2214                 else if (cmd.argument() == "index")
2215                         code = INDEX_CODE;
2216                 else if (cmd.argument() == "index_print")
2217                         code = INDEX_PRINT_CODE;
2218                 else if (cmd.argument() == "nomenclature")
2219                         code = NOMENCL_CODE;
2220                 else if (cmd.argument() == "nomencl_print")
2221                         code = NOMENCL_PRINT_CODE;
2222                 else if (cmd.argument() == "label")
2223                         code = LABEL_CODE;
2224                 else if (cmd.argument() == "note")
2225                         code = NOTE_CODE;
2226                 else if (cmd.argument() == "phantom")
2227                         code = PHANTOM_CODE;
2228                 else if (cmd.argument() == "ref")
2229                         code = REF_CODE;
2230                 else if (cmd.argument() == "space")
2231                         code = SPACE_CODE;
2232                 else if (cmd.argument() == "toc")
2233                         code = TOC_CODE;
2234                 else if (cmd.argument() == "vspace")
2235                         code = VSPACE_CODE;
2236                 else if (cmd.argument() == "wrap")
2237                         code = WRAP_CODE;
2238                 else if (cmd.argument() == "listings")
2239                         code = LISTINGS_CODE;
2240                 break;
2241
2242         case LFUN_ERT_INSERT:
2243                 code = ERT_CODE;
2244                 break;
2245         case LFUN_LISTING_INSERT:
2246                 code = LISTINGS_CODE;
2247                 // not allowed in description items
2248                 enable = !inDescriptionItem(cur);
2249                 break;
2250         case LFUN_FOOTNOTE_INSERT:
2251                 code = FOOT_CODE;
2252                 break;
2253         case LFUN_TABULAR_INSERT:
2254                 code = TABULAR_CODE;
2255                 break;
2256         case LFUN_MARGINALNOTE_INSERT:
2257                 code = MARGIN_CODE;
2258                 break;
2259         case LFUN_FLOAT_INSERT:
2260         case LFUN_FLOAT_WIDE_INSERT:
2261                 // FIXME: If there is a selection, we should check whether there
2262                 // are floats in the selection, but this has performance issues, see
2263                 // LFUN_CHANGE_ACCEPT/REJECT.
2264                 code = FLOAT_CODE;
2265                 if (inDescriptionItem(cur))
2266                         // not allowed in description items
2267                         enable = false;
2268                 else {
2269                         InsetCode const inset_code = cur.inset().lyxCode();
2270
2271                         // algorithm floats cannot be put in another float
2272                         if (to_utf8(cmd.argument()) == "algorithm") {
2273                                 enable = inset_code != WRAP_CODE && inset_code != FLOAT_CODE;
2274                                 break;
2275                         }
2276
2277                         // for figures and tables: only allow in another
2278                         // float or wrap if it is of the same type and
2279                         // not a subfloat already
2280                         if(cur.inset().lyxCode() == code) {
2281                                 InsetFloat const & ins =
2282                                         static_cast<InsetFloat const &>(cur.inset());
2283                                 enable = ins.params().type == to_utf8(cmd.argument())
2284                                         && !ins.params().subfloat;
2285                         } else if(cur.inset().lyxCode() == WRAP_CODE) {
2286                                 InsetWrap const & ins =
2287                                         static_cast<InsetWrap const &>(cur.inset());
2288                                 enable = ins.params().type == to_utf8(cmd.argument());
2289                         }
2290                 }
2291                 break;
2292         case LFUN_WRAP_INSERT:
2293                 code = WRAP_CODE;
2294                 // not allowed in description items
2295                 enable = !inDescriptionItem(cur);
2296                 break;
2297         case LFUN_FLOAT_LIST_INSERT:
2298                 code = FLOAT_LIST_CODE;
2299                 // not allowed in description items
2300                 enable = !inDescriptionItem(cur);
2301                 break;
2302         case LFUN_CAPTION_INSERT:
2303                 code = CAPTION_CODE;
2304                 // not allowed in description items
2305                 enable = !inDescriptionItem(cur);
2306                 break;
2307         case LFUN_NOTE_INSERT:
2308                 code = NOTE_CODE;
2309                 // in commands (sections etc.) and description items,
2310                 // only Notes are allowed
2311                 enable = (cmd.argument().empty() || cmd.getArg(0) == "Note" ||
2312                           (!cur.paragraph().layout().isCommand()
2313                            && !inDescriptionItem(cur)));
2314                 break;
2315         case LFUN_FLEX_INSERT: {
2316                 code = FLEX_CODE;
2317                 string s = cmd.getArg(0);
2318                 InsetLayout il =
2319                         cur.buffer()->params().documentClass().insetLayout(from_utf8(s));
2320                 if (il.lyxtype() != InsetLayout::CHARSTYLE &&
2321                     il.lyxtype() != InsetLayout::CUSTOM &&
2322                     il.lyxtype() != InsetLayout::ELEMENT &&
2323                     il.lyxtype ()!= InsetLayout::STANDARD)
2324                         enable = false;
2325                 break;
2326                 }
2327         case LFUN_BOX_INSERT:
2328                 code = BOX_CODE;
2329                 break;
2330         case LFUN_BRANCH_INSERT:
2331                 code = BRANCH_CODE;
2332                 if (cur.buffer()->masterBuffer()->params().branchlist().empty()
2333                     && cur.buffer()->params().branchlist().empty())
2334                         enable = false;
2335                 break;
2336         case LFUN_PHANTOM_INSERT:
2337                 code = PHANTOM_CODE;
2338                 break;
2339         case LFUN_LABEL_INSERT:
2340                 code = LABEL_CODE;
2341                 break;
2342         case LFUN_LINE_INSERT:
2343                 code = LINE_CODE;
2344                 break;
2345         case LFUN_INFO_INSERT:
2346                 code = INFO_CODE;
2347                 break;
2348         case LFUN_OPTIONAL_INSERT:
2349                 code = OPTARG_CODE;
2350                 enable = cur.paragraph().insetList().count(OPTARG_CODE)
2351                         < cur.paragraph().layout().optionalargs;
2352                 break;
2353         case LFUN_INDEX_INSERT:
2354                 code = INDEX_CODE;
2355                 break;
2356         case LFUN_INDEX_PRINT:
2357                 code = INDEX_PRINT_CODE;
2358                 // not allowed in description items
2359                 enable = !inDescriptionItem(cur);
2360                 break;
2361         case LFUN_NOMENCL_INSERT:
2362                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
2363                         enable = false;
2364                         break;
2365                 }
2366                 code = NOMENCL_CODE;
2367                 break;
2368         case LFUN_NOMENCL_PRINT:
2369                 code = NOMENCL_PRINT_CODE;
2370                 // not allowed in description items
2371                 enable = !inDescriptionItem(cur);
2372                 break;
2373         case LFUN_TOC_INSERT:
2374                 code = TOC_CODE;
2375                 // not allowed in description items
2376                 enable = !inDescriptionItem(cur);
2377                 break;
2378         case LFUN_HYPERLINK_INSERT:
2379                 if (cur.selIsMultiCell() || cur.selIsMultiLine()) {
2380                         enable = false;
2381                         break;
2382                 }
2383                 code = HYPERLINK_CODE;
2384                 break;
2385         case LFUN_QUOTE_INSERT:
2386                 // always allow this, since we will inset a raw quote
2387                 // if an inset is not allowed.
2388                 break;
2389         case LFUN_SPECIALCHAR_INSERT:
2390                 code = SPECIALCHAR_CODE;
2391                 break;
2392         case LFUN_SPACE_INSERT:
2393                 // slight hack: we know this is allowed in math mode
2394                 if (cur.inTexted())
2395                         code = SPACE_CODE;
2396                 break;
2397
2398         case LFUN_MATH_INSERT:
2399         case LFUN_MATH_AMS_MATRIX:
2400         case LFUN_MATH_MATRIX:
2401         case LFUN_MATH_DELIM:
2402         case LFUN_MATH_BIGDELIM:
2403         case LFUN_MATH_DISPLAY:
2404         case LFUN_MATH_MODE:
2405         case LFUN_MATH_MACRO:
2406         case LFUN_MATH_SUBSCRIPT:
2407         case LFUN_MATH_SUPERSCRIPT:
2408                 code = MATH_HULL_CODE;
2409                 break;
2410
2411         case LFUN_INSET_MODIFY:
2412                 // We need to disable this, because we may get called for a
2413                 // tabular cell via
2414                 // InsetTabular::getStatus() -> InsetText::getStatus()
2415                 // and we don't handle LFUN_INSET_MODIFY.
2416                 enable = false;
2417                 break;
2418
2419         case LFUN_FONT_EMPH:
2420                 flag.setOnOff(fontinfo.emph() == FONT_ON);
2421                 break;
2422
2423         case LFUN_FONT_ITAL:
2424                 flag.setOnOff(fontinfo.shape() == ITALIC_SHAPE);
2425                 break;
2426
2427         case LFUN_FONT_NOUN:
2428                 flag.setOnOff(fontinfo.noun() == FONT_ON);
2429                 break;
2430
2431         case LFUN_FONT_BOLD:
2432         case LFUN_FONT_BOLDSYMBOL:
2433                 flag.setOnOff(fontinfo.series() == BOLD_SERIES);
2434                 break;
2435
2436         case LFUN_FONT_SANS:
2437                 flag.setOnOff(fontinfo.family() == SANS_FAMILY);
2438                 break;
2439
2440         case LFUN_FONT_ROMAN:
2441                 flag.setOnOff(fontinfo.family() == ROMAN_FAMILY);
2442                 break;
2443
2444         case LFUN_FONT_TYPEWRITER:
2445                 flag.setOnOff(fontinfo.family() == TYPEWRITER_FAMILY);
2446                 break;
2447
2448         case LFUN_CUT:
2449         case LFUN_COPY:
2450                 enable = cur.selection();
2451                 break;
2452
2453         case LFUN_PASTE: {
2454                 if (cmd.argument().empty()) {
2455                         if (theClipboard().isInternal())
2456                                 enable = cap::numberOfSelections() > 0;
2457                         else
2458                                 enable = !theClipboard().empty();
2459                         break;
2460                 }
2461
2462                 // we have an argument
2463                 string const arg = to_utf8(cmd.argument());
2464                 if (isStrUnsignedInt(arg)) {
2465                         // it's a number and therefore means the internal stack
2466                         unsigned int n = convert<unsigned int>(arg);
2467                         enable = cap::numberOfSelections() > n;
2468                         break;
2469                 }
2470
2471                 // explicit graphics type?
2472                 Clipboard::GraphicsType type = Clipboard::AnyGraphicsType;
2473                 if ((arg == "pdf" && (type = Clipboard::PdfGraphicsType))
2474                           || (arg == "png" && (type = Clipboard::PngGraphicsType))
2475                           || (arg == "jpeg" && (type = Clipboard::JpegGraphicsType))
2476                           || (arg == "linkback" &&  (type = Clipboard::LinkBackGraphicsType))
2477                           || (arg == "emf" &&  (type = Clipboard::EmfGraphicsType))
2478                           || (arg == "wmf" &&  (type = Clipboard::WmfGraphicsType))) {
2479                         enable = theClipboard().hasGraphicsContents(type);
2480                         break;
2481                 }
2482
2483                 // unknown argument
2484                 enable = false;
2485                 break;
2486          }
2487
2488         case LFUN_CLIPBOARD_PASTE:
2489                 enable = !theClipboard().empty();
2490                 break;
2491
2492         case LFUN_PRIMARY_SELECTION_PASTE:
2493                 enable = cur.selection() || !theSelection().empty();
2494                 break;
2495
2496         case LFUN_SELECTION_PASTE:
2497                 enable = cap::selection();
2498                 break;
2499
2500         case LFUN_PARAGRAPH_MOVE_UP:
2501                 enable = cur.pit() > 0 && !cur.selection();
2502                 break;
2503
2504         case LFUN_PARAGRAPH_MOVE_DOWN:
2505                 enable = cur.pit() < cur.lastpit() && !cur.selection();
2506                 break;
2507
2508         case LFUN_CHANGE_ACCEPT:
2509         case LFUN_CHANGE_REJECT:
2510                 // In principle, these LFUNs should only be enabled if there
2511                 // is a change at the current position/in the current selection.
2512                 // However, without proper optimizations, this will inevitably
2513                 // result in unacceptable performance - just imagine a user who
2514                 // wants to select the complete content of a long document.
2515                 if (!cur.selection())
2516                         enable = cur.paragraph().isChanged(cur.pos());
2517                 else
2518                         // TODO: context-sensitive enabling of LFUN_CHANGE_ACCEPT/REJECT
2519                         // for selections.
2520                         enable = true;
2521                 break;
2522
2523         case LFUN_OUTLINE_UP:
2524         case LFUN_OUTLINE_DOWN:
2525         case LFUN_OUTLINE_IN:
2526         case LFUN_OUTLINE_OUT:
2527         case LFUN_OUTLINE_DRAGMOVE:
2528                 // FIXME: LyX is not ready for outlining within inset.
2529                 enable = isMainText()
2530                         && cur.paragraph().layout().toclevel != Layout::NOT_IN_TOC;
2531                 break;
2532
2533         case LFUN_NEWLINE_INSERT:
2534                 // LaTeX restrictions (labels or empty par)
2535                 enable = (cur.pos() > cur.paragraph().beginOfBody());
2536                 break;
2537
2538         case LFUN_TAB_INSERT:
2539         case LFUN_TAB_DELETE:
2540                 enable = cur.inset().getLayout().isPassThru();
2541                 break;
2542
2543         case LFUN_SET_GRAPHICS_GROUP: {
2544                 InsetGraphics * ins = graphics::getCurrentGraphicsInset(cur);
2545                 if (!ins)
2546                         enable = false;
2547                 else
2548                         flag.setOnOff(to_utf8(cmd.argument()) == ins->getParams().groupId);
2549                 break;
2550         }
2551
2552         case LFUN_NEWPAGE_INSERT:
2553                 // not allowed in description items
2554                 code = NEWPAGE_CODE;
2555                 enable = !inDescriptionItem(cur);
2556                 break;
2557
2558         case LFUN_DATE_INSERT: {
2559                 string const format = cmd.argument().empty()
2560                         ? lyxrc.date_insert_format : to_utf8(cmd.argument());
2561                 enable = support::os::is_valid_strftime(format);
2562                 break;
2563         }
2564
2565         case LFUN_LANGUAGE:
2566                 enable = !cur.inset().getLayout().isPassThru();
2567                 break;
2568
2569         case LFUN_BREAK_PARAGRAPH:
2570                 enable = cur.inset().getLayout().isMultiPar();
2571                 break;
2572
2573         case LFUN_WORD_DELETE_FORWARD:
2574         case LFUN_WORD_DELETE_BACKWARD:
2575         case LFUN_LINE_DELETE:
2576         case LFUN_WORD_FORWARD:
2577         case LFUN_WORD_BACKWARD:
2578         case LFUN_WORD_RIGHT:
2579         case LFUN_WORD_LEFT:
2580         case LFUN_CHAR_FORWARD:
2581         case LFUN_CHAR_FORWARD_SELECT:
2582         case LFUN_CHAR_BACKWARD:
2583         case LFUN_CHAR_BACKWARD_SELECT:
2584         case LFUN_CHAR_LEFT:
2585         case LFUN_CHAR_LEFT_SELECT:
2586         case LFUN_CHAR_RIGHT:
2587         case LFUN_CHAR_RIGHT_SELECT:
2588         case LFUN_UP:
2589         case LFUN_UP_SELECT:
2590         case LFUN_DOWN:
2591         case LFUN_DOWN_SELECT:
2592         case LFUN_PARAGRAPH_UP_SELECT:
2593         case LFUN_PARAGRAPH_DOWN_SELECT:
2594         case LFUN_LINE_BEGIN_SELECT:
2595         case LFUN_LINE_END_SELECT:
2596         case LFUN_WORD_FORWARD_SELECT:
2597         case LFUN_WORD_BACKWARD_SELECT:
2598         case LFUN_WORD_RIGHT_SELECT:
2599         case LFUN_WORD_LEFT_SELECT:
2600         case LFUN_WORD_SELECT:
2601         case LFUN_SECTION_SELECT:
2602         case LFUN_PARAGRAPH_UP:
2603         case LFUN_PARAGRAPH_DOWN:
2604         case LFUN_LINE_BEGIN:
2605         case LFUN_LINE_END:
2606         case LFUN_CHAR_DELETE_FORWARD:
2607         case LFUN_CHAR_DELETE_BACKWARD:
2608         case LFUN_INSET_INSERT:
2609         case LFUN_WORD_UPCASE:
2610         case LFUN_WORD_LOWCASE:
2611         case LFUN_WORD_CAPITALIZE:
2612         case LFUN_CHARS_TRANSPOSE:
2613         case LFUN_SERVER_GET_XY:
2614         case LFUN_SERVER_SET_XY:
2615         case LFUN_SERVER_GET_LAYOUT:
2616         case LFUN_LAYOUT:
2617         case LFUN_SELF_INSERT:
2618         case LFUN_FONT_DEFAULT:
2619         case LFUN_FONT_UNDERLINE:
2620         case LFUN_FONT_STRIKEOUT:
2621         case LFUN_FONT_UULINE:
2622         case LFUN_FONT_UWAVE:
2623         case LFUN_FONT_SIZE:
2624         case LFUN_TEXTSTYLE_APPLY:
2625         case LFUN_TEXTSTYLE_UPDATE:
2626         case LFUN_LAYOUT_PARAGRAPH:
2627         case LFUN_PARAGRAPH_UPDATE:
2628         case LFUN_ACCENT_UMLAUT:
2629         case LFUN_ACCENT_CIRCUMFLEX:
2630         case LFUN_ACCENT_GRAVE:
2631         case LFUN_ACCENT_ACUTE:
2632         case LFUN_ACCENT_TILDE:
2633         case LFUN_ACCENT_CEDILLA:
2634         case LFUN_ACCENT_MACRON:
2635         case LFUN_ACCENT_DOT:
2636         case LFUN_ACCENT_UNDERDOT:
2637         case LFUN_ACCENT_UNDERBAR:
2638         case LFUN_ACCENT_CARON:
2639         case LFUN_ACCENT_BREVE:
2640         case LFUN_ACCENT_TIE:
2641         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
2642         case LFUN_ACCENT_CIRCLE:
2643         case LFUN_ACCENT_OGONEK:
2644         case LFUN_THESAURUS_ENTRY:
2645         case LFUN_PARAGRAPH_PARAMS_APPLY:
2646         case LFUN_PARAGRAPH_PARAMS:
2647         case LFUN_ESCAPE:
2648         case LFUN_BUFFER_BEGIN:
2649         case LFUN_BUFFER_END:
2650         case LFUN_BUFFER_BEGIN_SELECT:
2651         case LFUN_BUFFER_END_SELECT:
2652         case LFUN_INSET_BEGIN:
2653         case LFUN_INSET_END:
2654         case LFUN_INSET_BEGIN_SELECT:
2655         case LFUN_INSET_END_SELECT:
2656         case LFUN_INSET_SELECT_ALL:
2657         case LFUN_UNICODE_INSERT:
2658                 // these are handled in our dispatch()
2659                 enable = true;
2660                 break;
2661
2662         default:
2663                 return false;
2664         }
2665
2666         if (code != NO_CODE
2667             && (cur.empty() 
2668                 || !cur.inset().insetAllowed(code)
2669                 || cur.paragraph().layout().pass_thru))
2670                 enable = false;
2671
2672         switch (cmd.action) {
2673         case LFUN_ACCENT_ACUTE:
2674         case LFUN_ACCENT_BREVE:
2675         case LFUN_ACCENT_CARON:
2676         case LFUN_ACCENT_CEDILLA:
2677         case LFUN_ACCENT_CIRCLE:
2678         case LFUN_ACCENT_CIRCUMFLEX:
2679         case LFUN_ACCENT_DOT:
2680         case LFUN_ACCENT_GRAVE:
2681         case LFUN_ACCENT_HUNGARIAN_UMLAUT:
2682         case LFUN_ACCENT_MACRON:
2683         case LFUN_ACCENT_OGONEK:
2684         case LFUN_ACCENT_TIE:
2685         case LFUN_ACCENT_TILDE:
2686         case LFUN_ACCENT_UMLAUT:
2687         case LFUN_ACCENT_UNDERBAR:
2688         case LFUN_ACCENT_UNDERDOT:
2689         case LFUN_FONT_BOLD:
2690         case LFUN_FONT_BOLDSYMBOL:
2691         case LFUN_FONT_TYPEWRITER:
2692         case LFUN_FONT_DEFAULT:
2693         case LFUN_FONT_EMPH:
2694         case LFUN_FONT_NOUN:
2695         case LFUN_FONT_ROMAN:
2696         case LFUN_FONT_SANS:
2697         case LFUN_FONT_FRAK:
2698         case LFUN_FONT_ITAL:
2699         case LFUN_FONT_SIZE:
2700         case LFUN_FONT_STATE:
2701         case LFUN_FONT_UNDERLINE:
2702         case LFUN_FONT_STRIKEOUT:
2703         case LFUN_FONT_UULINE:
2704         case LFUN_FONT_UWAVE:
2705         case LFUN_TEXTSTYLE_APPLY:
2706         case LFUN_TEXTSTYLE_UPDATE:
2707                 if (cur.inset().getLayout().isPassThru())
2708                         enable = false;
2709                 break;
2710         default:
2711                 break;
2712         }
2713
2714         flag.setEnabled(enable);
2715         return true;
2716 }
2717
2718
2719 void Text::pasteString(Cursor & cur, docstring const & clip,
2720                 bool asParagraphs)
2721 {
2722         cur.clearSelection();
2723         if (!clip.empty()) {
2724                 cur.recordUndo();
2725                 if (asParagraphs)
2726                         insertStringAsParagraphs(cur, clip, cur.current_font);
2727                 else
2728                         insertStringAsLines(cur, clip, cur.current_font);
2729         }
2730 }
2731
2732
2733 // FIXME: an item inset would make things much easier.
2734 bool Text::inDescriptionItem(Cursor & cur) const
2735 {
2736         Paragraph & par = cur.paragraph();
2737         pos_type const pos = cur.pos();
2738         pos_type const body_pos = par.beginOfBody();
2739
2740         if (par.layout().latextype != LATEX_LIST_ENVIRONMENT
2741             && (par.layout().latextype != LATEX_ITEM_ENVIRONMENT
2742                 || par.layout().margintype != MARGIN_FIRST_DYNAMIC))
2743                 return false;
2744
2745         return (pos < body_pos
2746                 || (pos == body_pos
2747                     && (pos == 0 || par.getChar(pos - 1) != ' ')));
2748 }
2749
2750 } // namespace lyx