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