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