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