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