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