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