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