]> git.lyx.org Git - lyx.git/blob - src/BufferView_pimpl.C
move getParFromID to Buffer
[lyx.git] / src / BufferView_pimpl.C
1 #include <config.h>
2
3 #include <ctime>
4 #include <unistd.h>
5 #include <sys/wait.h>
6 #include <locale.h>
7
8 #ifdef __GNUG__
9 #pragma implementation
10 #endif
11
12 #include "BufferView_pimpl.h"
13 #include "WorkArea.h"
14 #include "lyxscreen.h"
15 #include "lyxtext.h"
16 #include "lyxrow.h"
17 #include "LyXView.h"
18 #include "commandtags.h"
19 #include "lyxfunc.h"
20 #include "font.h"
21 #include "bufferview_funcs.h"
22 #include "TextCache.h"
23 #include "bufferlist.h"
24 #include "lyx_gui_misc.h"
25 #include "lyxrc.h"
26 #include "intl.h"
27 #include "support/LAssert.h"
28 #include "frontends/Dialogs.h"
29 #include "insets/insetbib.h"
30 #include "insets/insettext.h"
31 /// added for Dispatch functions
32 #include "lyx_cb.h"
33 #include "frontends/FileDialog.h"
34 #include "lyx_main.h"
35 #include "FloatList.h"
36 #include "support/filetools.h"
37 #include "support/lyxfunctional.h"
38 #include "insets/inseturl.h"
39 #include "insets/insetlatexaccent.h"
40 #include "insets/insettoc.h"
41 #include "insets/insetref.h"
42 #include "insets/insetparent.h"
43 #include "insets/insetindex.h"
44 #include "insets/insetinfo.h"
45 #include "insets/insetinclude.h"
46 #include "insets/insetcite.h"
47 #include "insets/insetert.h"
48 #include "insets/insetexternal.h"
49 #include "insets/insetgraphics.h"
50 #include "insets/insetfoot.h"
51 #include "insets/insetmarginal.h"
52 #include "insets/insetminipage.h"
53 #include "insets/insetfloat.h"
54 #include "insets/insetlist.h"
55 #include "insets/insettabular.h"
56 #include "insets/insettheorem.h"
57 #include "insets/insetcaption.h"
58 #include "insets/insetfloatlist.h"
59 #include "insets/insetspecialchar.h"
60 #include "gettext.h"
61 #include "ParagraphParameters.h"
62 #include "undo_funcs.h"
63 #include "mathed/formulabase.h"
64
65 extern LyXTextClass::size_type current_layout;
66 extern int greek_kb_flag;
67
68 using std::vector;
69 using std::find_if;
70 using std::find;
71 using std::pair;
72 using std::endl;
73 using std::make_pair;
74 using std::min;
75 using SigC::slot;
76
77 /* the selection possible is needed, that only motion events are 
78  * used, where the bottom press event was on the drawing area too */
79 bool selection_possible = false;
80
81 extern BufferList bufferlist;
82 extern char ascii_type;
83
84 extern bool math_insert_greek(BufferView *, char);
85 extern void sigchldhandler(pid_t pid, int * status);
86 extern int bibitemMaxWidth(BufferView *, LyXFont const &);
87
88
89 namespace {
90
91 const unsigned int saved_positions_num = 20;
92
93 inline
94 void waitForX()
95 {
96         XSync(fl_get_display(), 0);
97 }
98
99
100 void SetXtermCursor(Window win)
101 {
102         static Cursor cursor;
103         static bool cursor_undefined = true;
104         if (cursor_undefined){
105                 cursor = XCreateFontCursor(fl_get_display(), XC_xterm);
106                 XFlush(fl_get_display());
107                 cursor_undefined = false;
108         }
109         XDefineCursor(fl_get_display(), win, cursor);
110         XFlush(fl_get_display());
111 }
112
113 } // anon namespace
114
115
116 BufferView::Pimpl::Pimpl(BufferView * b, LyXView * o,
117              int xpos, int ypos, int width, int height)
118         : bv_(b), owner_(o), buffer_(0),
119           current_scrollbar_value(0), cursor_timeout(400),
120           workarea_(xpos, ypos, width, height), using_xterm_cursor(false),
121           inset_slept(false)
122 {
123         // Setup the signals
124         workarea_.scrollCB.connect(slot(this, &BufferView::Pimpl::scrollCB));
125         workarea_.workAreaExpose
126                 .connect(slot(this, &BufferView::Pimpl::workAreaExpose));
127         workarea_.workAreaEnter
128                 .connect(slot(this, &BufferView::Pimpl::enterView));
129         workarea_.workAreaLeave
130                 .connect(slot(this, &BufferView::Pimpl::leaveView));
131         workarea_.workAreaButtonPress
132                 .connect(slot(this, &BufferView::Pimpl::workAreaButtonPress));
133         workarea_.workAreaButtonRelease
134                 .connect(slot(this,
135                               &BufferView::Pimpl::workAreaButtonRelease));
136         workarea_.workAreaMotionNotify
137                 .connect(slot(this, &BufferView::Pimpl::workAreaMotionNotify));
138         workarea_.workAreaDoubleClick
139                 .connect(slot(this, &BufferView::Pimpl::doubleClick));
140         workarea_.workAreaTripleClick
141                 .connect(slot(this, &BufferView::Pimpl::tripleClick));
142         workarea_.workAreaKeyPress
143                 .connect(slot(this, &BufferView::Pimpl::workAreaKeyPress));
144         
145         cursor_timeout.timeout.connect(slot(this,
146                                             &BufferView::Pimpl::cursorToggle));
147         cursor_timeout.start();
148         workarea_.setFocus();
149         saved_positions.resize(saved_positions_num);
150 }
151
152
153 Painter & BufferView::Pimpl::painter() 
154 {
155         return workarea_.getPainter();
156 }
157
158
159 void BufferView::Pimpl::buffer(Buffer * b)
160 {
161         lyxerr[Debug::INFO] << "Setting buffer in BufferView ("
162                             << b << ")" << endl;
163         if (buffer_) {
164                 insetSleep();
165                 buffer_->delUser(bv_);
166
167                 // Put the old text into the TextCache, but
168                 // only if the buffer is still loaded.
169                 // Also set the owner of the test to 0
170                 //              bv_->text->owner(0);
171                 textcache.add(buffer_, workarea_.workWidth(), bv_->text);
172                 if (lyxerr.debugging())
173                         textcache.show(lyxerr, "BufferView::buffer");
174                 
175                 bv_->text = 0;
176         }
177
178         // Set current buffer
179         buffer_ = b;
180
181         if (bufferlist.getState() == BufferList::CLOSING) return;
182         
183         // Nuke old image
184         // screen is always deleted when the buffer is changed.
185         screen_.reset(0);
186
187         // If we are closing the buffer, use the first buffer as current
188         if (!buffer_) {
189                 buffer_ = bufferlist.first();
190         }
191
192         if (buffer_) {
193                 lyxerr[Debug::INFO] << "Buffer addr: " << buffer_ << endl;
194                 buffer_->addUser(bv_);
195                 // If we don't have a text object for this, we make one
196                 if (bv_->text == 0) {
197                         resizeCurrentBuffer();
198                 } else {
199                         updateScreen();
200                         updateScrollbar();
201                 }
202                 bv_->text->first = screen_->topCursorVisible(bv_->text);
203                 owner_->updateMenubar();
204                 owner_->updateToolbar();
205                 // Similarly, buffer-dependent dialogs should be updated or
206                 // hidden. This should go here because some dialogs (eg ToC)
207                 // require bv_->text.
208                 owner_->getDialogs()->updateBufferDependent(true);
209                 redraw();
210                 insetWakeup();
211         } else {
212                 lyxerr[Debug::INFO] << "  No Buffer!" << endl;
213                 owner_->updateMenubar();
214                 owner_->updateToolbar();
215                 owner_->getDialogs()->hideBufferDependent();
216                 updateScrollbar();
217                 workarea_.redraw();
218
219                 // Also remove all remaining text's from the testcache.
220                 // (there should not be any!) (if there is any it is a
221                 // bug!)
222                 if (lyxerr.debugging())
223                         textcache.show(lyxerr, "buffer delete all");
224                 textcache.clear();
225         }
226         // should update layoutchoice even if we don't have a buffer.
227         owner_->updateLayoutChoice();
228
229         owner_->updateWindowTitle();
230 }
231
232
233 void BufferView::Pimpl::resize(int xpos, int ypos, int width, int height)
234 {
235         workarea_.resize(xpos, ypos, width, height);
236         update(bv_->text, SELECT);
237         redraw();
238 }
239
240
241 void BufferView::Pimpl::resize()
242 {
243         if (buffer_)
244                 resizeCurrentBuffer();
245 }
246
247
248 void BufferView::Pimpl::redraw()
249 {
250         lyxerr[Debug::INFO] << "BufferView::redraw()" << endl;
251         workarea_.redraw();
252 }
253
254
255 bool BufferView::Pimpl::fitCursor(LyXText * text)
256 {
257         lyx::Assert(screen_.get());
258
259         bv_->owner()->getDialogs()->updateParagraph();
260
261         bool const ret = screen_->fitCursor(text, bv_);
262         if (ret)
263             updateScrollbar();
264         return ret;
265 }
266
267
268 void BufferView::Pimpl::redoCurrentBuffer()
269 {
270         lyxerr[Debug::INFO] << "BufferView::redoCurrentBuffer" << endl;
271         if (buffer_ && bv_->text) {
272                 resize();
273                 owner_->updateLayoutChoice();
274         }
275 }
276
277
278 int BufferView::Pimpl::resizeCurrentBuffer()
279 {
280         lyxerr[Debug::INFO] << "resizeCurrentBuffer" << endl;
281         
282         Paragraph * par = 0;
283         Paragraph * selstartpar = 0;
284         Paragraph * selendpar = 0;
285         UpdatableInset * the_locking_inset = 0;
286         
287         Paragraph::size_type pos = 0;
288         Paragraph::size_type selstartpos = 0;
289         Paragraph::size_type selendpos = 0;
290         bool selection = false;
291         bool mark_set  = false;
292
293         owner_->prohibitInput();
294
295         owner_->message(_("Formatting document..."));
296
297         if (bv_->text) {
298                 par = bv_->text->cursor.par();
299                 pos = bv_->text->cursor.pos();
300                 selstartpar = bv_->text->selection.start.par();
301                 selstartpos = bv_->text->selection.start.pos();
302                 selendpar = bv_->text->selection.end.par();
303                 selendpos = bv_->text->selection.end.pos();
304                 selection = bv_->text->selection.set();
305                 mark_set = bv_->text->selection.mark();
306                 the_locking_inset = bv_->theLockingInset();
307                 delete bv_->text;
308                 bv_->text = new LyXText(bv_);
309                 bv_->text->init(bv_);
310         } else {
311                 // See if we have a text in TextCache that fits
312                 // the new buffer_ with the correct width.
313                 bv_->text = textcache.findFit(buffer_, workarea_.workWidth());
314                 if (bv_->text) {
315                         if (lyxerr.debugging()) {
316                                 lyxerr << "Found a LyXText that fits:\n";
317                                 textcache.show(lyxerr, make_pair(buffer_, make_pair(workarea_.workWidth(), bv_->text)));
318                         }
319                         // Set the owner of the newly found text
320                         //      bv_->text->owner(bv_);
321                         if (lyxerr.debugging())
322                                 textcache.show(lyxerr, "resizeCurrentBuffer");
323                 } else {
324                         bv_->text = new LyXText(bv_);
325                         bv_->text->init(bv_);
326                 }
327         }
328         updateScreen();
329
330         if (par) {
331                 bv_->text->selection.set(true);
332                 /* at this point just to avoid the Delete-Empty-Paragraph
333                  * Mechanism when setting the cursor */
334                 bv_->text->selection.mark(mark_set);
335                 if (selection) {
336                         bv_->text->setCursor(bv_, selstartpar, selstartpos);
337                         bv_->text->selection.cursor = bv_->text->cursor;
338                         bv_->text->setCursor(bv_, selendpar, selendpos);
339                         bv_->text->setSelection(bv_);
340                         bv_->text->setCursor(bv_, par, pos);
341                 } else {
342                         bv_->text->setCursor(bv_, par, pos);
343                         bv_->text->selection.cursor = bv_->text->cursor;
344                         bv_->text->selection.set(false);
345                 }
346                 // remake the inset locking
347                 bv_->theLockingInset(the_locking_inset);
348         }
349         bv_->text->first = screen_->topCursorVisible(bv_->text);
350         buffer_->resizeInsets(bv_);
351         // this will scroll the screen such that the cursor becomes visible
352         updateScrollbar();
353         redraw();
354
355         setState();
356         owner_->allowInput();
357
358         /// clear the "Formatting Document" message 
359         owner_->message("");
360  
361         /// get rid of the splash screen if it's not gone already
362         owner_->getDialogs()->destroySplash();
363  
364         return 0;
365 }
366
367
368 void BufferView::Pimpl::updateScreen()
369 {
370         // Regenerate the screen.
371         screen_.reset(new LyXScreen(workarea_));
372 }
373
374
375 void BufferView::Pimpl::updateScrollbar()
376 {
377         /* If the text is smaller than the working area, the scrollbar
378          * maximum must be the working area height. No scrolling will 
379          * be possible */
380
381         if (!bv_->text) {
382                 workarea_.setScrollbar(0, 1.0);
383                 return;
384         }
385
386         long const text_height = bv_->text->height;
387
388         double const lineh = bv_->text->defaultHeight();
389         double const slider_size = 1.0 / double(text_height);
390
391         static long old_text_height;
392         static double old_lineh;
393         static double old_slider_size;
394
395         if (text_height != old_text_height) {
396                 workarea_.setScrollbarBounds(0, text_height - workarea_.height());
397                 old_text_height = text_height;
398         }
399         if (lineh != old_lineh) {
400                 workarea_.setScrollbarIncrements(lineh);
401                 old_lineh = lineh;
402         }
403         if (current_scrollbar_value != bv_->text->first
404             || slider_size != old_slider_size) {
405                 current_scrollbar_value = bv_->text->first;
406                 workarea_.setScrollbar(current_scrollbar_value, slider_size);
407                 old_slider_size = slider_size;
408         }
409 }
410
411
412 // Callback for scrollbar slider
413 void BufferView::Pimpl::scrollCB(double value)
414 {
415         if (!buffer_) return;
416
417         current_scrollbar_value = long(value);
418         if (current_scrollbar_value < 0)
419                 current_scrollbar_value = 0;
420    
421         if (!screen_.get())
422                 return;
423
424         screen_->draw(bv_->text, bv_, current_scrollbar_value);
425
426         if (!lyxrc.cursor_follows_scrollbar) {
427                 waitForX();
428                 return;
429         }
430  
431         LyXText * vbt = bv_->text;
432  
433         int const height = vbt->defaultHeight();
434         int const first = static_cast<int>((bv_->text->first + height));
435         int const last = static_cast<int>((bv_->text->first + workarea_.height() - height));
436
437         if (vbt->cursor.y() < first)
438                 vbt->setCursorFromCoordinates(bv_, 0, first);
439         else if (vbt->cursor.y() > last)
440                 vbt->setCursorFromCoordinates(bv_, 0, last);
441
442         waitForX();
443 }
444
445
446 int BufferView::Pimpl::scrollUp(long time)
447 {
448         if (!buffer_) return 0;
449         if (!screen_.get()) return 0;
450    
451         double value = workarea_.getScrollbarValue();
452    
453         if (value == 0) return 0;
454
455         float add_value =  (bv_->text->defaultHeight()
456                             + float(time) * float(time) * 0.125);
457    
458         if (add_value > workarea_.height())
459                 add_value = float(workarea_.height() -
460                                   bv_->text->defaultHeight());
461    
462         value -= add_value;
463
464         if (value < 0)
465                 value = 0;
466    
467         workarea_.setScrollbarValue(value);
468    
469         scrollCB(value); 
470         return 0;
471 }
472
473
474 int BufferView::Pimpl::scrollDown(long time)
475 {
476         if (!buffer_) return 0;
477         if (!screen_.get()) return 0;
478    
479         double value = workarea_.getScrollbarValue();
480         pair<float, float> p = workarea_.getScrollbarBounds();
481         double const max = p.second;
482         
483         if (value == max) return 0;
484
485         float add_value =  (bv_->text->defaultHeight()
486                             + float(time) * float(time) * 0.125);
487    
488         if (add_value > workarea_.height())
489                 add_value = float(workarea_.height() -
490                                   bv_->text->defaultHeight());
491    
492         value += add_value;
493    
494         if (value > max)
495                 value = max;
496
497         workarea_.setScrollbarValue(value);
498         
499         scrollCB(value); 
500         return 0;
501 }
502
503
504 void BufferView::Pimpl::workAreaKeyPress(KeySym keysym, unsigned int state)
505 {
506         bv_->owner()->getLyXFunc()->processKeySym(keysym, state);
507 }
508
509
510 void BufferView::Pimpl::workAreaMotionNotify(int x, int y, unsigned int state)
511 {
512         // Only use motion with button 1
513         if (!(state & Button1MotionMask))
514                 return;
515
516         if (!buffer_ || !screen_.get()) return;
517
518         // Check for inset locking
519         if (bv_->theLockingInset()) {
520                 LyXCursor cursor = bv_->text->cursor;
521                 LyXFont font = bv_->text->getFont(buffer_,
522                                                   cursor.par(), cursor.pos());
523                 int width = bv_->theLockingInset()->width(bv_, font);
524                 int inset_x = font.isVisibleRightToLeft()
525                         ? cursor.x() - width : cursor.x();
526                 int start_x = inset_x + bv_->theLockingInset()->scroll();
527                 bv_->theLockingInset()->
528                         insetMotionNotify(bv_,
529                                           x - start_x,
530                                           y - cursor.y() + bv_->text->first,
531                                           state);
532                 return;
533         }
534    
535         /* The test for not selection possible is needed, that only motion
536            events are used, where the bottom press event was on
537            the drawing area too */
538         if (!selection_possible)
539                 return;
540  
541         screen_->hideCursor();
542
543         bv_->text->setCursorFromCoordinates(bv_, x, y + bv_->text->first);
544       
545         if (!bv_->text->selection.set())
546                 update(bv_->text, BufferView::UPDATE); // Maybe an empty line was deleted
547       
548         bv_->text->setSelection(bv_);
549         screen_->toggleToggle(bv_->text, bv_);
550         fitCursor(bv_->text);
551         screen_->showCursor(bv_->text, bv_);
552 }
553
554
555 // Single-click on work area
556 void BufferView::Pimpl::workAreaButtonPress(int xpos, int ypos,
557                                             unsigned int button)
558 {
559         if (!buffer_ || !screen_.get()) return;
560
561         Inset * inset_hit = checkInsetHit(bv_->text, xpos, ypos, button);
562
563         // ok ok, this is a hack.
564         if (button == 4 || button == 5) {
565                 switch (button) {
566                 case 4:
567                         scrollUp(lyxrc.wheel_jump); // default 100, set in lyxrc
568                         break;
569                 case 5:
570                         scrollDown(lyxrc.wheel_jump);
571                         break;
572                 }
573         }
574         
575         if (bv_->theLockingInset()) {
576                 // We are in inset locking mode
577                 
578                 /* Check whether the inset was hit. If not reset mode,
579                    otherwise give the event to the inset */
580                 if (inset_hit == bv_->theLockingInset()) {
581                         bv_->theLockingInset()->
582                                 insetButtonPress(bv_,
583                                                  xpos, ypos,
584                                                  button);
585                         return;
586                 } else {
587                         bv_->unlockInset(bv_->theLockingInset());
588                 }
589         }
590         
591         if (!inset_hit)
592                 selection_possible = true;
593         screen_->hideCursor();
594
595         int const screen_first = bv_->text->first;
596         
597         // Middle button press pastes if we have a selection
598         bool paste_internally = false;
599         if (button == 2
600             && bv_->text->selection.set()) {
601                 owner_->getLyXFunc()->Dispatch(LFUN_COPY);
602                 paste_internally = true;
603         }
604         
605         // Clear the selection
606         screen_->toggleSelection(bv_->text, bv_);
607         bv_->text->clearSelection(bv_);
608         bv_->text->fullRebreak(bv_);
609         screen_->update(bv_->text, bv_);
610         updateScrollbar();
611         
612         // Single left click in math inset?
613         if ((inset_hit != 0) &&
614             (inset_hit->editable()==Inset::HIGHLY_EDITABLE)) {
615                 // Highly editable inset, like math
616                 UpdatableInset * inset = static_cast<UpdatableInset *>(inset_hit);
617                 selection_possible = false;
618                 owner_->updateLayoutChoice();
619                 owner_->message(inset->editMessage());
620                 inset->insetButtonPress(bv_, xpos, ypos, button);
621                 inset->edit(bv_, xpos, ypos, button);
622                 return;
623         } 
624         
625         // Right click on a footnote flag opens float menu
626         if (button == 3) { 
627                 selection_possible = false;
628                 return;
629         }
630         
631         if (!inset_hit) // otherwise it was already set in checkInsetHit(...)
632                 bv_->text->setCursorFromCoordinates(bv_, xpos, ypos + screen_first);
633         finishUndo();
634         bv_->text->selection.cursor = bv_->text->cursor;
635         bv_->text->cursor.x_fix(bv_->text->cursor.x());
636         
637         owner_->updateLayoutChoice();
638         if (fitCursor(bv_->text)) {
639                 selection_possible = false;
640         }
641         
642         // Insert primary selection with middle mouse
643         // if there is a local selection in the current buffer,
644         // insert this
645         if (button == 2) {
646                 if (paste_internally)
647                         owner_->getLyXFunc()->Dispatch(LFUN_PASTE);
648                 else
649                         owner_->getLyXFunc()->Dispatch(LFUN_PASTESELECTION,
650                                                        "paragraph");
651                 selection_possible = false;
652                 return;
653         }
654 }
655
656
657 void BufferView::Pimpl::doubleClick(int /*x*/, int /*y*/, unsigned int button) 
658 {
659         // select a word
660         if (!buffer_)
661             return;
662
663         LyXText * text = bv_->getLyXText();
664
665         if (text->bv_owner && bv_->theLockingInset())
666             return;
667
668         if (screen_.get() && button == 1) {
669             if (text->bv_owner) {
670                 screen_->hideCursor();
671                 screen_->toggleSelection(text, bv_);
672                 text->selectWord(bv_);
673                 screen_->toggleSelection(text, bv_, false);
674             } else {
675                 text->selectWord(bv_);
676             }
677             /* This will fit the cursor on the screen
678              * if necessary */
679             update(text, BufferView::SELECT|BufferView::FITCUR);
680         }
681 }
682
683
684 void BufferView::Pimpl::tripleClick(int /*x*/, int /*y*/, unsigned int button)
685 {
686         // select a line
687         if (buffer_)
688                 return;
689
690         LyXText * text = bv_->getLyXText();
691
692         if (text->bv_owner && bv_->theLockingInset())
693             return;
694
695         if (screen_.get() && (button == 1)) {
696                 screen_->hideCursor();
697                 screen_->toggleSelection(text, bv_);
698                 text->cursorHome(bv_);
699                 text->selection.cursor = text->cursor;
700                 text->cursorEnd(bv_);
701                 text->setSelection(bv_);
702                 screen_->toggleSelection(text, bv_, false);
703                 /* This will fit the cursor on the screen
704                  * if necessary */
705                 update(text, BufferView::SELECT|BufferView::FITCUR);
706         }
707 }
708
709
710 void BufferView::Pimpl::enterView()
711 {
712         if (active() && available()) {
713                 SetXtermCursor(workarea_.getWin());
714                 using_xterm_cursor = true;
715         }
716 }
717
718
719 void BufferView::Pimpl::leaveView()
720 {
721         if (using_xterm_cursor) {
722                 XUndefineCursor(fl_get_display(), workarea_.getWin());
723                 using_xterm_cursor = false;
724         }
725 }
726
727
728 void BufferView::Pimpl::workAreaButtonRelease(int x, int y,
729                                               unsigned int button)
730 {
731         if (!buffer_ || !screen_.get()) return;
732
733         // If we hit an inset, we have the inset coordinates in these
734         // and inset_hit points to the inset.  If we do not hit an
735         // inset, inset_hit is 0, and inset_x == x, inset_y == y.
736         Inset * inset_hit = checkInsetHit(bv_->text, x, y, button);
737
738         if (bv_->theLockingInset()) {
739                 // We are in inset locking mode.
740
741                 /* LyX does a kind of work-area grabbing for insets.
742                    Only a ButtonPress Event outside the inset will 
743                    force a insetUnlock. */
744                 bv_->theLockingInset()->
745                         insetButtonRelease(bv_, x, y, button);
746                 return;
747         }
748         
749         selection_possible = false;
750         
751         if (button == 2)
752                 return;
753
754         setState();
755         owner_->showState();
756
757         // Did we hit an editable inset?
758         if (inset_hit) {
759                 // Inset like error, notes and figures
760                 selection_possible = false;
761
762                 // CHECK fix this proper in 0.13
763
764                 // Following a ref shouldn't issue
765                 // a push on the undo-stack
766                 // anylonger, now that we have
767                 // keybindings for following
768                 // references and returning from
769                 // references.  IMHO though, it
770                 // should be the inset's own business
771                 // to push or not push on the undo
772                 // stack. They don't *have* to
773                 // alter the document...
774                 // (Joacim)
775                 // ...or maybe the SetCursorParUndo()
776                 // below isn't necessary at all anylonger?
777                 if (inset_hit->lyxCode() == Inset::REF_CODE) {
778                         setCursorParUndo(bv_);
779                 }
780
781                 owner_->message(inset_hit->editMessage());
782
783                 if (inset_hit->editable()==Inset::HIGHLY_EDITABLE) {
784                         // Highly editable inset, like math
785                         UpdatableInset *inset = (UpdatableInset *)inset_hit;
786                         inset->insetButtonRelease(bv_, x, y, button);
787                 } else {
788                         inset_hit->insetButtonRelease(bv_, x, y, button);
789                         inset_hit->edit(bv_, x, y, button);
790                 }
791                 return;
792         }
793
794         // check whether we want to open a float
795         if (bv_->text) {
796                 bool hit = false;
797                 char c = ' ';
798                 if (bv_->text->cursor.pos() <
799                     bv_->text->cursor.par()->size()) {
800                         c = bv_->text->cursor.par()->
801                                 getChar(bv_->text->cursor.pos());
802                 }
803                         if (bv_->text->cursor.pos() - 1 >= 0) {
804                         c = bv_->text->cursor.par()->
805                                 getChar(bv_->text->cursor.pos() - 1);
806                 }
807                 if (hit == true) {
808                         selection_possible = false;
809                         return;
810                 }
811         }
812
813         // Maybe we want to edit a bibitem ale970302
814         if (bv_->text->cursor.par()->bibkey && x < 20 + 
815             bibitemMaxWidth(bv_, textclasslist.
816                             TextClass(buffer_->
817                                       params.textclass).defaultfont())) {
818                 bv_->text->cursor.par()->bibkey->edit(bv_, 0, 0, 0);
819         }
820
821         return;
822 }
823
824
825 /* 
826  * Returns an inset if inset was hit. 0 otherwise.
827  * If hit, the coordinates are changed relative to the inset. 
828  * Otherwise coordinates are not changed, and false is returned.
829  */
830 Inset * BufferView::Pimpl::checkInsetHit(LyXText * text, int & x, int & y,
831                                          unsigned int /* button */)
832 {
833         if (!screen_.get())
834                 return 0;
835   
836         int y_tmp = y + text->first;
837   
838         LyXCursor cursor;
839         text->setCursorFromCoordinates(bv_, cursor, x, y_tmp);
840         text->setCursor(bv_, cursor, cursor.par(),cursor.pos(),true);
841
842
843         if (cursor.pos() < cursor.par()->size()
844             && cursor.par()->getChar(cursor.pos()) == Paragraph::META_INSET
845             && cursor.par()->getInset(cursor.pos())
846             && cursor.par()->getInset(cursor.pos())->editable()) {
847
848                 // Check whether the inset really was hit
849                 Inset * tmpinset = cursor.par()->getInset(cursor.pos());
850                 LyXFont font = text->getFont(buffer_,
851                                                   cursor.par(), cursor.pos());
852                 int const width = tmpinset->width(bv_, font);
853                 int const inset_x = font.isVisibleRightToLeft()
854                         ? cursor.x() - width : cursor.x();
855                 int const start_x = inset_x + tmpinset->scroll();
856                 int const end_x = inset_x + width;
857
858                 if (x > start_x && x < end_x
859                     && y_tmp > cursor.y() - tmpinset->ascent(bv_, font)
860                     && y_tmp < cursor.y() + tmpinset->descent(bv_, font)) {
861                         text->setCursor(bv_, cursor.par(),cursor.pos(), true);
862                         x = x - start_x;
863                         // The origin of an inset is on the baseline
864                         y = y_tmp - (text->cursor.y()); 
865                         return tmpinset;
866                 }
867         }
868
869         if ((cursor.pos() - 1 >= 0) &&
870             (cursor.par()->getChar(cursor.pos()-1) == Paragraph::META_INSET) &&
871             (cursor.par()->getInset(cursor.pos() - 1)) &&
872             (cursor.par()->getInset(cursor.pos() - 1)->editable())) {
873                 Inset * tmpinset = cursor.par()->getInset(cursor.pos()-1);
874                 LyXFont font = text->getFont(buffer_, cursor.par(),
875                                                   cursor.pos()-1);
876                 int const width = tmpinset->width(bv_, font);
877                 int const inset_x = font.isVisibleRightToLeft()
878                         ? cursor.x() : cursor.x() - width;
879                 int const start_x = inset_x + tmpinset->scroll();
880                 int const end_x = inset_x + width;
881
882                 if (x > start_x && x < end_x
883                     && y_tmp > cursor.y() - tmpinset->ascent(bv_, font)
884                     && y_tmp < cursor.y() + tmpinset->descent(bv_, font)) {
885 #if 0
886                         if (move_cursor && (tmpinset != bv_->theLockingInset()))
887 #endif
888                                 text->setCursor(bv_, cursor.par(),
889                                                 cursor.pos() - 1, true);
890                         x = x - start_x;
891                         // The origin of an inset is on the baseline
892                         y = y_tmp - (text->cursor.y()); 
893                         return tmpinset;
894                 }
895         }
896         return 0;
897 }
898
899
900 void BufferView::Pimpl::workAreaExpose()
901 {
902         static int work_area_width;
903         static unsigned int work_area_height;
904
905         bool const widthChange = workarea_.workWidth() != work_area_width;
906         bool const heightChange = workarea_.height() != work_area_height;
907
908         // update from work area
909         work_area_width = workarea_.workWidth();
910         work_area_height = workarea_.height();
911         if (buffer_ != 0) {
912                 if (widthChange) {
913                         // The visible LyXView need a resize
914                         owner_->resize();
915
916                         // Remove all texts from the textcache
917                         // This is not _really_ what we want to do. What
918                         // we really want to do is to delete in textcache
919                         // that does not have a BufferView with matching
920                         // width, but as long as we have only one BufferView
921                         // deleting all gives the same result.
922                         if (lyxerr.debugging())
923                                 textcache.show(lyxerr, "Expose delete all");
924                         textcache.clear();
925                 } else if (heightChange) {
926                         // Rebuild image of current screen
927                         updateScreen();
928                         // fitCursor() ensures we don't jump back
929                         // to the start of the document on vertical
930                         // resize
931                         fitCursor(bv_->text);
932
933                         // The main window size has changed, repaint most stuff
934                         redraw();
935                 } else if (screen_.get())
936                     screen_->redraw(bv_->text, bv_);
937         } else {
938                 // Grey box when we don't have a buffer
939                 workarea_.greyOut();
940         }
941
942         // always make sure that the scrollbar is sane.
943         updateScrollbar();
944         owner_->updateLayoutChoice();
945         return;
946 }
947
948
949 void BufferView::Pimpl::update()
950 {
951         if (screen_.get() &&
952                 (!bv_->theLockingInset() || !bv_->theLockingInset()->nodraw()))
953         {
954                 screen_->update(bv_->text, bv_);
955         }
956 }
957
958 // Values used when calling update:
959 // -3 - update
960 // -2 - update, move sel_cursor if selection, fitcursor
961 // -1 - update, move sel_cursor if selection, fitcursor, mark dirty
962 //  0 - update, move sel_cursor if selection, fitcursor 
963 //  1 - update, move sel_cursor if selection, fitcursor, mark dirty
964 //  3 - update, move sel_cursor if selection
965 //
966 // update -
967 // a simple redraw of the parts that need refresh
968 //
969 // move sel_cursor if selection -
970 // the text's sel_cursor is moved if there is selection is progress
971 //
972 // fitcursor -
973 // fitCursor() is called and the scrollbar updated
974 //
975 // mark dirty -
976 // the buffer is marked dirty.
977 //
978 // enum {
979 //       UPDATE = 0,
980 //       SELECT = 1,
981 //       FITCUR = 2,
982 //       CHANGE = 4 
983 // };
984 //
985 // UPDATE_ONLY = UPDATE;
986 // UPDATE_SELECT = UPDATE | SELECT;
987 // UPDATE_SELECT_MOVE = UPDATE | SELECT | FITCUR;
988 // UPDATE_SELECT_MOVE_AFTER_CHANGE = UPDATE | SELECT | FITCUR | CHANGE;
989 //
990 // update(-3) -> update(0)         -> update(0) -> update(UPDATE)
991 // update(-2) -> update(1 + 2)     -> update(3) -> update(SELECT|FITCUR)
992 // update(-1) -> update(1 + 2 + 4) -> update(7) -> update(SELECT|FITCUR|CHANGE)
993 // update(1)  -> update(1 + 2 + 4) -> update(7) -> update(SELECT|FITCUR|CHANGE)
994 // update(3)  -> update(1)         -> update(1) -> update(SELECT)
995
996 void BufferView::Pimpl::update(LyXText * text, BufferView::UpdateCodes f)
997 {
998         owner_->updateLayoutChoice();
999
1000         if (!text->selection.set() && (f & SELECT)) {
1001                 text->selection.cursor = text->cursor;
1002         }
1003
1004         text->fullRebreak(bv_);
1005
1006         if (text->inset_owner) {
1007             text->inset_owner->setUpdateStatus(bv_, InsetText::NONE);
1008             updateInset(text->inset_owner, true);
1009         } else
1010             update();
1011
1012         if ((f & FITCUR)) {
1013                 fitCursor(text);
1014         }
1015
1016         if ((f & CHANGE)) {
1017                 buffer_->markDirty();
1018         }
1019 }
1020
1021
1022 // Callback for cursor timer
1023 void BufferView::Pimpl::cursorToggle()
1024 {
1025         // Quite a nice place for asyncron Inset updating, isn't it?
1026         // Actually no! This is run even if no buffer exist... so (Lgb)
1027         if (!buffer_) {
1028                 cursor_timeout.restart();
1029                 return;
1030         }
1031  
1032         int status = 1;
1033         int const pid = waitpid(static_cast<pid_t>(0), &status, WNOHANG);
1034         if (pid == -1) // error find out what is wrong
1035                 ; // ignore it for now.
1036         else if (pid > 0)
1037                 sigchldhandler(pid, &status);
1038
1039         updatelist.update(bv_);
1040         
1041         if (!screen_.get()) {
1042                 cursor_timeout.restart();
1043                 return;
1044         }
1045
1046         if (!bv_->theLockingInset()) {
1047                 screen_->cursorToggle(bv_->text, bv_);
1048         } else {
1049                 bv_->theLockingInset()->toggleInsetCursor(bv_);
1050         }
1051         
1052         cursor_timeout.restart();
1053 }
1054
1055
1056 void BufferView::Pimpl::cursorPrevious(LyXText * text)
1057 {
1058         if (!text->cursor.row()->previous())
1059                 return;
1060         
1061         int y = text->first;
1062         if (text->inset_owner)
1063                 y += bv_->text->first;
1064         Row * cursorrow = text->cursor.row();
1065         text->setCursorFromCoordinates(bv_, bv_->text->cursor.x_fix(), y);
1066         finishUndo();
1067         // This is to allow jumping over large insets
1068         if ((cursorrow == text->cursor.row()))
1069                 text->cursorUp(bv_);
1070         
1071         if (text->inset_owner ||
1072             text->cursor.row()->height() < workarea_.height())
1073                 screen_->draw(bv_->text, bv_,
1074                               text->cursor.y()
1075                               - text->cursor.row()->baseline()
1076                               + text->cursor.row()->height()
1077                               - workarea_.height() + 1 );
1078         updateScrollbar();
1079 }
1080
1081
1082 void BufferView::Pimpl::cursorNext(LyXText * text)
1083 {
1084         if (!text->cursor.row()->next())
1085                 return;
1086         
1087         int y = text->first + workarea_.height();
1088 //      if (text->inset_owner)
1089 //              y += bv_->text->first;
1090         text->getRowNearY(y);
1091     
1092         Row * cursorrow = text->cursor.row();
1093         text->setCursorFromCoordinates(bv_, text->cursor.x_fix(), y); // + workarea_->height());
1094         finishUndo();
1095         // This is to allow jumping over large insets
1096         if ((cursorrow == bv_->text->cursor.row()))
1097                 text->cursorDown(bv_);
1098         
1099         if (text->inset_owner ||
1100             text->cursor.row()->height() < workarea_.height())
1101                 screen_->draw(bv_->text, bv_, text->cursor.y() -
1102                               text->cursor.row()->baseline());
1103         updateScrollbar();
1104 }
1105
1106
1107 bool BufferView::Pimpl::available() const
1108 {
1109         if (buffer_ && bv_->text) return true;
1110         return false;
1111 }
1112
1113
1114 void BufferView::Pimpl::beforeChange(LyXText * text)
1115 {
1116         toggleSelection();
1117         text->clearSelection(bv_);
1118 }
1119
1120
1121 void BufferView::Pimpl::savePosition(unsigned int i)
1122 {
1123         if (i >= saved_positions_num)
1124                 return;
1125         saved_positions[i] = Position(buffer_->fileName(),
1126                                       bv_->text->cursor.par()->id(),
1127                                       bv_->text->cursor.pos());
1128         if (i > 0) {
1129                 ostringstream str;
1130                 str << _("Saved bookmark") << ' ' << i;
1131                 owner_->message(str.str().c_str());
1132         }
1133 }
1134
1135
1136 void BufferView::Pimpl::restorePosition(unsigned int i)
1137 {
1138         if (i >= saved_positions_num)
1139                 return;
1140
1141         string const fname = saved_positions[i].filename;
1142
1143         beforeChange(bv_->text);
1144
1145         if (fname != buffer_->fileName()) {
1146                 Buffer * b = bufferlist.exists(fname) ?
1147                         bufferlist.getBuffer(fname) :
1148                         bufferlist.loadLyXFile(fname); // don't ask, just load it
1149                 if (b != 0 ) buffer(b);
1150         }
1151
1152         Paragraph * par = buffer_->getParFromID(saved_positions[i].par_id);
1153         if (!par)
1154                 return;
1155
1156         bv_->text->setCursor(bv_, par,
1157                              min(par->size(), saved_positions[i].par_pos));
1158
1159         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
1160         if (i > 0) {
1161                 ostringstream str;
1162                 str << _("Moved to bookmark") << ' ' << i;
1163                 owner_->message(str.str().c_str());
1164         }
1165 }
1166
1167
1168 bool BufferView::Pimpl::isSavedPosition(unsigned int i)
1169 {
1170         if (i >= saved_positions_num)
1171                 return false;
1172
1173         return !saved_positions[i].filename.empty();
1174 }
1175
1176
1177 void BufferView::Pimpl::setState()
1178 {
1179         if (!lyxrc.rtl_support)
1180                 return;
1181
1182         LyXText * text = bv_->getLyXText();
1183         if (text->real_current_font.isRightToLeft()
1184 #ifndef NO_LATEX
1185             &&
1186             text->real_current_font.latex() != LyXFont::ON
1187 #endif
1188                 ) {
1189                 if (owner_->getIntl()->keymap == Intl::PRIMARY)
1190                         owner_->getIntl()->KeyMapSec();
1191         } else {
1192                 if (owner_->getIntl()->keymap == Intl::SECONDARY)
1193                         owner_->getIntl()->KeyMapPrim();
1194         }
1195 }
1196
1197
1198 void BufferView::Pimpl::insetSleep()
1199 {
1200         if (bv_->theLockingInset() && !inset_slept) {
1201                 bv_->theLockingInset()->getCursorPos(bv_, bv_->slx, bv_->sly);
1202                 bv_->theLockingInset()->insetUnlock(bv_);
1203                 inset_slept = true;
1204         }
1205 }
1206
1207
1208 void BufferView::Pimpl::insetWakeup()
1209 {
1210         if (bv_->theLockingInset() && inset_slept) {
1211                 bv_->theLockingInset()->edit(bv_, bv_->slx, bv_->sly, 0);
1212                 inset_slept = false;
1213         }
1214 }
1215
1216
1217 void BufferView::Pimpl::insetUnlock()
1218 {
1219         if (bv_->theLockingInset()) {
1220                 if (!inset_slept)
1221                         bv_->theLockingInset()->insetUnlock(bv_);
1222                 bv_->theLockingInset(0);
1223                 finishUndo();
1224                 inset_slept = false;
1225         }
1226 }
1227
1228
1229 bool BufferView::Pimpl::focus() const
1230 {
1231         return workarea_.hasFocus();
1232 }
1233
1234
1235 void BufferView::Pimpl::focus(bool f)
1236 {
1237         if (f) workarea_.setFocus();
1238 }
1239
1240
1241 bool BufferView::Pimpl::active() const
1242 {
1243         return workarea_.active();
1244 }
1245
1246
1247 bool BufferView::Pimpl::belowMouse() const 
1248 {
1249         return workarea_.belowMouse();
1250 }
1251
1252
1253 void BufferView::Pimpl::showCursor()
1254 {
1255         if (screen_.get())
1256                 screen_->showCursor(bv_->text, bv_);
1257 }
1258
1259
1260 void BufferView::Pimpl::hideCursor()
1261 {
1262         if (screen_.get())
1263                 screen_->hideCursor();
1264 }
1265
1266
1267 void BufferView::Pimpl::toggleSelection(bool b)
1268 {
1269         if (screen_.get())
1270                 screen_->toggleSelection(bv_->text, bv_, b);
1271 }
1272
1273
1274 void BufferView::Pimpl::toggleToggle()
1275 {
1276         if (screen_.get())
1277                 screen_->toggleToggle(bv_->text, bv_);
1278 }
1279
1280
1281 void BufferView::Pimpl::center() 
1282 {
1283         beforeChange(bv_->text);
1284         if (bv_->text->cursor.y() > static_cast<int>((workarea_.height() / 2))) {
1285                 screen_->draw(bv_->text, bv_, bv_->text->cursor.y() - workarea_.height() / 2);
1286         } else {
1287                 screen_->draw(bv_->text, bv_, 0);
1288         }
1289         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
1290         redraw();
1291 }
1292
1293
1294 void BufferView::Pimpl::pasteClipboard(bool asPara) 
1295 {
1296         if (!buffer_) return;
1297
1298         screen_->hideCursor();
1299         beforeChange(bv_->text);
1300         
1301         string const clip(workarea_.getClipboard());
1302         
1303         if (clip.empty()) return;
1304
1305         if (asPara) {
1306                 bv_->text->insertStringAsParagraphs(bv_, clip);
1307         } else {
1308                 bv_->text->insertStringAsLines(bv_, clip);
1309         }
1310         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
1311 }
1312
1313
1314 void BufferView::Pimpl::stuffClipboard(string const & stuff) const
1315 {
1316         workarea_.putClipboard(stuff);
1317 }
1318
1319
1320 /*
1321  * Dispatch functions for actions which can be valid for BufferView->text
1322  * and/or InsetText->text!!!
1323  */
1324
1325
1326 inline
1327 void BufferView::Pimpl::moveCursorUpdate(bool selecting)
1328 {
1329         LyXText * lt = bv_->getLyXText();
1330         
1331         if (selecting || lt->selection.mark()) {
1332                 lt->setSelection(bv_);
1333                 if (lt->bv_owner)
1334                         toggleToggle();
1335         }
1336         update(lt, BufferView::SELECT|BufferView::FITCUR);
1337         showCursor();
1338         
1339         /* ---> Everytime the cursor is moved, show the current font state. */
1340         // should this too me moved out of this func?
1341         //owner->showState();
1342         setState();
1343 }
1344
1345
1346 Inset * BufferView::Pimpl::getInsetByCode(Inset::Code code)
1347 {
1348         LyXCursor cursor = bv_->getLyXText()->cursor;
1349         Buffer::inset_iterator it =
1350                 find_if(Buffer::inset_iterator(
1351                         cursor.par(), cursor.pos()),
1352                         buffer_->inset_iterator_end(),
1353                         lyx::compare_memfun(&Inset::lyxCode, code));
1354         return it != buffer_->inset_iterator_end() ? (*it) : 0;
1355 }
1356
1357
1358 void BufferView::Pimpl::MenuInsertLyXFile(string const & filen)
1359 {
1360         string filename = filen;
1361
1362         if (filename.empty()) {
1363                 // Launch a file browser
1364                 string initpath = lyxrc.document_path;
1365
1366                 if (available()) {
1367                         string const trypath = owner_->buffer()->filepath;
1368                         // If directory is writeable, use this as default.
1369                         if (IsDirWriteable(trypath) == 1)
1370                                 initpath = trypath;
1371                 }
1372
1373                 FileDialog fileDlg(bv_->owner(),
1374                                    _("Select LyX document to insert"),
1375                         LFUN_FILE_INSERT,
1376                         make_pair(string(_("Documents")),
1377                                   string(lyxrc.document_path)),
1378                         make_pair(string(_("Examples")),
1379                                   string(AddPath(system_lyxdir, "examples"))));
1380
1381                 FileDialog::Result result =
1382                         fileDlg.Select(initpath,
1383                                        _("*.lyx| LyX Documents (*.lyx)"));
1384  
1385                 if (result.first == FileDialog::Later)
1386                         return;
1387
1388                 filename = result.second;
1389
1390                 // check selected filename
1391                 if (filename.empty()) {
1392                         owner_->message(_("Canceled."));
1393                         return;
1394                 }
1395         }
1396
1397         // get absolute path of file and add ".lyx" to the filename if
1398         // necessary
1399         filename = FileSearch(string(), filename, "lyx");
1400
1401         string const disp_fn(MakeDisplayPath(filename));
1402         
1403         ostringstream s1;
1404         s1 << _("Inserting document") << ' '
1405            << disp_fn << " ...";
1406         owner_->message(s1.str().c_str());
1407         bool const res = bv_->insertLyXFile(filename);
1408         if (res) {
1409                 ostringstream str;
1410                 str << _("Document") << ' ' << disp_fn
1411                     << ' ' << _("inserted.");
1412                 owner_->message(str.str().c_str());
1413         } else {
1414                 ostringstream str;
1415                 str << _("Could not insert document") << ' '
1416                     << disp_fn;
1417                 owner_->message(str.str().c_str());
1418         }
1419 }
1420
1421
1422 bool BufferView::Pimpl::Dispatch(kb_action action, string const & argument)
1423 {
1424         lyxerr[Debug::ACTION] << "BufferView::Pimpl::Dispatch: action["
1425                               << action <<"] arg[" << argument << "]" << endl;
1426         
1427         switch (action) {
1428                 // --- Misc -------------------------------------------
1429         case LFUN_APPENDIX:
1430         {
1431                 if (available()) {
1432                         LyXText * lt = bv_->getLyXText();
1433                         lt->toggleAppendix(bv_);
1434                         update(lt,
1435                                BufferView::SELECT
1436                                | BufferView::FITCUR
1437                                | BufferView::CHANGE);
1438                 }
1439         }
1440         break;
1441
1442         case LFUN_TOC_INSERT:
1443         {
1444                 InsetCommandParams p;
1445                 p.setCmdName("tableofcontents");
1446                 Inset * inset = new InsetTOC(p);
1447                 if (!insertInset(inset, "Standard"))
1448                         delete inset;
1449                 break;
1450         }
1451                 
1452         case LFUN_TABULAR_FEATURE:
1453         case LFUN_SCROLL_INSET:
1454                 // this is not handled here as this funktion is only aktive
1455                 // if we have a locking_inset and that one is (or contains)
1456                 // a tabular-inset
1457                 break;
1458
1459         case LFUN_INSET_GRAPHICS:
1460         {
1461                 Inset * new_inset = new InsetGraphics;
1462                 if (!insertInset(new_inset)) {
1463                         delete new_inset;
1464                 } else {
1465                         // this is need because you don't use a inset->Edit()
1466                         updateInset(new_inset, true);
1467                         new_inset->edit(bv_, 0, 0, 0);
1468                 }
1469                 break;
1470         }
1471                 
1472         case LFUN_PASTE:
1473                 bv_->paste();
1474                 setState();
1475                 break;
1476                 
1477         case LFUN_PASTESELECTION:
1478         {
1479                 bool asPara = false;
1480                 if (argument == "paragraph") asPara = true;
1481                 pasteClipboard(asPara);
1482         }
1483         break;
1484         
1485         case LFUN_CUT:
1486                 bv_->cut();
1487                 break;
1488                 
1489         case LFUN_COPY:
1490                 bv_->copy();
1491                 break;
1492                 
1493         case LFUN_LAYOUT_COPY:
1494                 bv_->copyEnvironment();
1495                 break;
1496                 
1497         case LFUN_LAYOUT_PASTE:
1498                 bv_->pasteEnvironment();
1499                 setState();
1500                 break;
1501                 
1502         case LFUN_GOTOERROR:
1503                 gotoInset(Inset::ERROR_CODE, false);
1504                 break;
1505                 
1506         case LFUN_GOTONOTE:
1507                 gotoInset(Inset::IGNORE_CODE, false);
1508                 break;
1509
1510         case LFUN_REFERENCE_GOTO:
1511         {
1512                 vector<Inset::Code> tmp;
1513                 tmp.push_back(Inset::LABEL_CODE);
1514                 tmp.push_back(Inset::REF_CODE);
1515                 gotoInset(tmp, true);
1516                 break;
1517         }
1518
1519         case LFUN_HYPHENATION:
1520                 hyphenationPoint();
1521                 break;
1522                 
1523         case LFUN_LDOTS:
1524                 ldots();
1525                 break;
1526                 
1527         case LFUN_END_OF_SENTENCE:
1528                 endOfSentenceDot();
1529                 break;
1530
1531         case LFUN_MENU_SEPARATOR:
1532                 menuSeparator();
1533                 break;
1534                 
1535         case LFUN_HFILL:
1536                 hfill();
1537                 break;
1538                 
1539         case LFUN_DEPTH:
1540                 changeDepth(bv_, bv_->getLyXText(), 0);
1541                 break;
1542                 
1543         case LFUN_DEPTH_MIN:
1544                 changeDepth(bv_, bv_->getLyXText(), -1);
1545                 break;
1546                 
1547         case LFUN_DEPTH_PLUS:
1548                 changeDepth(bv_, bv_->getLyXText(), 1);
1549                 break;
1550                 
1551         case LFUN_FREE:
1552                 owner_->getDialogs()->setUserFreeFont();
1553                 break;
1554
1555 #ifndef NO_LATEX
1556         case LFUN_TEX:
1557                 Tex(bv_);
1558                 setState();
1559                 owner_->showState();
1560                 break;
1561 #endif
1562                 
1563         case LFUN_FILE_INSERT:
1564         {
1565                 MenuInsertLyXFile(argument);
1566         }
1567         break;
1568         
1569         case LFUN_FILE_INSERT_ASCII_PARA:
1570                 InsertAsciiFile(bv_, argument, true);
1571                 break;
1572
1573         case LFUN_FILE_INSERT_ASCII:
1574                 InsertAsciiFile(bv_, argument, false);
1575                 break;
1576                 
1577         case LFUN_LAYOUT:
1578         {
1579                 lyxerr[Debug::INFO] << "LFUN_LAYOUT: (arg) "
1580                                     << argument << endl;
1581                 
1582                 // Derive layout number from given argument (string)
1583                 // and current buffer's textclass (number). */    
1584                 LyXTextClassList::ClassList::size_type tclass =
1585                         buffer_->params.textclass;
1586                 pair <bool, LyXTextClass::size_type> layout = 
1587                         textclasslist.NumberOfLayout(tclass, argument);
1588
1589                 // If the entry is obsolete, use the new one instead.
1590                 if (layout.first) {
1591                         string obs = textclasslist.Style(tclass,layout.second)
1592                                 .obsoleted_by();
1593                         if (!obs.empty()) 
1594                                 layout = 
1595                                         textclasslist.NumberOfLayout(tclass, obs);
1596                 }
1597
1598                 // see if we found the layout number:
1599                 if (!layout.first) {
1600                         owner_->getLyXFunc()->setErrorMessage(
1601                                 string(N_("Layout ")) + argument +
1602                                 N_(" not known"));
1603                         break;
1604                 }
1605
1606                 if (current_layout != layout.second) {
1607                         LyXText * lt = bv_->getLyXText();
1608                         hideCursor();
1609                         current_layout = layout.second;
1610                         update(lt,
1611                                BufferView::SELECT
1612                                | BufferView::FITCUR);
1613                         lt->setLayout(bv_, layout.second);
1614                         owner_->setLayout(layout.second);
1615                         update(lt,
1616                                BufferView::SELECT
1617                                | BufferView::FITCUR
1618                                | BufferView::CHANGE);
1619                         setState();
1620                 }
1621         }
1622         break;
1623
1624         case LFUN_LANGUAGE:
1625                 Lang(bv_, argument);
1626                 setState();
1627                 owner_->showState();
1628                 break;
1629
1630         case LFUN_EMPH:
1631                 Emph(bv_);
1632                 owner_->showState();
1633                 break;
1634
1635         case LFUN_BOLD:
1636                 Bold(bv_);
1637                 owner_->showState();
1638                 break;
1639                 
1640         case LFUN_NOUN:
1641                 Noun(bv_);
1642                 owner_->showState();
1643                 break;
1644                 
1645         case LFUN_CODE:
1646                 Code(bv_);
1647                 owner_->showState();
1648                 break;
1649                 
1650         case LFUN_SANS:
1651                 Sans(bv_);
1652                 owner_->showState();
1653                 break;
1654                 
1655         case LFUN_ROMAN:
1656                 Roman(bv_);
1657                 owner_->showState();
1658                 break;
1659                 
1660         case LFUN_DEFAULT:
1661                 StyleReset(bv_);
1662                 owner_->showState();
1663                 break;
1664                 
1665         case LFUN_UNDERLINE:
1666                 Underline(bv_);
1667                 owner_->showState();
1668                 break;
1669                 
1670         case LFUN_FONT_SIZE:
1671                 FontSize(bv_, argument);
1672                 owner_->showState();
1673                 break;
1674                 
1675         case LFUN_FONT_STATE:
1676                 owner_->getLyXFunc()->setMessage(CurrentState(bv_));
1677                 break;
1678                 
1679         case LFUN_UPCASE_WORD:
1680         {
1681                 LyXText * lt = bv_->getLyXText();
1682                 
1683                 update(lt,
1684                        BufferView::SELECT
1685                        | BufferView::FITCUR);
1686                 lt->changeCase(bv_, LyXText::text_uppercase);
1687                 if (lt->inset_owner)
1688                         updateInset(lt->inset_owner, true);
1689                 update(lt,
1690                        BufferView::SELECT
1691                        | BufferView::FITCUR
1692                        | BufferView::CHANGE);
1693         }
1694         break;
1695                 
1696         case LFUN_LOWCASE_WORD:
1697         {
1698                 LyXText * lt = bv_->getLyXText();
1699                 
1700                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1701                 lt->changeCase(bv_, LyXText::text_lowercase);
1702                 if (lt->inset_owner)
1703                         updateInset(lt->inset_owner, true);
1704                 update(lt,
1705                        BufferView::SELECT
1706                        | BufferView::FITCUR
1707                        | BufferView::CHANGE);
1708         }
1709         break;
1710                 
1711         case LFUN_CAPITALIZE_WORD:
1712         {
1713                 LyXText * lt = bv_->getLyXText();
1714                 
1715                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1716                 lt->changeCase(bv_, LyXText::text_capitalization);
1717                 if (lt->inset_owner)
1718                         updateInset(lt->inset_owner, true);
1719                 update(lt,
1720                        BufferView::SELECT
1721                        | BufferView::FITCUR
1722                        | BufferView::CHANGE);
1723         }
1724         break;
1725
1726         case LFUN_TRANSPOSE_CHARS:
1727         {
1728                 LyXText * lt = bv_->getLyXText();
1729                 
1730                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1731                 lt->transposeChars(*bv_);
1732                 if (lt->inset_owner)
1733                         updateInset(lt->inset_owner, true);
1734                 update(lt,
1735                        BufferView::SELECT
1736                        | BufferView::FITCUR
1737                        | BufferView::CHANGE);
1738         }
1739         break;
1740                 
1741                                           
1742         case LFUN_INSERT_LABEL:
1743                 MenuInsertLabel(bv_, argument);
1744                 break;
1745                 
1746         case LFUN_REF_INSERT:
1747                 if (argument.empty()) {
1748                         InsetCommandParams p("ref");
1749                         owner_->getDialogs()->createRef(p.getAsString());
1750                 } else {
1751                         InsetCommandParams p;
1752                         p.setFromString(argument);
1753
1754                         InsetRef * inset = new InsetRef(p, *buffer_);
1755                         if (!insertInset(inset))
1756                                 delete inset;
1757                         else
1758                                 updateInset(inset, true);
1759                 }
1760                 break;
1761
1762         case LFUN_BOOKMARK_SAVE:
1763                 savePosition(strToUnsignedInt(argument));
1764                 break;
1765
1766         case LFUN_BOOKMARK_GOTO:
1767                 restorePosition(strToUnsignedInt(argument));
1768                 break;
1769
1770         case LFUN_REF_GOTO:
1771         {
1772                 string label(argument);
1773                 if (label.empty()) {
1774                         InsetRef * inset = 
1775                                 static_cast<InsetRef*>(getInsetByCode(Inset::REF_CODE));
1776                         if (inset) {
1777                                 label = inset->getContents();
1778                                 savePosition(0);
1779                         }
1780                 }
1781                 
1782                 if (!label.empty()) {
1783                         //bv_->savePosition(0);
1784                         if (!bv_->gotoLabel(label))
1785                                 WriteAlert(_("Error"), 
1786                                            _("Couldn't find this label"), 
1787                                            _("in current document."));
1788                 }
1789         }
1790         break;
1791                 
1792                 // --- Cursor Movements -----------------------------
1793         case LFUN_RIGHT:
1794         {
1795                 LyXText * lt = bv_->getLyXText();
1796                 
1797                 bool is_rtl = lt->cursor.par()->isRightToLeftPar(buffer_->params);
1798                 if (!lt->selection.mark())
1799                         beforeChange(lt);
1800                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1801                 if (is_rtl)
1802                         lt->cursorLeft(bv_, false);
1803                 if (lt->cursor.pos() < lt->cursor.par()->size()
1804                     && lt->cursor.par()->getChar(lt->cursor.pos())
1805                     == Paragraph::META_INSET
1806                     && lt->cursor.par()->getInset(lt->cursor.pos())
1807                     && lt->cursor.par()->getInset(lt->cursor.pos())->editable() == Inset::HIGHLY_EDITABLE){
1808                         Inset * tmpinset = lt->cursor.par()->getInset(lt->cursor.pos());
1809                         owner_->getLyXFunc()->setMessage(tmpinset->editMessage());
1810                         int y = 0;
1811                         if (is_rtl) {
1812                                 LyXFont const font = 
1813                                         lt->getFont(buffer_,
1814                                                     lt->cursor.par(),
1815                                                     lt->cursor.pos());  
1816                                 y = tmpinset->descent(bv_,font);
1817                         }
1818                         tmpinset->edit(bv_, 0, y, 0);
1819                         break;
1820                 }
1821                 if (!is_rtl)
1822                         lt->cursorRight(bv_, false);
1823                 finishUndo();
1824                 moveCursorUpdate(false);
1825                 owner_->showState();
1826         }
1827         break;
1828                 
1829         case LFUN_LEFT:
1830         {
1831                 // This is soooo ugly. Isn`t it possible to make
1832                 // it simpler? (Lgb)
1833                 LyXText * lt = bv_->getLyXText();
1834                 bool is_rtl = lt->cursor.par()->isRightToLeftPar(buffer_->params);
1835                 if (!lt->selection.mark())
1836                         beforeChange(lt);
1837                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1838                 LyXCursor const cur = lt->cursor;
1839                 if (!is_rtl)
1840                         lt->cursorLeft(bv_, false);
1841                 if ((is_rtl || cur != lt->cursor) && // only if really moved!
1842                     lt->cursor.pos() < lt->cursor.par()->size() &&
1843                     (lt->cursor.par()->getChar(lt->cursor.pos()) ==
1844                      Paragraph::META_INSET) &&
1845                     lt->cursor.par()->getInset(lt->cursor.pos()) &&
1846                     (lt->cursor.par()->getInset(lt->cursor.pos())->editable()
1847                      == Inset::HIGHLY_EDITABLE))
1848                 {
1849                         Inset * tmpinset = lt->cursor.par()->getInset(lt->cursor.pos());
1850                         owner_->getLyXFunc()->setMessage(tmpinset->editMessage());
1851                         LyXFont const font = lt->getFont(buffer_,
1852                                                          lt->cursor.par(),
1853                                                          lt->cursor.pos());
1854                         int y = is_rtl ? 0 
1855                                 : tmpinset->descent(bv_,font);
1856                         tmpinset->edit(bv_,
1857                                        tmpinset->x() +
1858                                        tmpinset->width(bv_,font),
1859                                        y, 0);
1860                         break;
1861                 }
1862                 if  (is_rtl)
1863                         lt->cursorRight(bv_, false);
1864
1865                 finishUndo();
1866                 moveCursorUpdate(false);
1867                 owner_->showState();
1868         }
1869         break;
1870                 
1871         case LFUN_UP:
1872         {
1873                 LyXText * lt = bv_->getLyXText();
1874                 
1875                 if (!lt->selection.mark())
1876                         beforeChange(lt);
1877                 update(lt, BufferView::UPDATE);
1878                 lt->cursorUp(bv_);
1879                 finishUndo();
1880                 moveCursorUpdate(false);
1881                 owner_->showState();
1882         }
1883         break;
1884                 
1885         case LFUN_DOWN:
1886         {
1887                 LyXText * lt = bv_->getLyXText();
1888                 
1889                 if (!lt->selection.mark())
1890                         beforeChange(lt);
1891                 update(lt, BufferView::UPDATE);
1892                 lt->cursorDown(bv_);
1893                 finishUndo();
1894                 moveCursorUpdate(false);
1895                 owner_->showState();
1896         }
1897         break;
1898
1899         case LFUN_UP_PARAGRAPH:
1900         {
1901                 LyXText * lt = bv_->getLyXText();
1902                 
1903                 if (!lt->selection.mark())
1904                         beforeChange(lt);
1905                 update(lt, BufferView::UPDATE);
1906                 lt->cursorUpParagraph(bv_);
1907                 finishUndo();
1908                 moveCursorUpdate(false);
1909                 owner_->showState();
1910         }
1911         break;
1912                 
1913         case LFUN_DOWN_PARAGRAPH:
1914         {
1915                 LyXText * lt = bv_->getLyXText();
1916                 
1917                 if (!lt->selection.mark())
1918                         beforeChange(lt);
1919                 update(lt, BufferView::UPDATE);
1920                 lt->cursorDownParagraph(bv_);
1921                 finishUndo();
1922                 moveCursorUpdate(false);
1923                 owner_->showState();
1924         }
1925         break;
1926                 
1927         case LFUN_PRIOR:
1928         {
1929                 LyXText * lt = bv_->getLyXText();
1930                 
1931                 if (!lt->selection.mark())
1932                         beforeChange(lt);
1933                 update(lt, BufferView::UPDATE);
1934                 cursorPrevious(lt);
1935                 finishUndo();
1936                 moveCursorUpdate(false);
1937                 owner_->showState();
1938         }
1939         break;
1940                 
1941         case LFUN_NEXT:
1942         {
1943                 LyXText * lt = bv_->getLyXText();
1944                 
1945                 if (!lt->selection.mark())
1946                         beforeChange(lt);
1947                 update(lt, BufferView::UPDATE);
1948                 cursorNext(lt);
1949                 finishUndo();
1950                 moveCursorUpdate(false);
1951                 owner_->showState();
1952         }
1953         break;
1954                 
1955         case LFUN_HOME:
1956         {
1957                 LyXText * lt = bv_->getLyXText();
1958                 
1959                 if (!lt->selection.mark())
1960                         beforeChange(lt);
1961                 update(lt, BufferView::SELECT|BufferView::FITCUR);
1962                 lt->cursorHome(bv_);
1963                 finishUndo();
1964                 moveCursorUpdate(false);
1965                 owner_->showState();
1966         }
1967         break;
1968                 
1969         case LFUN_END:
1970         {
1971                 LyXText * lt = bv_->getLyXText();
1972                 
1973                 if (!lt->selection.mark())
1974                         beforeChange(lt);
1975                 update(lt,
1976                        BufferView::SELECT|BufferView::FITCUR);
1977                 lt->cursorEnd(bv_);
1978                 finishUndo();
1979                 moveCursorUpdate(false);
1980                 owner_->showState();
1981         }
1982         break;
1983                 
1984         case LFUN_SHIFT_TAB:
1985         case LFUN_TAB:
1986         {
1987                 LyXText * lt = bv_->getLyXText();
1988                 
1989                 if (!lt->selection.mark())
1990                         beforeChange(lt);
1991                 update(lt,
1992                        BufferView::SELECT|BufferView::FITCUR);
1993                 lt->cursorTab(bv_);
1994                 finishUndo();
1995                 moveCursorUpdate(false);
1996                 owner_->showState();
1997         }
1998         break;
1999                 
2000         case LFUN_WORDRIGHT:
2001         {
2002                 LyXText * lt = bv_->getLyXText();
2003                 
2004                 if (!lt->selection.mark())
2005                         beforeChange(lt);
2006                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2007                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2008                         lt->cursorLeftOneWord(bv_);
2009                 else
2010                         lt->cursorRightOneWord(bv_);
2011                 finishUndo();
2012                 moveCursorUpdate(false);
2013                 owner_->showState();
2014         }
2015         break;
2016                 
2017         case LFUN_WORDLEFT:
2018         {
2019                 LyXText * lt = bv_->getLyXText();
2020                 
2021                 if (!lt->selection.mark())
2022                         beforeChange(lt);
2023                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2024                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2025                         lt->cursorRightOneWord(bv_);
2026                 else
2027                         lt->cursorLeftOneWord(bv_);
2028                 finishUndo();
2029                 moveCursorUpdate(false);
2030                 owner_->showState();
2031         }
2032         break;
2033                 
2034         case LFUN_BEGINNINGBUF:
2035         {
2036                 LyXText * lt = bv_->getLyXText();
2037                 
2038                 if (!lt->selection.mark())
2039                         beforeChange(lt);
2040                 update(lt,
2041                        BufferView::SELECT|BufferView::FITCUR);
2042                 lt->cursorTop(bv_);
2043                 finishUndo();
2044                 moveCursorUpdate(false);
2045                 owner_->showState();
2046         }
2047         break;
2048                 
2049         case LFUN_ENDBUF:
2050         {
2051                 LyXText * lt = bv_->getLyXText();
2052                 
2053                 if (!lt->selection.mark())
2054                         beforeChange(lt);
2055                 update(lt,
2056                        BufferView::SELECT|BufferView::FITCUR);
2057                 lt->cursorBottom(bv_);
2058                 finishUndo();
2059                 moveCursorUpdate(false);
2060                 owner_->showState();
2061         }
2062         break;
2063       
2064                 /* cursor selection ---------------------------- */
2065         case LFUN_RIGHTSEL:
2066         {
2067                 LyXText * lt = bv_->getLyXText();
2068                 
2069                 update(lt,
2070                        BufferView::SELECT|BufferView::FITCUR);
2071                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2072                         lt->cursorLeft(bv_);
2073                 else
2074                         lt->cursorRight(bv_);
2075                 finishUndo();
2076                 moveCursorUpdate(true);
2077                 owner_->showState();
2078         }
2079         break;
2080                 
2081         case LFUN_LEFTSEL:
2082         {
2083                 LyXText * lt = bv_->getLyXText();
2084                 
2085                 update(lt,
2086                        BufferView::SELECT|BufferView::FITCUR);
2087                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2088                         lt->cursorRight(bv_);
2089                 else
2090                         lt->cursorLeft(bv_);
2091                 finishUndo();
2092                 moveCursorUpdate(true);
2093                 owner_->showState();
2094         }
2095         break;
2096                 
2097         case LFUN_UPSEL:
2098         {
2099                 LyXText * lt = bv_->getLyXText();
2100                 
2101                 update(lt,
2102                        BufferView::SELECT|BufferView::FITCUR);
2103                 lt->cursorUp(bv_);
2104                 finishUndo();
2105                 moveCursorUpdate(true);
2106                 owner_->showState();
2107         }
2108         break;
2109                 
2110         case LFUN_DOWNSEL:
2111         {
2112                 LyXText * lt = bv_->getLyXText();
2113                 
2114                 update(lt,
2115                        BufferView::SELECT|BufferView::FITCUR);
2116                 lt->cursorDown(bv_);
2117                 finishUndo();
2118                 moveCursorUpdate(true);
2119                 owner_->showState();
2120         }
2121         break;
2122
2123         case LFUN_UP_PARAGRAPHSEL:
2124         {
2125                 LyXText * lt = bv_->getLyXText();
2126                 
2127                 update(lt,
2128                        BufferView::SELECT|BufferView::FITCUR);
2129                 lt->cursorUpParagraph(bv_);
2130                 finishUndo();
2131                 moveCursorUpdate(true);
2132                 owner_->showState();
2133         }
2134         break;
2135                 
2136         case LFUN_DOWN_PARAGRAPHSEL:
2137         {
2138                 LyXText * lt = bv_->getLyXText();
2139                 
2140                 update(lt,
2141                        BufferView::SELECT|BufferView::FITCUR);
2142                 lt->cursorDownParagraph(bv_);
2143                 finishUndo();
2144                 moveCursorUpdate(true);
2145                 owner_->showState();
2146         }
2147         break;
2148                 
2149         case LFUN_PRIORSEL:
2150         {
2151                 LyXText * lt = bv_->getLyXText();
2152                 
2153                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2154                 cursorPrevious(lt);
2155                 finishUndo();
2156                 moveCursorUpdate(true);
2157                 owner_->showState();
2158         }
2159         break;
2160                 
2161         case LFUN_NEXTSEL:
2162         {
2163                 LyXText * lt = bv_->getLyXText();
2164                 
2165                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2166                 cursorNext(lt);
2167                 finishUndo();
2168                 moveCursorUpdate(true);
2169                 owner_->showState();
2170         }
2171         break;
2172                 
2173         case LFUN_HOMESEL:
2174         {
2175                 LyXText * lt = bv_->getLyXText();
2176                 
2177                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2178                 lt->cursorHome(bv_);
2179                 finishUndo();
2180                 moveCursorUpdate(true);
2181                 owner_->showState();
2182         }
2183         break;
2184                 
2185         case LFUN_ENDSEL:
2186         {
2187                 LyXText * lt = bv_->getLyXText();
2188                 
2189                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2190                 lt->cursorEnd(bv_);
2191                 finishUndo();
2192                 moveCursorUpdate(true);
2193                 owner_->showState();
2194         }
2195         break;
2196                 
2197         case LFUN_WORDRIGHTSEL:
2198         {
2199                 LyXText * lt = bv_->getLyXText();
2200                 
2201                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2202                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2203                         lt->cursorLeftOneWord(bv_);
2204                 else
2205                         lt->cursorRightOneWord(bv_);
2206                 finishUndo();
2207                 moveCursorUpdate(true);
2208                 owner_->showState();
2209         }
2210         break;
2211                 
2212         case LFUN_WORDLEFTSEL:
2213         {
2214                 LyXText * lt = bv_->getLyXText();
2215                 
2216                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2217                 if (lt->cursor.par()->isRightToLeftPar(buffer_->params))
2218                         lt->cursorRightOneWord(bv_);
2219                 else
2220                         lt->cursorLeftOneWord(bv_);
2221                 finishUndo();
2222                 moveCursorUpdate(true);
2223                 owner_->showState();
2224         }
2225         break;
2226                 
2227         case LFUN_BEGINNINGBUFSEL:
2228         {
2229                 LyXText * lt = bv_->getLyXText();
2230                 
2231                 if (lt->inset_owner)
2232                         break;
2233                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2234                 lt->cursorTop(bv_);
2235                 finishUndo();
2236                 moveCursorUpdate(true);
2237                 owner_->showState();
2238         }
2239         break;
2240                 
2241         case LFUN_ENDBUFSEL:
2242         {
2243                 LyXText * lt = bv_->getLyXText();
2244                 
2245                 if (lt->inset_owner)
2246                         break;
2247                 update(lt,
2248                        BufferView::SELECT|BufferView::FITCUR);
2249                 lt->cursorBottom(bv_);
2250                 finishUndo();
2251                 moveCursorUpdate(true);
2252                 owner_->showState();
2253         }
2254         break;
2255
2256                 // --- text changing commands ------------------------
2257         case LFUN_BREAKLINE:
2258         {
2259                 LyXText * lt = bv_->getLyXText();
2260
2261                 beforeChange(lt);
2262                 lt->insertChar(bv_, Paragraph::META_NEWLINE);
2263                 update(lt,
2264                        BufferView::SELECT
2265                        | BufferView::FITCUR
2266                        | BufferView::CHANGE);
2267                 moveCursorUpdate(false);
2268         }
2269         break;
2270                 
2271         case LFUN_PROTECTEDSPACE:
2272         {
2273                 LyXText * lt = bv_->getLyXText();
2274
2275                 LyXLayout const & style = textclasslist
2276                         .Style(buffer_->params.textclass,
2277                                lt->cursor.par()->getLayout());
2278
2279                 if (style.free_spacing) {
2280                         lt->insertChar(bv_, ' ');
2281                         update(lt,
2282                                BufferView::SELECT
2283                                | BufferView::FITCUR
2284                                | BufferView::CHANGE);
2285                 } else {
2286                         protectedBlank(lt);
2287                 }
2288                 moveCursorUpdate(false);
2289         }
2290         break;
2291                 
2292         case LFUN_SETMARK:
2293         {
2294                 LyXText * lt = bv_->getLyXText();
2295
2296                 if (lt->selection.mark()) {
2297                         beforeChange(lt);
2298                         update(lt,
2299                                BufferView::SELECT
2300                                | BufferView::FITCUR);
2301                         owner_->getLyXFunc()->setMessage(N_("Mark removed"));
2302                 } else {
2303                         beforeChange(lt);
2304                         lt->selection.mark(true);
2305                         update(lt,
2306                                BufferView::SELECT
2307                                | BufferView::FITCUR);
2308                         owner_->getLyXFunc()->setMessage(N_("Mark set"));
2309                 }
2310                 lt->selection.cursor = lt->cursor;
2311         }
2312         break;
2313                 
2314         case LFUN_DELETE:
2315         {
2316                 LyXText * lt = bv_->getLyXText();
2317
2318                 if (!lt->selection.set()) {
2319                         lt->Delete(bv_);
2320                         lt->selection.cursor = lt->cursor;
2321                         update(lt,
2322                                BufferView::SELECT
2323                                | BufferView::FITCUR
2324                                | BufferView::CHANGE);
2325                         // It is possible to make it a lot faster still
2326                         // just comment out the line below...
2327                         showCursor();
2328                 } else {
2329                         bv_->cut();
2330                 }
2331                 moveCursorUpdate(false);
2332                 owner_->showState();
2333                 setState();
2334         }
2335         break;
2336
2337         case LFUN_DELETE_SKIP:
2338         {
2339                 LyXText * lt = bv_->getLyXText();
2340
2341                 // Reverse the effect of LFUN_BREAKPARAGRAPH_SKIP.
2342                 
2343                 LyXCursor cursor = lt->cursor;
2344
2345                 if (!lt->selection.set()) {
2346                         if (cursor.pos() == cursor.par()->size()) {
2347                                 lt->cursorRight(bv_);
2348                                 cursor = lt->cursor;
2349                                 if (cursor.pos() == 0
2350                                     && !(cursor.par()->params().spaceTop()
2351                                          == VSpace (VSpace::NONE))) {
2352                                         lt->setParagraph
2353                                                 (bv_,
2354                                                  cursor.par()->params().lineTop(),
2355                                                  cursor.par()->params().lineBottom(),
2356                                                  cursor.par()->params().pagebreakTop(), 
2357                                                  cursor.par()->params().pagebreakBottom(),
2358                                                  VSpace(VSpace::NONE), 
2359                                                  cursor.par()->params().spaceBottom(),
2360                                                  cursor.par()->params().align(), 
2361                                                  cursor.par()->params().labelWidthString(), 0);
2362                                         lt->cursorLeft(bv_);
2363                                         update(lt, 
2364                                                BufferView::SELECT
2365                                                | BufferView::FITCUR
2366                                                | BufferView::CHANGE);
2367                                 } else {
2368                                         lt->cursorLeft(bv_);
2369                                         lt->Delete(bv_);
2370                                         lt->selection.cursor = lt->cursor;
2371                                         update(lt,
2372                                                BufferView::SELECT
2373                                                | BufferView::FITCUR
2374                                                | BufferView::CHANGE);
2375                                 }
2376                         } else {
2377                                 lt->Delete(bv_);
2378                                 lt->selection.cursor = lt->cursor;
2379                                 update(lt,
2380                                        BufferView::SELECT
2381                                        | BufferView::FITCUR
2382                                        | BufferView::CHANGE);
2383                         }
2384                 } else {
2385                         bv_->cut();
2386                 }
2387         }
2388         break;
2389
2390         /* -------> Delete word forward. */
2391         case LFUN_DELETE_WORD_FORWARD:
2392                 update(bv_->getLyXText(), BufferView::SELECT|BufferView::FITCUR);
2393                 bv_->getLyXText()->deleteWordForward(bv_);
2394                 update(bv_->getLyXText(), BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2395                 moveCursorUpdate(false);
2396                 owner_->showState();
2397                 break;
2398
2399                 /* -------> Delete word backward. */
2400         case LFUN_DELETE_WORD_BACKWARD:
2401         {
2402                 LyXText * lt = bv_->getLyXText();
2403                 
2404                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2405                 lt->deleteWordBackward(bv_);
2406                 update(lt,
2407                        BufferView::SELECT
2408                        | BufferView::FITCUR
2409                        | BufferView::CHANGE);
2410                 moveCursorUpdate(false);
2411                 owner_->showState();
2412         }
2413         break;
2414                 
2415                 /* -------> Kill to end of line. */
2416         case LFUN_DELETE_LINE_FORWARD:
2417         {
2418                 LyXText * lt = bv_->getLyXText();
2419                 
2420                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2421                 lt->deleteLineForward(bv_);
2422                 update(lt,
2423                        BufferView::SELECT
2424                        | BufferView::FITCUR
2425                        | BufferView::CHANGE);
2426                 moveCursorUpdate(false);
2427         }
2428         break;
2429                 
2430                 /* -------> Set mark off. */
2431         case LFUN_MARK_OFF:
2432         {
2433                 LyXText * lt = bv_->getLyXText();
2434                 
2435                 beforeChange(lt);
2436                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2437                 lt->selection.cursor = lt->cursor;
2438                 owner_->getLyXFunc()->setMessage(N_("Mark off"));
2439         }
2440         break;
2441
2442                 /* -------> Set mark on. */
2443         case LFUN_MARK_ON:
2444         {
2445                 LyXText * lt = bv_->getLyXText();
2446                 
2447                 beforeChange(lt);
2448                 lt->selection.mark(true);
2449                 update(lt, BufferView::SELECT|BufferView::FITCUR);
2450                 lt->selection.cursor = lt->cursor;
2451                 owner_->getLyXFunc()->setMessage(N_("Mark on"));
2452         }
2453         break;
2454                 
2455         case LFUN_BACKSPACE:
2456         {
2457                 LyXText * lt = bv_->getLyXText();
2458                 
2459                 if (!lt->selection.set()) {
2460                         if (owner_->getIntl()->getTrans().backspace()) {
2461                                 lt->backspace(bv_);
2462                                 lt->selection.cursor = lt->cursor;
2463                                 update(lt,
2464                                        BufferView::SELECT
2465                                        | BufferView::FITCUR
2466                                        | BufferView::CHANGE);
2467                                 // It is possible to make it a lot faster still
2468                                 // just comment out the line below...
2469                                 showCursor();
2470                         }
2471                 } else {
2472                         bv_->cut();
2473                 }
2474                 owner_->showState();
2475                 setState();
2476         }
2477         break;
2478
2479         case LFUN_BACKSPACE_SKIP:
2480         {
2481                 // Reverse the effect of LFUN_BREAKPARAGRAPH_SKIP.
2482                 LyXText * lt = bv_->getLyXText();
2483                 
2484                 LyXCursor cursor = lt->cursor;
2485                 
2486                 if (!lt->selection.set()) {
2487                         if (cursor.pos() == 0 
2488                             && !(cursor.par()->params().spaceTop() 
2489                                  == VSpace (VSpace::NONE))) {
2490                                 lt->setParagraph 
2491                                         (bv_,
2492                                          cursor.par()->params().lineTop(),      
2493                                          cursor.par()->params().lineBottom(),
2494                                          cursor.par()->params().pagebreakTop(), 
2495                                          cursor.par()->params().pagebreakBottom(),
2496                                          VSpace(VSpace::NONE), cursor.par()->params().spaceBottom(),
2497                                          cursor.par()->params().align(), 
2498                                          cursor.par()->params().labelWidthString(), 0);
2499                                 update(lt,
2500                                        BufferView::SELECT
2501                                        | BufferView::FITCUR
2502                                        | BufferView::CHANGE);
2503                         } else {
2504                                 lt->backspace(bv_);
2505                                 lt->selection.cursor = cursor;
2506                                 update(lt,
2507                                        BufferView::SELECT
2508                                        | BufferView::FITCUR
2509                                        | BufferView::CHANGE);
2510                         }
2511                 } else
2512                         bv_->cut();
2513         }
2514         break;
2515
2516         case LFUN_BREAKPARAGRAPH:
2517         {
2518                 LyXText * lt = bv_->getLyXText();
2519                 
2520                 beforeChange(lt);
2521                 lt->breakParagraph(bv_, 0);
2522                 update(lt,
2523                        BufferView::SELECT
2524                        | BufferView::FITCUR
2525                        | BufferView::CHANGE);
2526                 lt->selection.cursor = lt->cursor;
2527                 setState();
2528                 owner_->showState();
2529                 break;
2530         }
2531
2532         case LFUN_BREAKPARAGRAPHKEEPLAYOUT:
2533         {
2534                 LyXText * lt = bv_->getLyXText();
2535                 
2536                 beforeChange(lt);
2537                 lt->breakParagraph(bv_, 1);
2538                 update(lt,
2539                        BufferView::SELECT
2540                        | BufferView::FITCUR
2541                        | BufferView::CHANGE);
2542                 lt->selection.cursor = lt->cursor;
2543                 setState();
2544                 owner_->showState();
2545                 break;
2546         }
2547         
2548         case LFUN_BREAKPARAGRAPH_SKIP:
2549         {
2550                 // When at the beginning of a paragraph, remove
2551                 // indentation and add a "defskip" at the top.
2552                 // Otherwise, do the same as LFUN_BREAKPARAGRAPH.
2553                 LyXText * lt = bv_->getLyXText();
2554                 
2555                 LyXCursor cursor = lt->cursor;
2556                 
2557                 beforeChange(lt);
2558                 if (cursor.pos() == 0) {
2559                         if (cursor.par()->params().spaceTop() == VSpace(VSpace::NONE)) {
2560                                 lt->setParagraph
2561                                         (bv_,
2562                                          cursor.par()->params().lineTop(),      
2563                                          cursor.par()->params().lineBottom(),
2564                                          cursor.par()->params().pagebreakTop(), 
2565                                          cursor.par()->params().pagebreakBottom(),
2566                                          VSpace(VSpace::DEFSKIP), cursor.par()->params().spaceBottom(),
2567                                          cursor.par()->params().align(), 
2568                                          cursor.par()->params().labelWidthString(), 1);
2569                                 //update(BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2570                         } 
2571                 }
2572                 else {
2573                         lt->breakParagraph(bv_, 0);
2574                         //update(BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
2575                 }
2576
2577                 update(lt,
2578                        BufferView::SELECT
2579                        | BufferView::FITCUR
2580                        | BufferView::CHANGE);
2581                 lt->selection.cursor = cursor;
2582                 setState();
2583                 owner_->showState();
2584         }
2585         break;
2586
2587         case LFUN_PARAGRAPH_SPACING:
2588         {
2589                 LyXText * lt = bv_->getLyXText();
2590                 
2591                 Paragraph * par = lt->cursor.par();
2592                 Spacing::Space cur_spacing = par->params().spacing().getSpace();
2593                 float cur_value = 1.0;
2594                 if (cur_spacing == Spacing::Other) {
2595                         cur_value = par->params().spacing().getValue();
2596                 }
2597                 
2598                 istringstream istr(argument.c_str());
2599
2600                 string tmp;
2601                 istr >> tmp;
2602                 Spacing::Space new_spacing = cur_spacing;
2603                 float new_value = cur_value;
2604                 if (tmp.empty()) {
2605                         lyxerr << "Missing argument to `paragraph-spacing'"
2606                                << endl;
2607                 } else if (tmp == "single") {
2608                         new_spacing = Spacing::Single;
2609                 } else if (tmp == "onehalf") {
2610                         new_spacing = Spacing::Onehalf;
2611                 } else if (tmp == "double") {
2612                         new_spacing = Spacing::Double;
2613                 } else if (tmp == "other") {
2614                         new_spacing = Spacing::Other;
2615                         float tmpval = 0.0;
2616                         istr >> tmpval;
2617                         lyxerr << "new_value = " << tmpval << endl;
2618                         if (tmpval != 0.0)
2619                                 new_value = tmpval;
2620                 } else if (tmp == "default") {
2621                         new_spacing = Spacing::Default;
2622                 } else {
2623                         lyxerr << _("Unknown spacing argument: ")
2624                                << argument << endl;
2625                 }
2626                 if (cur_spacing != new_spacing || cur_value != new_value) {
2627                         par->params().spacing(Spacing(new_spacing, new_value));
2628                         lt->redoParagraph(bv_);
2629                         update(lt,
2630                                BufferView::SELECT
2631                                | BufferView::FITCUR
2632                                | BufferView::CHANGE);
2633                 }
2634         }
2635         break;
2636         
2637         case LFUN_QUOTE:
2638                 bv_->insertCorrectQuote();
2639                 break;
2640
2641         case LFUN_HTMLURL:
2642         case LFUN_URL:
2643         {
2644                 InsetCommandParams p;
2645                 if (action == LFUN_HTMLURL)
2646                         p.setCmdName("htmlurl");
2647                 else
2648                         p.setCmdName("url");
2649                 owner_->getDialogs()->createUrl( p.getAsString() );
2650         }
2651         break;
2652         
2653         case LFUN_INSERT_URL:
2654         {
2655                 InsetCommandParams p;
2656                 p.setFromString( argument );
2657
2658                 InsetUrl * inset = new InsetUrl( p );
2659                 if (!insertInset(inset))
2660                         delete inset;
2661                 else
2662                         updateInset( inset, true );
2663         }
2664         break;
2665         
2666         case LFUN_INSET_TEXT:
2667         {
2668                 InsetText * new_inset = new InsetText;
2669                 if (insertInset(new_inset))
2670                         new_inset->edit(bv_, 0, 0, 0);
2671                 else
2672                         delete new_inset;
2673         }
2674         break;
2675         
2676         case LFUN_INSET_ERT:
2677         {
2678                 InsetERT * new_inset = new InsetERT;
2679                 if (insertInset(new_inset))
2680                         new_inset->edit(bv_, 0, 0, 0);
2681                 else
2682                         delete new_inset;
2683         }
2684         break;
2685         
2686         case LFUN_INSET_EXTERNAL:
2687         {
2688                 InsetExternal * new_inset = new InsetExternal;
2689                 if (insertInset(new_inset))
2690                         new_inset->edit(bv_, 0, 0, 0);
2691                 else
2692                         delete new_inset;
2693         }
2694         break;
2695         
2696         case LFUN_INSET_FOOTNOTE:
2697         {
2698                 InsetFoot * new_inset = new InsetFoot;
2699                 if (insertInset(new_inset))
2700                         new_inset->edit(bv_, 0, 0, 0);
2701                 else
2702                         delete new_inset;
2703         }
2704         break;
2705
2706         case LFUN_INSET_MARGINAL:
2707         {
2708                 InsetMarginal * new_inset = new InsetMarginal;
2709                 if (insertInset(new_inset))
2710                         new_inset->edit(bv_, 0, 0, 0);
2711                 else
2712                         delete new_inset;
2713         }
2714         break;
2715
2716         case LFUN_INSET_MINIPAGE:
2717         {
2718                 InsetMinipage * new_inset = new InsetMinipage;
2719                 if (insertInset(new_inset))
2720                         new_inset->edit(bv_, 0, 0, 0);
2721                 else
2722                         delete new_inset;
2723         }
2724         break;
2725
2726         case LFUN_INSET_FLOAT:
2727         {
2728                 // check if the float type exist
2729                 if (floatList.typeExist(argument)) {
2730                         InsetFloat * new_inset = new InsetFloat(argument);
2731                         if (insertInset(new_inset))
2732                                 new_inset->edit(bv_, 0, 0, 0);
2733                         else
2734                                 delete new_inset;
2735                 } else {
2736                         lyxerr << "Non-existant float type: "
2737                                << argument << endl;
2738                 }
2739                 
2740         }
2741         break;
2742
2743         case LFUN_INSET_WIDE_FLOAT:
2744         {
2745                 // check if the float type exist
2746                 if (floatList.typeExist(argument)) {
2747                         InsetFloat * new_inset = new InsetFloat(argument);
2748                         new_inset->wide(true);
2749                         if (insertInset(new_inset))
2750                                 new_inset->edit(bv_, 0, 0, 0);
2751                         else
2752                                 delete new_inset;
2753                 } else {
2754                         lyxerr << "Non-existant float type: "
2755                                << argument << endl;
2756                 }
2757                 
2758         }
2759         break;
2760
2761         case LFUN_INSET_LIST:
2762         {
2763                 InsetList * new_inset = new InsetList;
2764                 if (insertInset(new_inset))
2765                         new_inset->edit(bv_, 0, 0, 0);
2766                 else
2767                         delete new_inset;
2768         }
2769         break;
2770
2771         case LFUN_INSET_THEOREM:
2772         {
2773                 InsetTheorem * new_inset = new InsetTheorem;
2774                 if (insertInset(new_inset))
2775                         new_inset->edit(bv_, 0, 0, 0);
2776                 else
2777                         delete new_inset;
2778         }
2779         break;
2780
2781         case LFUN_INSET_CAPTION:
2782         {
2783                 // Do we have a locking inset...
2784                 if (bv_->theLockingInset()) {
2785                         lyxerr << "Locking inset code: "
2786                                << static_cast<int>(bv_->theLockingInset()->lyxCode());
2787                         InsetCaption * new_inset = new InsetCaption;
2788                         new_inset->setOwner(bv_->theLockingInset());
2789                         new_inset->setAutoBreakRows(true);
2790                         new_inset->setDrawFrame(0, InsetText::LOCKED);
2791                         new_inset->setFrameColor(0, LColor::captionframe);
2792                         if (insertInset(new_inset))
2793                                 new_inset->edit(bv_, 0, 0, 0);
2794                         else
2795                                 delete new_inset;
2796                 }
2797         }
2798         break;
2799         
2800         case LFUN_INSET_TABULAR:
2801         {
2802                 int r = 2;
2803                 int c = 2;
2804                 if (!argument.empty())
2805                         ::sscanf(argument.c_str(),"%d%d", &r, &c);
2806                 InsetTabular * new_inset =
2807                         new InsetTabular(*buffer_, r, c);
2808                 bool const rtl =
2809                         bv_->getLyXText()->real_current_font.isRightToLeft();
2810                 if (!open_new_inset(new_inset, rtl))
2811                         delete new_inset;
2812         }
2813         break;
2814
2815         // --- lyxserver commands ----------------------------
2816
2817         case LFUN_CHARATCURSOR:
2818         {
2819                 Paragraph::size_type pos = bv_->getLyXText()->cursor.pos();
2820                 if (pos < bv_->getLyXText()->cursor.par()->size())
2821                         owner_->getLyXFunc()->setMessage(
2822                                 tostr(bv_->getLyXText()->cursor.par()->getChar(pos)));
2823                 else
2824                         owner_->getLyXFunc()->setMessage("EOF");
2825         }
2826         break;
2827         
2828         case LFUN_GETXY:
2829                 owner_->getLyXFunc()->setMessage(tostr(bv_->getLyXText()->cursor.x())
2830                                                  + ' '
2831                                                  + tostr(bv_->getLyXText()->cursor.y()));
2832                 break;
2833                 
2834         case LFUN_SETXY:
2835         {
2836                 int x = 0;
2837                 int y = 0;
2838                 if (::sscanf(argument.c_str(), " %d %d", &x, &y) != 2) {
2839                         lyxerr << "SETXY: Could not parse coordinates in '"
2840                                << argument << std::endl;
2841                 }
2842                 bv_->getLyXText()->setCursorFromCoordinates(bv_, x, y);
2843         }
2844         break;
2845         
2846         case LFUN_GETLAYOUT:
2847                 owner_->getLyXFunc()->setMessage(tostr(bv_->getLyXText()->cursor.par()->layout));
2848                 break;
2849                         
2850         case LFUN_GETFONT:
2851         {
2852                 LyXFont & font = bv_->getLyXText()->current_font;
2853                 if (font.shape() == LyXFont::ITALIC_SHAPE)
2854                         owner_->getLyXFunc()->setMessage("E");
2855                 else if (font.shape() == LyXFont::SMALLCAPS_SHAPE)
2856                         owner_->getLyXFunc()->setMessage("N");
2857                 else
2858                         owner_->getLyXFunc()->setMessage("0");
2859
2860         }
2861         break;
2862
2863         case LFUN_GETLATEX:
2864         {
2865 #ifndef NO_LATEX
2866                 LyXFont & font = bv_->getLyXText()->current_font;
2867                 if (font.latex() == LyXFont::ON)
2868                         owner_->getLyXFunc()->setMessage("L");
2869                 else
2870 #endif
2871                         owner_->getLyXFunc()->setMessage("0");
2872         }
2873         break;
2874
2875         // --- accented characters ---------------------------
2876                 
2877         case LFUN_UMLAUT:
2878         case LFUN_CIRCUMFLEX:
2879         case LFUN_GRAVE:
2880         case LFUN_ACUTE:
2881         case LFUN_TILDE:
2882         case LFUN_CEDILLA:
2883         case LFUN_MACRON:
2884         case LFUN_DOT:
2885         case LFUN_UNDERDOT:
2886         case LFUN_UNDERBAR:
2887         case LFUN_CARON:
2888         case LFUN_SPECIAL_CARON:
2889         case LFUN_BREVE:
2890         case LFUN_TIE:
2891         case LFUN_HUNG_UMLAUT:
2892         case LFUN_CIRCLE:
2893         case LFUN_OGONEK:
2894                 if (argument.empty()) {
2895                         // As always...
2896                         owner_->getLyXFunc()->handleKeyFunc(action);
2897                 } else {
2898                         owner_->getLyXFunc()->handleKeyFunc(action);
2899                         owner_->getIntl()->getTrans()
2900                                 .TranslateAndInsert(argument[0], bv_->getLyXText());
2901                         update(bv_->getLyXText(),
2902                                BufferView::SELECT
2903                                | BufferView::FITCUR
2904                                | BufferView::CHANGE);
2905                 }
2906                 break;
2907         
2908         case LFUN_MATH_MACRO:
2909                 mathDispatchMathMacro(bv_, argument);
2910                 break;
2911
2912         case LFUN_MATH_DELIM:     
2913                 mathDispatchMathDelim(bv_, argument);
2914                 break;
2915
2916         case LFUN_INSERT_MATRIX:
2917                 mathDispatchInsertMatrix(bv_, argument);
2918                 break;
2919
2920         case LFUN_INSERT_MATH:
2921                 mathDispatchInsertMath(bv_, argument);
2922                 break;
2923
2924         case LFUN_MATH_IMPORT_SELECTION: // Imports LaTeX from the X selection
2925                 mathDispatchMathImportSelection(bv_, argument);
2926                 break;
2927
2928         case LFUN_MATH_DISPLAY:          // Open or create a displayed math inset
2929                 mathDispatchMathDisplay(bv_, argument);
2930                 break;
2931
2932         case LFUN_MATH_MODE:             // Open or create an inlined math inset 
2933                 mathDispatchMathMode(bv_, argument);
2934                 break;
2935                 
2936         case LFUN_CITATION_INSERT:
2937         {
2938                 InsetCommandParams p;
2939                 p.setFromString( argument );
2940
2941                 InsetCitation * inset = new InsetCitation( p );
2942                 if (!insertInset(inset))
2943                         delete inset;
2944                 else
2945                         updateInset( inset, true );
2946         }
2947         break;
2948                     
2949         case LFUN_INSERT_BIBTEX:
2950         {   
2951                 // ale970405+lasgoutt970425
2952                 // The argument can be up to two tokens separated 
2953                 // by a space. The first one is the bibstyle.
2954                 string const db       = token(argument, ' ', 0);
2955                 string bibstyle = token(argument, ' ', 1);
2956                 if (bibstyle.empty())
2957                         bibstyle = "plain";
2958
2959                 InsetCommandParams p( "BibTeX", db, bibstyle );
2960                 InsetBibtex * inset = new InsetBibtex(p);
2961                 
2962                 if (insertInset(inset)) {
2963                         if (argument.empty())
2964                                 inset->edit(bv_, 0, 0, 0);
2965                 } else
2966                         delete inset;
2967         }
2968         break;
2969                 
2970         // BibTeX data bases
2971         case LFUN_BIBDB_ADD:
2972         {
2973                 InsetBibtex * inset = 
2974                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
2975                 if (inset) {
2976                         inset->addDatabase(argument);
2977                 }
2978         }
2979         break;
2980                     
2981         case LFUN_BIBDB_DEL:
2982         {
2983                 InsetBibtex * inset = 
2984                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
2985                 if (inset) {
2986                         inset->delDatabase(argument);
2987                 }
2988         }
2989         break;
2990         
2991         case LFUN_BIBTEX_STYLE:
2992         {
2993                 InsetBibtex * inset = 
2994                         static_cast<InsetBibtex*>(getInsetByCode(Inset::BIBTEX_CODE));
2995                 if (inset) {
2996                         inset->setOptions(argument);
2997                 }
2998         }
2999         break;
3000                 
3001         case LFUN_INDEX_CREATE:
3002         {
3003                 InsetCommandParams p( "index" );
3004                 
3005                 if (argument.empty()) {
3006                         // Get the word immediately preceding the cursor
3007                         Paragraph::size_type curpos = 
3008                                 bv_->getLyXText()->cursor.pos() - 1;
3009
3010                         string curstring;
3011                         if (curpos >= 0 )
3012                                 curstring = bv_->getLyXText()
3013                                         ->cursor.par()->getWord(curpos);
3014
3015                         p.setContents( curstring );
3016                 } else {
3017                         p.setContents( argument );
3018                 }
3019
3020                 owner_->getDialogs()->createIndex( p.getAsString() );
3021         }
3022         break;
3023                     
3024         case LFUN_INDEX_INSERT:
3025         {
3026                 InsetCommandParams p;
3027                 p.setFromString(argument);
3028                 InsetIndex * inset = new InsetIndex(p);
3029
3030                 if (!insertInset(inset))
3031                         delete inset;
3032                 else
3033                         updateInset(inset, true);
3034         }
3035         break;
3036                     
3037         case LFUN_INDEX_INSERT_LAST:
3038         {
3039                 // Get word immediately preceding the cursor
3040                 Paragraph::size_type curpos = 
3041                         bv_->getLyXText()->cursor.pos() - 1;
3042                 // Can't do that at the beginning of a paragraph
3043                 if (curpos < 0) break;
3044
3045                 string const curstring(bv_->getLyXText()
3046                                        ->cursor.par()->getWord(curpos));
3047
3048                 InsetCommandParams p("index", curstring);
3049                 InsetIndex * inset = new InsetIndex(p);
3050
3051                 if (!insertInset(inset))
3052                         delete inset;
3053                 else
3054                         updateInset(inset, true);
3055         }
3056         break;
3057
3058         case LFUN_INDEX_PRINT:
3059         {
3060                 InsetCommandParams p("printindex");
3061                 Inset * inset = new InsetPrintIndex(p);
3062                 if (!insertInset(inset, "Standard"))
3063                         delete inset;
3064         }
3065         break;
3066
3067         case LFUN_PARENTINSERT:
3068         {
3069                 lyxerr << "arg " << argument << endl;
3070                 InsetCommandParams p( "lyxparent", argument );
3071                 Inset * inset = new InsetParent(p, *buffer_);
3072                 if (!insertInset(inset, "Standard"))
3073                         delete inset;
3074         }
3075                  
3076         break;
3077
3078         case LFUN_CHILD_INSERT:
3079         {
3080                 InsetInclude::Params p;
3081                 p.cparams.setFromString(argument);
3082                 p.masterFilename_ = buffer_->fileName();
3083
3084                 InsetInclude * inset = new InsetInclude(p);
3085                 if (!insertInset(inset))
3086                         delete inset;
3087                 else {
3088                         updateInset(inset, true);
3089                         bv_->owner()->getDialogs()->showInclude(inset);
3090                 }
3091         }
3092         break; 
3093
3094         case LFUN_FLOAT_LIST:
3095         {
3096                 // We should check the argument for validity. (Lgb)
3097                 Inset * inset = new InsetFloatList(argument);
3098                 if (!insertInset(inset, "Standard"))
3099                         delete inset;
3100         }
3101         break;
3102         
3103         case LFUN_INSERT_NOTE:
3104                 insertNote();
3105                 break;
3106
3107         case LFUN_SELFINSERT:
3108         {
3109                 if (argument.empty()) break;
3110                 
3111                 /* Automatically delete the currently selected
3112                  * text and replace it with what is being
3113                  * typed in now. Depends on lyxrc settings
3114                  * "auto_region_delete", which defaults to
3115                  * true (on). */
3116
3117                 LyXText * lt = bv_->getLyXText();
3118                 
3119                 if (lyxrc.auto_region_delete) {
3120                         if (lt->selection.set()) {
3121                                 lt->cutSelection(bv_, false);
3122                                 bv_->update(lt,
3123                                             BufferView::SELECT
3124                                             | BufferView::FITCUR
3125                                             | BufferView::CHANGE);
3126                         }
3127                 }
3128                 
3129                 bv_->beforeChange(lt);
3130                 LyXFont const old_font(lt->real_current_font);
3131                 
3132                 string::const_iterator cit = argument.begin();
3133                 string::const_iterator end = argument.end();
3134                 for (; cit != end; ++cit) {
3135                         if (greek_kb_flag) {
3136                                 if (!math_insert_greek(bv_, *cit))
3137                                         owner_->getIntl()->getTrans().TranslateAndInsert(*cit, lt);
3138                         } else
3139                                 owner_->getIntl()->getTrans().TranslateAndInsert(*cit, lt);
3140                 }
3141                 
3142                 bv_->update(lt,
3143                             BufferView::SELECT
3144                             | BufferView::FITCUR
3145                             | BufferView::CHANGE);
3146                 
3147                 lt->selection.cursor = lt->cursor;
3148                 moveCursorUpdate(false);
3149                 
3150                 // real_current_font.number can change so we need to
3151                 // update the minibuffer
3152                 if (old_font != lt->real_current_font)
3153                         owner_->showState();
3154                 //return string();
3155         }
3156         break;
3157
3158         case LFUN_DATE_INSERT:  // jdblair: date-insert cmd
3159         {
3160                 time_t now_time_t = time(NULL);
3161                 struct tm * now_tm = localtime(&now_time_t);
3162                 setlocale(LC_TIME, "");
3163                 string arg;
3164                 if (!argument.empty())
3165                         arg = argument;
3166                 else 
3167                         arg = lyxrc.date_insert_format;
3168                 char datetmp[32];
3169                 int const datetmp_len =
3170                         ::strftime(datetmp, 32, arg.c_str(), now_tm);
3171
3172                 LyXText * lt = bv_->getLyXText();
3173                 
3174                 for (int i = 0; i < datetmp_len; i++) {
3175                         lt->insertChar(bv_, datetmp[i]);
3176                         update(lt,
3177                                BufferView::SELECT
3178                                | BufferView::FITCUR
3179                                | BufferView::CHANGE);
3180                 }
3181
3182                 lt->selection.cursor = lt->cursor;
3183                 moveCursorUpdate(false);
3184         }
3185         break;
3186
3187         case LFUN_UNKNOWN_ACTION:
3188                 owner_->getLyXFunc()->setErrorMessage(N_("Unknown function!"));
3189                 break;
3190         
3191         default:
3192                 return false;
3193         } // end of switch
3194
3195         return true;
3196 }
3197
3198
3199 void BufferView::Pimpl::newline()
3200 {
3201         if (available()) {
3202                 LyXText * lt = bv_->getLyXText();
3203                 hideCursor();
3204                 update(lt,
3205                        BufferView::SELECT
3206                        | BufferView::FITCUR);
3207                 lt->insertChar(bv_, Paragraph::META_NEWLINE);
3208                 update(lt,
3209                        BufferView::SELECT
3210                        | BufferView::FITCUR
3211                        | BufferView::CHANGE);
3212         }
3213 }
3214
3215
3216 void BufferView::Pimpl::hfill()
3217 {
3218         if (available()) {
3219                 LyXText * lt = bv_->getLyXText();
3220                 hideCursor();
3221                 update(lt,
3222                        BufferView::SELECT
3223                        | BufferView::FITCUR);
3224                 lt->insertChar(bv_, Paragraph::META_HFILL);
3225                 update(lt,
3226                        BufferView::SELECT
3227                        | BufferView::FITCUR
3228                        | BufferView::CHANGE);
3229         }
3230 }
3231
3232
3233 void BufferView::Pimpl::protectedBlank(LyXText * lt)
3234 {
3235         if (available()) {
3236                 hideCursor();
3237                 update(lt, BufferView::SELECT|BufferView::FITCUR);
3238                 InsetSpecialChar * new_inset =
3239                         new InsetSpecialChar(InsetSpecialChar::PROTECTED_SEPARATOR);
3240                 if (!insertInset(new_inset))
3241                         delete new_inset;
3242                 else
3243                         updateInset(new_inset, true);
3244         }
3245 }
3246
3247
3248 void BufferView::Pimpl::menuSeparator()
3249 {
3250         if (available()) {
3251                 LyXText * lt = bv_->getLyXText();
3252                 
3253                 hideCursor();
3254                 update(lt, BufferView::SELECT|BufferView::FITCUR);
3255                 InsetSpecialChar * new_inset = 
3256                         new InsetSpecialChar(InsetSpecialChar::MENU_SEPARATOR);
3257                 insertInset(new_inset);
3258         }
3259 }
3260
3261
3262 void BufferView::Pimpl::endOfSentenceDot()
3263 {
3264         if (available()) {
3265                 hideCursor();
3266                 update(bv_->getLyXText(), BufferView::SELECT|BufferView::FITCUR);
3267                 InsetSpecialChar * new_inset = 
3268                         new InsetSpecialChar(InsetSpecialChar::END_OF_SENTENCE);
3269                 insertInset(new_inset);
3270         }
3271 }
3272
3273
3274 void BufferView::Pimpl::ldots()
3275 {
3276         if (available())  {
3277                 hideCursor();
3278                 update(bv_->getLyXText(), BufferView::SELECT|BufferView::FITCUR);
3279                 InsetSpecialChar * new_inset = 
3280                         new InsetSpecialChar(InsetSpecialChar::LDOTS);
3281                 insertInset(new_inset);
3282         }
3283 }
3284
3285
3286 void BufferView::Pimpl::hyphenationPoint()
3287 {
3288         if (available()) {
3289                 hideCursor();
3290                 update(bv_->getLyXText(), BufferView::SELECT|BufferView::FITCUR);
3291                 InsetSpecialChar * new_inset = 
3292                         new InsetSpecialChar(InsetSpecialChar::HYPHENATION);
3293                 insertInset(new_inset);
3294         }
3295 }
3296
3297
3298 void BufferView::Pimpl::insertNote()
3299 {
3300         InsetInfo * new_inset = new InsetInfo();
3301         insertInset(new_inset);
3302         new_inset->edit(bv_, 0, 0, 0);
3303 }
3304
3305
3306 // Open and lock an updatable inset
3307 bool BufferView::Pimpl::open_new_inset(UpdatableInset * new_inset, bool behind)
3308 {
3309         LyXText * lt = bv_->getLyXText();
3310         
3311         beforeChange(lt);
3312         finishUndo();
3313         if (!insertInset(new_inset)) {
3314                 delete new_inset;
3315                 return false;
3316         }
3317         if (behind) {
3318                 LyXFont & font = lt->real_current_font;
3319                 new_inset->edit(bv_, new_inset->width(bv_, font), 0, 0);
3320         } else
3321                 new_inset->edit(bv_, 0, 0, 0);
3322         return true;
3323 }
3324
3325
3326 bool BufferView::Pimpl::insertInset(Inset * inset, string const & lout)
3327 {
3328         // if we are in a locking inset we should try to insert the
3329         // inset there otherwise this is a illegal function now
3330         if (bv_->theLockingInset()) {
3331                 if (bv_->theLockingInset()->insertInsetAllowed(inset))
3332                     return bv_->theLockingInset()->insertInset(bv_, inset);
3333                 return false;
3334         }
3335
3336         // not quite sure if we want this...
3337         setCursorParUndo(bv_);
3338         freezeUndo();
3339         
3340         beforeChange(bv_->text);
3341         if (!lout.empty()) {
3342                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
3343                 bv_->text->breakParagraph(bv_);
3344                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3345
3346                 if (bv_->text->cursor.par()->size()) {
3347                         bv_->text->cursorLeft(bv_);
3348                         
3349                         bv_->text->breakParagraph(bv_);
3350                         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3351                 }
3352
3353                 pair<bool, LyXTextClass::size_type> lres =
3354                         textclasslist.NumberOfLayout(buffer_->params
3355                                                      .textclass, lout);
3356                 LyXTextClass::size_type lay;
3357                 if (lres.first != false) {
3358                         // layout found
3359                         lay = lres.second;
3360                 } else {
3361                         // layout not fount using default "Standard" (0)
3362                         lay = 0;
3363                 }
3364                  
3365                 bv_->text->setLayout(bv_, lay);
3366                 
3367                 bv_->text->setParagraph(bv_, 0, 0,
3368                                    0, 0,
3369                                    VSpace(VSpace::NONE), VSpace(VSpace::NONE),
3370                                    LYX_ALIGN_LAYOUT, 
3371                                    string(),
3372                                    0);
3373                 update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3374 #ifndef NO_LATEX
3375                 bv_->text->current_font.setLatex(LyXFont::OFF);
3376 #endif
3377         }
3378         
3379         bv_->text->insertInset(bv_, inset);
3380         update(bv_->text, BufferView::SELECT|BufferView::FITCUR|BufferView::CHANGE);
3381
3382         unFreezeUndo();
3383         return true;
3384 }
3385
3386
3387 void BufferView::Pimpl::updateInset(Inset * inset, bool mark_dirty)
3388 {
3389         if (!inset)
3390                 return;
3391
3392         // first check for locking insets
3393         if (bv_->theLockingInset()) {
3394                 if (bv_->theLockingInset() == inset) {
3395                         if (bv_->text->updateInset(bv_, inset)) {
3396                                 update();
3397                                 if (mark_dirty) {
3398                                         buffer_->markDirty();
3399                                 }
3400                                 updateScrollbar();
3401                                 return;
3402                         }
3403                 } else if (bv_->theLockingInset()->updateInsetInInset(bv_, inset)) {
3404                         if (bv_->text->updateInset(bv_,
3405                                                    bv_->theLockingInset())) {
3406                                 update();
3407                                 if (mark_dirty){
3408                                         buffer_->markDirty();
3409                                 }
3410                                 updateScrollbar();
3411                                 return;
3412                         }
3413                 }
3414         }
3415   
3416         // then check the current buffer
3417         if (available()) {
3418                 hideCursor();
3419                 update(bv_->text, BufferView::UPDATE);
3420                 if (bv_->text->updateInset(bv_, inset)) {
3421                         if (mark_dirty) {
3422                                 update(bv_->text,
3423                                        BufferView::SELECT
3424                                        | BufferView::FITCUR
3425                                        | BufferView::CHANGE);
3426                         } else {
3427                                 update(bv_->text, SELECT);
3428                         }
3429                         return;
3430                 }
3431         }
3432 }
3433
3434
3435 void BufferView::Pimpl::gotoInset(vector<Inset::Code> const & codes,
3436                                   bool same_content)
3437 {
3438         if (!available()) return;
3439         
3440         hideCursor();
3441         beforeChange(bv_->text);
3442         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
3443         
3444         string contents;
3445         if (same_content &&
3446             bv_->text->cursor.par()->getChar(bv_->text->cursor.pos()) == Paragraph::META_INSET) {
3447                 Inset const * inset = bv_->text->cursor.par()->getInset(bv_->text->cursor.pos());
3448                 if (find(codes.begin(), codes.end(), inset->lyxCode())
3449                     != codes.end())
3450                         contents =
3451                                 static_cast<InsetCommand const *>(inset)->getContents();
3452         }
3453         
3454         if (!bv_->text->gotoNextInset(bv_, codes, contents)) {
3455                 if (bv_->text->cursor.pos() 
3456                     || bv_->text->cursor.par() != bv_->text->firstParagraph()) {
3457                         LyXCursor tmp = bv_->text->cursor;
3458                         bv_->text->cursor.par(bv_->text->firstParagraph());
3459                         bv_->text->cursor.pos(0);
3460                         if (!bv_->text->gotoNextInset(bv_, codes, contents)) {
3461                                 bv_->text->cursor = tmp;
3462                                 bv_->owner()->message(_("No more insets"));
3463                         }
3464                 } else {
3465                         bv_->owner()->message(_("No more insets"));
3466                 }
3467         }
3468         update(bv_->text, BufferView::SELECT|BufferView::FITCUR);
3469         bv_->text->selection.cursor = bv_->text->cursor;
3470 }
3471
3472
3473 void BufferView::Pimpl::gotoInset(Inset::Code code, bool same_content)
3474 {
3475         gotoInset(vector<Inset::Code>(1, code), same_content);
3476 }