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