]> git.lyx.org Git - lyx.git/blob - src/BufferView.C
a448a86534cd91375f03ad40db31755749563a11
[lyx.git] / src / BufferView.C
1 /**
2  * \file BufferView.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Alfredo Braunstein
7  * \author Lars Gullik Bjønnes
8  * \author John Levon
9  * \author André Pönitz
10  * \author Jürgen Vigna
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #include <config.h>
16
17 #include "BufferView.h"
18
19 #include "buffer.h"
20 #include "buffer_funcs.h"
21 #include "bufferlist.h"
22 #include "bufferparams.h"
23 #include "coordcache.h"
24 #include "CutAndPaste.h"
25 #include "debug.h"
26 #include "dispatchresult.h"
27 #include "errorlist.h"
28 #include "factory.h"
29 #include "FloatList.h"
30 #include "funcrequest.h"
31 #include "FuncStatus.h"
32 #include "gettext.h"
33 #include "intl.h"
34 #include "insetiterator.h"
35 #include "language.h"
36 #include "LaTeXFeatures.h"
37 #include "lyx_cb.h" // added for Dispatch functions
38 #include "lyx_main.h"
39 #include "lyxfind.h"
40 #include "lyxfunc.h"
41 #include "lyxlayout.h"
42 #include "lyxtext.h"
43 #include "lyxtextclass.h"
44 #include "lyxrc.h"
45 #include "session.h"
46 #include "paragraph.h"
47 #include "paragraph_funcs.h"
48 #include "ParagraphParameters.h"
49 #include "pariterator.h"
50 #include "texrow.h"
51 #include "toc.h"
52 #include "undo.h"
53 #include "vspace.h"
54 #include "WordLangTuple.h"
55 #include "metricsinfo.h"
56
57 #include "insets/insetbibtex.h"
58 #include "insets/insetcommand.h" // ChangeRefs
59 #include "insets/insetref.h"
60 #include "insets/insettext.h"
61
62 #include "frontends/Alert.h"
63 #include "frontends/FileDialog.h"
64 #include "frontends/FontMetrics.h"
65
66 #include "graphics/Previews.h"
67
68 #include "support/convert.h"
69 #include "support/filefilterlist.h"
70 #include "support/filetools.h"
71 #include "support/package.h"
72 #include "support/types.h"
73
74 #include <boost/bind.hpp>
75 #include <boost/current_function.hpp>
76
77 #include <functional>
78 #include <vector>
79
80
81 namespace lyx {
82
83 using support::addPath;
84 using support::bformat;
85 using support::FileFilterList;
86 using support::fileSearch;
87 using support::isDirWriteable;
88 using support::makeDisplayPath;
89 using support::makeAbsPath;
90 using support::package;
91
92 using std::distance;
93 using std::endl;
94 using std::istringstream;
95 using std::make_pair;
96 using std::min;
97 using std::max;
98 using std::mem_fun_ref;
99 using std::string;
100 using std::vector;
101
102 namespace Alert = frontend::Alert;
103
104 namespace {
105
106 unsigned int const saved_positions_num = 20;
107
108
109 /// Return an inset of this class if it exists at the current cursor position
110 template <class T>
111 T * getInsetByCode(LCursor & cur, InsetBase::Code code)
112 {
113         T * inset = 0;
114         DocIterator it = cur;
115         if (it.nextInset() &&
116             it.nextInset()->lyxCode() == code) {
117                 inset = static_cast<T*>(it.nextInset());
118         }
119         return inset;
120 }
121
122 } // anon namespace
123
124
125 BufferView::BufferView()
126         : buffer_(0), wh_(0),
127           cursor_(*this),
128           multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
129           intl_(new Intl)
130 {
131         xsel_cache_.set = false;
132
133         saved_positions.resize(saved_positions_num);
134         // load saved bookmarks
135         Session::BookmarkList & bmList = LyX::ref().session().loadBookmarks();
136         for (Session::BookmarkList::iterator bm = bmList.begin();
137                 bm != bmList.end(); ++bm)
138                 if (bm->get<0>() < saved_positions_num)
139                         saved_positions[bm->get<0>()] = Position( bm->get<1>(), bm->get<2>(), bm->get<3>() );
140         // and then clear them
141         bmList.clear();
142
143         intl_->initKeyMapper(lyxrc.use_kbmap);
144 }
145
146
147 BufferView::~BufferView()
148 {
149 }
150
151
152 Buffer * BufferView::buffer() const
153 {
154         return buffer_;
155 }
156
157
158 void BufferView::setBuffer(Buffer * b)
159 {
160         lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
161                             << "[ b = " << b << "]" << endl;
162
163         if (buffer_) {
164                 // Save the actual cursor position and anchor inside the
165                 // buffer so that it can be restored in case we rechange
166                 // to this buffer later on.
167                 buffer_->saveCursor(cursor_.selectionBegin(),
168                                     cursor_.selectionEnd());
169                 // current buffer is going to be switched-off, save cursor pos
170                 LyX::ref().session().saveFilePosition(buffer_->fileName(),
171                         boost::tie(cursor_.pit(), cursor_.pos()) );
172         }
173
174         // If we're quitting lyx, don't bother updating stuff
175         if (quitting) {
176                 buffer_ = 0;
177                 return;
178         }
179
180         // If we are closing current buffer, switch to the first in
181         // buffer list.
182         if (!b) {
183                 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
184                                     << " No Buffer!" << endl;
185                 // We are closing the buffer, use the first buffer as current
186                 buffer_ = theBufferList().first();
187         } else {
188                 // Set current buffer
189                 buffer_ = b;
190         }
191
192         // Reset old cursor
193         cursor_ = LCursor(*this);
194         anchor_ref_ = 0;
195         offset_ref_ = 0;
196
197         if (buffer_) {
198                 lyxerr[Debug::INFO] << BOOST_CURRENT_FUNCTION
199                                     << "Buffer addr: " << buffer_ << endl;
200                 cursor_.push(buffer_->inset());
201                 cursor_.resetAnchor();
202                 buffer_->text().init(this);
203                 buffer_->text().setCurrentFont(cursor_);
204                 if (buffer_->getCursor().size() > 0 &&
205                     buffer_->getAnchor().size() > 0)
206                 {
207                         cursor_.setCursor(buffer_->getAnchor().asDocIterator(&(buffer_->inset())));
208                         cursor_.resetAnchor();
209                         cursor_.setCursor(buffer_->getCursor().asDocIterator(&(buffer_->inset())));
210                         cursor_.setSelection();
211                 }
212         }
213
214         update();
215
216         if (buffer_ && graphics::Previews::status() != LyXRC::PREVIEW_OFF)
217                 graphics::Previews::get().generateBufferPreviews(*buffer_);
218 }
219
220
221 bool BufferView::loadLyXFile(string const & filename, bool tolastfiles)
222 {
223         // Get absolute path of file and add ".lyx"
224         // to the filename if necessary
225         string s = fileSearch(string(), filename, "lyx");
226
227         bool const found = !s.empty();
228
229         if (!found)
230                 s = filename;
231
232         // File already open?
233         if (theBufferList().exists(s)) {
234                 docstring const file = makeDisplayPath(s, 20);
235                 docstring text = bformat(_("The document %1$s is already "
236                                                      "loaded.\n\nDo you want to revert "
237                                                      "to the saved version?"), file);
238                 int const ret = Alert::prompt(_("Revert to saved document?"),
239                         text, 0, 1,  _("&Revert"), _("&Switch to document"));
240
241                 if (ret != 0) {
242                         setBuffer(theBufferList().getBuffer(s));
243                         return true;
244                 }
245                 // FIXME: should be LFUN_REVERT
246                 if (!theBufferList().close(theBufferList().getBuffer(s), false))
247                         return false;
248                 // Fall through to new load. (Asger)
249         }
250
251         Buffer * b = 0;
252
253         if (found) {
254                 b = theBufferList().newBuffer(s);
255                 if (!lyx::loadLyXFile(b, s)) {
256                         theBufferList().release(b);
257                         return false;
258                 }
259         } else {
260                 docstring text = bformat(_("The document %1$s does not yet "
261                                                      "exist.\n\nDo you want to create "
262                                                      "a new document?"), from_utf8(s));
263                 int const ret = Alert::prompt(_("Create new document?"),
264                          text, 0, 1, _("&Create"), _("Cancel"));
265
266                 if (ret == 0) {
267                         b = newFile(s, string(), true);
268                         if (!b)
269                                 return false;
270                 } else
271                         return false;
272         }
273
274         setBuffer(b);
275         // Send the "errors" signal in case of parsing errors
276         b->errors("Parse");
277
278         // scroll to the position when the file was last closed
279         if (lyxrc.use_lastfilepos) {
280                 pit_type pit;
281                 pos_type pos;
282                 boost::tie(pit, pos) = LyX::ref().session().loadFilePosition(s);
283                 // I am not sure how to separate the following part to a function
284                 // so I will leave this to Lars.
285                 //
286                 // check pit since the document may be externally changed.
287                 if ( static_cast<size_t>(pit) < b->paragraphs().size() ) {
288                         ParIterator it = b->par_iterator_begin();
289                         ParIterator const end = b->par_iterator_end();
290                         for (; it != end; ++it)
291                                 if (it.pit() == pit) {
292                                         // restored pos may be bigger than it->size
293                                         setCursor(makeDocIterator(it, min(pos, it->size())));
294                                         update(Update::FitCursor);
295                                         break;
296                                 }
297                 }
298         }
299
300         if (tolastfiles)
301                 LyX::ref().session().addLastFile(b->fileName());
302
303         return true;
304 }
305
306
307 void BufferView::reload()
308 {
309         string const fn = buffer_->fileName();
310         if (theBufferList().close(buffer_, false))
311                 loadLyXFile(fn);
312 }
313
314
315 void BufferView::resize()
316 {
317         if (!buffer_)
318                 return;
319
320         lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION << endl;
321
322         buffer_->text().init(this);
323         update();
324         switchKeyMap();
325 }
326
327
328 bool BufferView::fitCursor()
329 {
330         if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
331                 frontend::FontMetrics const & fm =
332                         theFontMetrics(cursor_.getFont());
333                 int const asc = fm.maxAscent();
334                 int const des = fm.maxDescent();
335                 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
336                 if (p.y_ - asc >= 0 && p.y_ + des < height_)
337                         return false;
338         }
339         center();
340         return true;
341 }
342
343
344 bool BufferView::multiParSel()
345 {
346         if (!cursor_.selection())
347                 return false;
348         bool ret = multiparsel_cache_;
349         multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
350         // Either this, or previous selection spans paragraphs
351         return ret || multiparsel_cache_;
352 }
353
354
355 bool BufferView::update(Update::flags flags)
356 {
357         // This is close to a hot-path.
358         if (lyxerr.debugging(Debug::DEBUG)) {
359                 lyxerr[Debug::DEBUG]
360                         << BOOST_CURRENT_FUNCTION
361                         << "[fitcursor = " << (flags & Update::FitCursor)
362                         << ", forceupdate = " << (flags & Update::Force)
363                         << ", singlepar = " << (flags & Update::SinglePar)
364                         << "]  buffer: " << buffer_ << endl;
365         }
366
367         // Check needed to survive LyX startup
368         if (!buffer_)
369                 return false;
370
371         lyxerr[Debug::WORKAREA] << "BufferView::update" << std::endl;
372
373         // Update macro store
374         buffer_->buildMacros();
375
376         // First drawing step
377         updateMetrics(flags & Update::SinglePar);
378
379         // The second drawing step is done in WorkArea::redraw() if needed.
380         bool const need_second_step =
381                 (flags & (Update::Force | Update::FitCursor | Update::MultiParSel))
382                 && (fitCursor() || multiParSel());
383
384         return need_second_step;
385 }
386
387
388 void BufferView::updateScrollbar()
389 {
390         if (!buffer_) {
391                 lyxerr[Debug::DEBUG] << BOOST_CURRENT_FUNCTION
392                                      << " no text in updateScrollbar" << endl;
393                 scrollbarParameters_.reset();
394                 return;
395         }
396
397         LyXText & t = buffer_->text();
398         int const parsize = int(t.paragraphs().size() - 1);
399         if (anchor_ref_ >  parsize)  {
400                 anchor_ref_ = parsize;
401                 offset_ref_ = 0;
402         }
403
404         lyxerr[Debug::GUI]
405                 << BOOST_CURRENT_FUNCTION
406                 << " Updating scrollbar: height: " << t.paragraphs().size()
407                 << " curr par: " << cursor_.bottom().pit()
408                 << " default height " << defaultRowHeight() << endl;
409
410         // It would be better to fix the scrollbar to understand
411         // values in [0..1] and divide everything by wh
412
413         // estimated average paragraph height:
414         if (wh_ == 0)
415                 wh_ = height_ / 4;
416         int h = t.getPar(anchor_ref_).height();
417
418         // Normalize anchor/offset (MV):
419         while (offset_ref_ > h && anchor_ref_ < parsize) {
420                 anchor_ref_++;
421                 offset_ref_ -= h;
422                 h = t.getPar(anchor_ref_).height();
423         }
424         // Look at paragraph heights on-screen
425         int sumh = 0;
426         int nh = 0;
427         for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
428                 if (sumh > height_)
429                         break;
430                 int const h2 = t.getPar(pit).height();
431                 sumh += h2;
432                 nh++;
433         }
434         int const hav = sumh / nh;
435         // More realistic average paragraph height
436         if (hav > wh_)
437                 wh_ = hav;
438
439         scrollbarParameters_.height = (parsize + 1) * wh_;
440         scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
441         scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
442 }
443
444
445 ScrollbarParameters const & BufferView::scrollbarParameters() const
446 {
447         return scrollbarParameters_;
448 }
449
450
451 void BufferView::scrollDocView(int value)
452 {
453         lyxerr[Debug::GUI] << BOOST_CURRENT_FUNCTION
454                            << "[ value = " << value << "]" << endl;
455
456         if (!buffer_)
457                 return;
458
459         LyXText & t = buffer_->text();
460
461         float const bar = value / float(wh_ * t.paragraphs().size());
462
463         anchor_ref_ = int(bar * t.paragraphs().size());
464         if (anchor_ref_ >  int(t.paragraphs().size()) - 1)
465                 anchor_ref_ = int(t.paragraphs().size()) - 1;
466         t.redoParagraph(anchor_ref_);
467         int const h = t.getPar(anchor_ref_).height();
468         offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
469 }
470
471
472 void BufferView::setCursorFromScrollbar()
473 {
474         LyXText & t = buffer_->text();
475
476         int const height = 2 * defaultRowHeight();
477         int const first = height;
478         int const last = height_ - height;
479         LCursor & cur = cursor_;
480
481         bv_funcs::CurStatus st = bv_funcs::status(this, cur);
482
483         switch (st) {
484         case bv_funcs::CUR_ABOVE:
485                 t.setCursorFromCoordinates(cur, 0, first);
486                 cur.clearSelection();
487                 break;
488         case bv_funcs::CUR_BELOW:
489                 t.setCursorFromCoordinates(cur, 0, last);
490                 cur.clearSelection();
491                 break;
492         case bv_funcs::CUR_INSIDE:
493                 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
494                 int const newy = min(last, max(y, first));
495                 if (y != newy) {
496                         cur.reset(buffer_->inset());
497                         t.setCursorFromCoordinates(cur, 0, newy);
498                 }
499         }
500 }
501
502
503 Change const BufferView::getCurrentChange() const
504 {
505         if (!cursor_.selection())
506                 return Change(Change::UNCHANGED);
507
508         DocIterator dit = cursor_.selectionBegin();
509         return dit.paragraph().lookupChange(dit.pos());
510 }
511
512
513 void BufferView::savePosition(unsigned int i)
514 {
515         if (i >= saved_positions_num)
516                 return;
517         BOOST_ASSERT(cursor_.inTexted());
518         saved_positions[i] = Position(buffer_->fileName(),
519                                       cursor_.paragraph().id(),
520                                       cursor_.pos());
521         if (i > 0)
522                 // emit message signal.
523                 message(bformat(_("Saved bookmark %1$d"), i));
524 }
525
526
527 void BufferView::restorePosition(unsigned int i)
528 {
529         if (i >= saved_positions_num)
530                 return;
531
532         string const fname = saved_positions[i].filename;
533
534         cursor_.clearSelection();
535
536         if (fname != buffer_->fileName()) {
537                 Buffer * b = 0;
538                 if (theBufferList().exists(fname))
539                         b = theBufferList().getBuffer(fname);
540                 else {
541                         b = theBufferList().newBuffer(fname);
542                         // Don't ask, just load it
543                         lyx::loadLyXFile(b, fname);
544                 }
545                 if (b)
546                         setBuffer(b);
547         }
548
549         ParIterator par = buffer_->getParFromID(saved_positions[i].par_id);
550         if (par == buffer_->par_iterator_end())
551                 return;
552
553         setCursor(makeDocIterator(par, min(par->size(), saved_positions[i].par_pos)));
554
555         if (i > 0)
556                 // emit message signal.
557                 message(bformat(_("Moved to bookmark %1$d"), i));
558 }
559
560
561 bool BufferView::isSavedPosition(unsigned int i)
562 {
563         return i < saved_positions_num && !saved_positions[i].filename.empty();
564 }
565
566 void BufferView::saveSavedPositions()
567 {
568         // save bookmarks. It is better to use the pit interface
569         // but I do not know how to effectively convert between
570         // par_id and pit.
571         for (unsigned int i=1; i < saved_positions_num; ++i) {
572                 if ( isSavedPosition(i) )
573                         LyX::ref().session().saveBookmark( boost::tie(
574                                 i,
575                                 saved_positions[i].filename,
576                                 saved_positions[i].par_id,
577                                 saved_positions[i].par_pos) );
578         }
579 }
580
581 void BufferView::switchKeyMap()
582 {
583         if (!lyxrc.rtl_support)
584                 return;
585
586         if (getLyXText()->real_current_font.isRightToLeft()) {
587                 if (intl_->keymap == Intl::PRIMARY)
588                         intl_->keyMapSec();
589         } else {
590                 if (intl_->keymap == Intl::SECONDARY)
591                         intl_->keyMapPrim();
592         }
593 }
594
595
596 int BufferView::workWidth() const
597 {
598         return width_;
599 }
600
601
602 void BufferView::center()
603 {
604         CursorSlice & bot = cursor_.bottom();
605         pit_type const pit = bot.pit();
606         bot.text()->redoParagraph(pit);
607         Paragraph const & par = bot.text()->paragraphs()[pit];
608         anchor_ref_ = pit;
609         offset_ref_ = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary()).y_
610                 + par.ascent() - height_ / 2;
611 }
612
613
614 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
615 {
616         FuncStatus flag;
617
618         switch (cmd.action) {
619
620         case LFUN_UNDO:
621                 flag.enabled(!buffer_->undostack().empty());
622                 break;
623         case LFUN_REDO:
624                 flag.enabled(!buffer_->redostack().empty());
625                 break;
626         case LFUN_FILE_INSERT:
627         case LFUN_FILE_INSERT_ASCII_PARA:
628         case LFUN_FILE_INSERT_ASCII:
629         case LFUN_BOOKMARK_SAVE:
630                 // FIXME: Actually, these LFUNS should be moved to LyXText
631                 flag.enabled(cursor_.inTexted());
632                 break;
633         case LFUN_FONT_STATE:
634         case LFUN_LABEL_INSERT:
635         case LFUN_PARAGRAPH_GOTO:
636         // FIXME handle non-trivially
637         case LFUN_OUTLINE_UP:
638         case LFUN_OUTLINE_DOWN:
639         case LFUN_OUTLINE_IN:
640         case LFUN_OUTLINE_OUT:
641         case LFUN_NOTE_NEXT:
642         case LFUN_REFERENCE_NEXT:
643         case LFUN_WORD_FIND:
644         case LFUN_WORD_REPLACE:
645         case LFUN_MARK_OFF:
646         case LFUN_MARK_ON:
647         case LFUN_MARK_TOGGLE:
648         case LFUN_SCREEN_RECENTER:
649         case LFUN_BIBTEX_DATABASE_ADD:
650         case LFUN_BIBTEX_DATABASE_DEL:
651         case LFUN_WORDS_COUNT:
652         case LFUN_NEXT_INSET_TOGGLE:
653                 flag.enabled(true);
654                 break;
655
656         case LFUN_LABEL_GOTO: {
657                 flag.enabled(!cmd.argument().empty()
658                     || getInsetByCode<InsetRef>(cursor_, InsetBase::REF_CODE));
659                 break;
660         }
661
662         case LFUN_BOOKMARK_GOTO:
663                 flag.enabled(isSavedPosition(convert<unsigned int>(to_utf8(cmd.argument()))));
664                 break;
665
666         case LFUN_CHANGES_TRACK:
667                 flag.enabled(true);
668                 flag.setOnOff(buffer_->params().trackChanges);
669                 break;
670
671         case LFUN_CHANGES_OUTPUT: {
672                 OutputParams runparams;
673                 LaTeXFeatures features(*buffer_, buffer_->params(), runparams);
674                 flag.enabled(buffer_ && features.isAvailable("dvipost"));
675                 flag.setOnOff(buffer_->params().outputChanges);
676                 break;
677         }
678
679         case LFUN_CHANGES_MERGE:
680         case LFUN_CHANGE_NEXT:
681         case LFUN_ALL_CHANGES_ACCEPT:
682         case LFUN_ALL_CHANGES_REJECT:
683                 flag.enabled(buffer_); // FIXME: Change tracking (MG)
684                 break;
685
686         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
687                 flag.setOnOff(buffer_->params().compressed);
688                 break;
689         }
690
691         default:
692                 flag.enabled(false);
693         }
694
695         return flag;
696 }
697
698
699 bool BufferView::dispatch(FuncRequest const & cmd)
700 {
701         //lyxerr << BOOST_CURRENT_FUNCTION
702         //       << [ cmd = " << cmd << "]" << endl;
703
704         // Make sure that the cached BufferView is correct.
705         lyxerr[Debug::ACTION] << BOOST_CURRENT_FUNCTION
706                 << " action[" << cmd.action << ']'
707                 << " arg[" << to_utf8(cmd.argument()) << ']'
708                 << " x[" << cmd.x << ']'
709                 << " y[" << cmd.y << ']'
710                 << " button[" << cmd.button() << ']'
711                 << endl;
712
713         LCursor & cur = cursor_;
714
715         switch (cmd.action) {
716
717         case LFUN_UNDO:
718                 if (buffer_) {
719                         cur.message(_("Undo"));
720                         cur.clearSelection();
721                         if (!textUndo(*this))
722                                 cur.message(_("No further undo information"));
723                         update();
724                         switchKeyMap();
725                 }
726                 break;
727
728         case LFUN_REDO:
729                 if (buffer_) {
730                         cur.message(_("Redo"));
731                         cur.clearSelection();
732                         if (!textRedo(*this))
733                                 cur.message(_("No further redo information"));
734                         update();
735                         switchKeyMap();
736                 }
737                 break;
738
739         case LFUN_FILE_INSERT:
740                 // FIXME: We don't know the encoding of filenames
741                 menuInsertLyXFile(to_utf8(cmd.argument()));
742                 break;
743
744         case LFUN_FILE_INSERT_ASCII_PARA:
745                 // FIXME: We don't know the encoding of filenames
746                 insertAsciiFile(this, to_utf8(cmd.argument()), true);
747                 break;
748
749         case LFUN_FILE_INSERT_ASCII:
750                 // FIXME: We don't know the encoding of filenames
751                 insertAsciiFile(this, to_utf8(cmd.argument()), false);
752                 break;
753
754         case LFUN_FONT_STATE:
755                 cur.message(from_utf8(cur.currentState()));
756                 break;
757
758         case LFUN_BOOKMARK_SAVE:
759                 savePosition(convert<unsigned int>(to_utf8(cmd.argument())));
760                 break;
761
762         case LFUN_BOOKMARK_GOTO:
763                 restorePosition(convert<unsigned int>(to_utf8(cmd.argument())));
764                 break;
765
766         case LFUN_LABEL_GOTO: {
767                 docstring label = cmd.argument();
768                 if (label.empty()) {
769                         InsetRef * inset =
770                                 getInsetByCode<InsetRef>(cursor_,
771                                                          InsetBase::REF_CODE);
772                         if (inset) {
773                                 label = inset->getParam("reference");
774                                 savePosition(0);
775                         }
776                 }
777
778                 if (!label.empty())
779                         gotoLabel(label);
780                 break;
781         }
782
783         case LFUN_PARAGRAPH_GOTO: {
784                 int const id = convert<int>(to_utf8(cmd.argument()));
785                 ParIterator par = buffer_->getParFromID(id);
786                 if (par == buffer_->par_iterator_end()) {
787                         lyxerr[Debug::INFO] << "No matching paragraph found! ["
788                                             << id << ']' << endl;
789                         break;
790                 } else {
791                         lyxerr[Debug::INFO] << "Paragraph " << par->id()
792                                             << " found." << endl;
793                 }
794
795                 // Set the cursor
796                 setCursor(makeDocIterator(par, 0));
797
798                 update();
799                 switchKeyMap();
800                 break;
801         }
802
803         case LFUN_OUTLINE_UP:
804                 toc::outline(toc::Up, cursor_);
805                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
806                 updateLabels(*buffer_);
807                 break;
808         case LFUN_OUTLINE_DOWN:
809                 toc::outline(toc::Down, cursor_);
810                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
811                 updateLabels(*buffer_);
812                 break;
813         case LFUN_OUTLINE_IN:
814                 toc::outline(toc::In, cursor_);
815                 updateLabels(*buffer_);
816                 break;
817         case LFUN_OUTLINE_OUT:
818                 toc::outline(toc::Out, cursor_);
819                 updateLabels(*buffer_);
820                 break;
821
822         case LFUN_NOTE_NEXT:
823                 bv_funcs::gotoInset(this, InsetBase::NOTE_CODE, false);
824                 break;
825
826         case LFUN_REFERENCE_NEXT: {
827                 vector<InsetBase_code> tmp;
828                 tmp.push_back(InsetBase::LABEL_CODE);
829                 tmp.push_back(InsetBase::REF_CODE);
830                 bv_funcs::gotoInset(this, tmp, true);
831                 break;
832         }
833
834         case LFUN_CHANGES_TRACK:
835                 buffer_->params().trackChanges = !buffer_->params().trackChanges;
836                 break;
837
838         case LFUN_CHANGES_OUTPUT: {
839                 buffer_->params().outputChanges = !buffer_->params().outputChanges;
840                 break;
841         }
842
843         case LFUN_CHANGE_NEXT:
844                 findNextChange(this);
845                 break;
846
847         case LFUN_CHANGES_MERGE:
848                 if (findNextChange(this))
849                         showDialog("changes");
850                 break;
851
852         case LFUN_ALL_CHANGES_ACCEPT: {
853                 cursor_.reset(buffer_->inset());
854 #ifdef WITH_WARNINGS
855 #warning FIXME changes
856 #endif
857                 while (findNextChange(this))
858                         getLyXText()->acceptChange(cursor_);
859                 update();
860                 break;
861         }
862
863         case LFUN_ALL_CHANGES_REJECT: {
864                 cursor_.reset(buffer_->inset());
865 #ifdef WITH_WARNINGS
866 #warning FIXME changes
867 #endif
868                 while (findNextChange(this))
869                         getLyXText()->rejectChange(cursor_);
870                 break;
871         }
872
873         case LFUN_WORD_FIND:
874                 find(this, cmd);
875                 break;
876
877         case LFUN_WORD_REPLACE:
878                 replace(this, cmd);
879                 break;
880
881         case LFUN_MARK_OFF:
882                 cur.clearSelection();
883                 cur.resetAnchor();
884                 cur.message(from_utf8(N_("Mark off")));
885                 break;
886
887         case LFUN_MARK_ON:
888                 cur.clearSelection();
889                 cur.mark() = true;
890                 cur.resetAnchor();
891                 cur.message(from_utf8(N_("Mark on")));
892                 break;
893
894         case LFUN_MARK_TOGGLE:
895                 cur.clearSelection();
896                 if (cur.mark()) {
897                         cur.mark() = false;
898                         cur.message(from_utf8(N_("Mark removed")));
899                 } else {
900                         cur.mark() = true;
901                         cur.message(from_utf8(N_("Mark set")));
902                 }
903                 cur.resetAnchor();
904                 break;
905
906         case LFUN_SCREEN_RECENTER:
907                 center();
908                 break;
909
910         case LFUN_BIBTEX_DATABASE_ADD: {
911                 LCursor tmpcur = cursor_;
912                 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
913                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
914                                                 InsetBase::BIBTEX_CODE);
915                 if (inset) {
916                         if (inset->addDatabase(to_utf8(cmd.argument())))
917                                 buffer_->updateBibfilesCache();
918                 }
919                 break;
920         }
921
922         case LFUN_BIBTEX_DATABASE_DEL: {
923                 LCursor tmpcur = cursor_;
924                 bv_funcs::findInset(tmpcur, InsetBase::BIBTEX_CODE, false);
925                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
926                                                 InsetBase::BIBTEX_CODE);
927                 if (inset) {
928                         if (inset->delDatabase(to_utf8(cmd.argument())))
929                                 buffer_->updateBibfilesCache();
930                 }
931                 break;
932         }
933
934         case LFUN_WORDS_COUNT: {
935                 DocIterator from, to;
936                 if (cur.selection()) {
937                         from = cur.selectionBegin();
938                         to = cur.selectionEnd();
939                 } else {
940                         from = doc_iterator_begin(buffer_->inset());
941                         to = doc_iterator_end(buffer_->inset());
942                 }
943                 int const count = countWords(from, to);
944                 docstring message;
945                 if (count != 1) {
946                         if (cur.selection())
947                                 message = bformat(_("%1$d words in selection."),
948                                           count);
949                                 else
950                                         message = bformat(_("%1$d words in document."),
951                                                           count);
952                 }
953                 else {
954                         if (cur.selection())
955                                 message = _("One word in selection.");
956                         else
957                                 message = _("One word in document.");
958                 }
959
960                 Alert::information(_("Count words"), message);
961         }
962                 break;
963
964         case LFUN_BUFFER_TOGGLE_COMPRESSION:
965                 // turn compression on/off
966                 buffer_->params().compressed = !buffer_->params().compressed;
967                 break;
968
969         case LFUN_NEXT_INSET_TOGGLE: {
970                 // this is the real function we want to invoke
971                 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
972                 // if there is an inset at cursor, see whether it
973                 // wants to toggle.
974                 InsetBase * inset = cur.nextInset();
975                 if (inset && inset->isActive()) {
976                         LCursor tmpcur = cur;
977                         tmpcur.pushLeft(*inset);
978                         inset->dispatch(tmpcur, tmpcmd);
979                         if (tmpcur.result().dispatched()) {
980                                 cur.dispatched();
981                         }
982                 }
983                 // if it did not work, try the underlying inset.
984                 if (!cur.result().dispatched())
985                         cur.dispatch(tmpcmd);
986
987                 if (cur.result().dispatched())
988                         cur.clearSelection();
989
990                 break;
991         }
992
993         default:
994                 return false;
995         }
996
997         return true;
998 }
999
1000
1001 docstring const BufferView::requestSelection()
1002 {
1003         if (!buffer_)
1004                 return docstring();
1005
1006         LCursor & cur = cursor_;
1007
1008         if (!cur.selection()) {
1009                 xsel_cache_.set = false;
1010                 return docstring();
1011         }
1012
1013         if (!xsel_cache_.set ||
1014             cur.top() != xsel_cache_.cursor ||
1015             cur.anchor_.top() != xsel_cache_.anchor)
1016         {
1017                 xsel_cache_.cursor = cur.top();
1018                 xsel_cache_.anchor = cur.anchor_.top();
1019                 xsel_cache_.set = cur.selection();
1020                 return cur.selectionAsString(false);
1021         }
1022         return docstring();
1023 }
1024
1025
1026 void BufferView::clearSelection()
1027 {
1028         if (buffer_) {
1029                 cursor_.clearSelection();
1030                 xsel_cache_.set = false;
1031         }
1032 }
1033
1034
1035 void BufferView::workAreaResize(int width, int height)
1036 {
1037         bool const widthChange = width != width_;
1038         bool const heightChange = height != height_;
1039
1040         // Update from work area
1041         width_ = width;
1042         height_ = height;
1043
1044         if (buffer_ && widthChange) {
1045                 // The WorkArea content needs a resize
1046                 resize();
1047         }
1048
1049         if (widthChange || heightChange)
1050                 update();
1051 }
1052
1053
1054 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1055 {
1056         //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1057
1058         // This is only called for mouse related events including
1059         // LFUN_FILE_OPEN generated by drag-and-drop.
1060         FuncRequest cmd = cmd0;
1061
1062         if (!buffer_)
1063                 return false;
1064
1065         LCursor cur(*this);
1066         cur.push(buffer_->inset());
1067         cur.selection() = cursor_.selection();
1068
1069         // Doesn't go through lyxfunc, so we need to update
1070         // the layout choice etc. ourselves
1071
1072         // E.g. Qt mouse press when no buffer
1073         if (!buffer_)
1074                 return false;
1075
1076         // Either the inset under the cursor or the
1077         // surrounding LyXText will handle this event.
1078
1079         // Build temporary cursor.
1080         cmd.y = min(max(cmd.y, -1), height_);
1081         InsetBase * inset = buffer_->text().editXY(cur, cmd.x, cmd.y);
1082         //lyxerr << BOOST_CURRENT_FUNCTION
1083         //       << " * hit inset at tip: " << inset << endl;
1084         //lyxerr << BOOST_CURRENT_FUNCTION
1085         //       << " * created temp cursor:" << cur << endl;
1086
1087         // Put anchor at the same position.
1088         cur.resetAnchor();
1089
1090         // Try to dispatch to an non-editable inset near this position
1091         // via the temp cursor. If the inset wishes to change the real
1092         // cursor it has to do so explicitly by using
1093         //  cur.bv().cursor() = cur;  (or similar)
1094         if (inset)
1095                 inset->dispatch(cur, cmd);
1096
1097         // Now dispatch to the temporary cursor. If the real cursor should
1098         // be modified, the inset's dispatch has to do so explicitly.
1099         if (!cur.result().dispatched())
1100                 cur.dispatch(cmd);
1101
1102         if (cur.result().dispatched()) {
1103                 // Redraw if requested or necessary.
1104                 if (cur.result().update())
1105                         update(Update::FitCursor | Update::Force);
1106                 else
1107                         update(Update::FitCursor | Update::MultiParSel);
1108         }
1109
1110         return true;
1111 }
1112
1113
1114 void BufferView::scroll(int /*lines*/)
1115 {
1116 //      if (!buffer_)
1117 //              return;
1118 //
1119 //      LyXText const * t = &buffer_->text();
1120 //      int const line_height = defaultRowHeight();
1121 //
1122 //      // The new absolute coordinate
1123 //      int new_top_y = top_y() + lines * line_height;
1124 //
1125 //      // Restrict to a valid value
1126 //      new_top_y = std::min(t->height() - 4 * line_height, new_top_y);
1127 //      new_top_y = std::max(0, new_top_y);
1128 //
1129 //      scrollDocView(new_top_y);
1130 //
1131 //      // Update the scrollbar.
1132 //      workArea_->setScrollbarParams(t->height(), top_y(), defaultRowHeight());}
1133 }
1134
1135
1136 void BufferView::setCursorFromRow(int row)
1137 {
1138         int tmpid = -1;
1139         int tmppos = -1;
1140
1141         buffer_->texrow().getIdFromRow(row, tmpid, tmppos);
1142
1143         if (tmpid == -1)
1144                 buffer_->text().setCursor(cursor_, 0, 0);
1145         else
1146                 buffer_->text().setCursor(cursor_, buffer_->getParFromID(tmpid).pit(), tmppos);
1147 }
1148
1149
1150 void BufferView::gotoLabel(docstring const & label)
1151 {
1152         for (InsetIterator it = inset_iterator_begin(buffer_->inset()); it; ++it) {
1153                 vector<docstring> labels;
1154                 it->getLabelList(*buffer_, labels);
1155                 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1156                         setCursor(it);
1157                         update();
1158                         return;
1159                 }
1160         }
1161 }
1162
1163
1164 LyXText * BufferView::getLyXText()
1165 {
1166         LyXText * text = cursor_.innerText();
1167         BOOST_ASSERT(text);
1168         return text;
1169 }
1170
1171
1172 LyXText const * BufferView::getLyXText() const
1173 {
1174         LyXText const * text = cursor_.innerText();
1175         BOOST_ASSERT(text);
1176         return text;
1177 }
1178
1179
1180 int BufferView::workHeight() const
1181 {
1182         return height_;
1183 }
1184
1185
1186 void BufferView::setCursor(DocIterator const & dit)
1187 {
1188         size_t const n = dit.depth();
1189         for (size_t i = 0; i < n; ++i)
1190                 dit[i].inset().edit(cursor_, true);
1191
1192         cursor_.setCursor(dit);
1193         cursor_.selection() = false;
1194 }
1195
1196
1197 void BufferView::mouseSetCursor(LCursor & cur)
1198 {
1199         BOOST_ASSERT(&cur.bv() == this);
1200
1201         // Has the cursor just left the inset?
1202         bool badcursor = false;
1203         if (&cursor_.inset() != &cur.inset())
1204                 badcursor = cursor_.inset().notifyCursorLeaves(cursor_);
1205
1206         // do the dEPM magic if needed
1207         // FIXME: move this to InsetText::notifyCursorLeaves?
1208         if (!badcursor && cursor_.inTexted())
1209                 cursor_.text()->deleteEmptyParagraphMechanism(cur, cursor_);
1210
1211         cursor_ = cur;
1212         cursor_.clearSelection();
1213         cursor_.setTargetX();
1214         finishUndo();
1215
1216 }
1217
1218
1219 void BufferView::putSelectionAt(DocIterator const & cur,
1220                                 int length, bool backwards)
1221 {
1222         cursor_.clearSelection();
1223
1224         setCursor(cur);
1225
1226         if (length) {
1227                 if (backwards) {
1228                         cursor_.pos() += length;
1229                         cursor_.setSelection(cursor_, -length);
1230                 } else
1231                         cursor_.setSelection(cursor_, length);
1232         }
1233 }
1234
1235
1236 LCursor & BufferView::cursor()
1237 {
1238         return cursor_;
1239 }
1240
1241
1242 LCursor const & BufferView::cursor() const
1243 {
1244         return cursor_;
1245 }
1246
1247
1248 pit_type BufferView::anchor_ref() const
1249 {
1250         return anchor_ref_;
1251 }
1252
1253
1254 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1255 {
1256         return metrics_info_;
1257 }
1258
1259
1260 void BufferView::updateMetrics(bool singlepar)
1261 {
1262         // FIXME (Abdel 19/10/2006):
1263         // There's something fishy in tabular. The coord_cache_ is not
1264         // correctly reconstructed when a character is trying to be inserted.
1265         // Not clearing out the coord_cache_ fixes the crash but there is a
1266         // bad side effect: buffer-begin and buffer-end do not update the screen.
1267         //
1268         // Remove old position cache
1269         coord_cache_.clear();
1270
1271         LyXText & buftext = buffer_->text();
1272         pit_type size = int(buftext.paragraphs().size());
1273
1274         if (anchor_ref_ > int(buftext.paragraphs().size() - 1)) {
1275                 anchor_ref_ = int(buftext.paragraphs().size() - 1);
1276                 offset_ref_ = 0;
1277         }
1278
1279         pit_type const pit = anchor_ref_;
1280         int pit1 = pit;
1281         int pit2 = pit;
1282         size_t const npit = buftext.paragraphs().size();
1283
1284         // Rebreak anchor paragraph. In Single Paragraph mode, rebreak only
1285         // the (main text, not inset!) paragraph containing the cursor.
1286         // (if this paragraph contains insets etc., rebreaking will
1287         // recursively descend)
1288         if (!singlepar || pit == cursor_.bottom().pit())
1289                 buftext.redoParagraph(pit);
1290         int y0 = buftext.getPar(pit).ascent() - offset_ref_;
1291
1292         // Redo paragraphs above anchor if necessary; again, in Single Par
1293         // mode, only if we encounter the (main text) one having the cursor.
1294         int y1 = y0;
1295         while (y1 > 0 && pit1 > 0) {
1296                 y1 -= buftext.getPar(pit1).ascent();
1297                 --pit1;
1298                 if (!singlepar || pit1 == cursor_.bottom().pit())
1299                         buftext.redoParagraph(pit1);
1300                 y1 -= buftext.getPar(pit1).descent();
1301         }
1302
1303
1304         // Take care of ascent of first line
1305         y1 -= buftext.getPar(pit1).ascent();
1306
1307         // Normalize anchor for next time
1308         anchor_ref_ = pit1;
1309         offset_ref_ = -y1;
1310
1311         // Grey at the beginning is ugly
1312         if (pit1 == 0 && y1 > 0) {
1313                 y0 -= y1;
1314                 y1 = 0;
1315                 anchor_ref_ = 0;
1316         }
1317
1318         // Redo paragraphs below the anchor if necessary. Single par mode:
1319         // only the one containing the cursor if encountered.
1320         int y2 = y0;
1321         while (y2 < height_ && pit2 < int(npit) - 1) {
1322                 y2 += buftext.getPar(pit2).descent();
1323                 ++pit2;
1324                 if (!singlepar || pit2 == cursor_.bottom().pit())
1325                         buftext.redoParagraph(pit2);
1326                 y2 += buftext.getPar(pit2).ascent();
1327         }
1328
1329         // Take care of descent of last line
1330         y2 += buftext.getPar(pit2).descent();
1331
1332         // The coordinates of all these paragraphs are correct, cache them
1333         int y = y1;
1334         CoordCache::InnerParPosCache & parPos = coord_cache_.parPos()[&buftext];
1335         for (pit_type pit = pit1; pit <= pit2; ++pit) {
1336                 Paragraph const & par = buftext.getPar(pit);
1337                 y += par.ascent();
1338                 parPos[pit] = Point(0, y);
1339                 if (singlepar && pit == cursor_.bottom().pit()) {
1340                         // In Single Paragraph mode, collect here the
1341                         // y1 and y2 of the (one) paragraph the cursor is in
1342                         y1 = y - par.ascent();
1343                         y2 = y + par.descent();
1344                 }
1345                 y += par.descent();
1346         }
1347
1348         if (singlepar) {
1349                 // collect cursor paragraph iter bounds
1350                 pit1 = cursor_.bottom().pit();
1351                 pit2 = cursor_.bottom().pit();
1352         }
1353
1354         lyxerr[Debug::DEBUG]
1355                 << BOOST_CURRENT_FUNCTION
1356                 << " y1: " << y1
1357                 << " y2: " << y2
1358                 << " pit1: " << pit1
1359                 << " pit2: " << pit2
1360                 << " npit: " << npit
1361                 << " singlepar: " << singlepar
1362                 << "size: " << size
1363                 << endl;
1364
1365         metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2, singlepar, size);
1366
1367         if (lyxerr.debugging(Debug::WORKAREA)) {
1368                 coord_cache_.dump();
1369         }
1370 }
1371
1372
1373 void BufferView::menuInsertLyXFile(string const & filenm)
1374 {
1375         BOOST_ASSERT(cursor_.inTexted());
1376         string filename = filenm;
1377
1378         if (filename.empty()) {
1379                 // Launch a file browser
1380                 // FIXME UNICODE
1381                 string initpath = lyxrc.document_path;
1382
1383                 if (buffer_) {
1384                         string const trypath = buffer_->filePath();
1385                         // If directory is writeable, use this as default.
1386                         if (isDirWriteable(trypath))
1387                                 initpath = trypath;
1388                 }
1389
1390                 // FIXME UNICODE
1391                 FileDialog fileDlg(_("Select LyX document to insert"),
1392                         LFUN_FILE_INSERT,
1393                         make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1394                         make_pair(_("Examples|#E#e"), from_utf8(addPath(package().system_support(), "examples"))));
1395
1396                 FileDialog::Result result =
1397                         fileDlg.open(from_utf8(initpath),
1398                                      FileFilterList(_("LyX Documents (*.lyx)")),
1399                                      docstring());
1400
1401                 if (result.first == FileDialog::Later)
1402                         return;
1403
1404                 // FIXME UNICODE
1405                 filename = to_utf8(result.second);
1406
1407                 // check selected filename
1408                 if (filename.empty()) {
1409                         // emit message signal.
1410                         message(_("Canceled."));
1411                         return;
1412                 }
1413         }
1414
1415         // Get absolute path of file and add ".lyx"
1416         // to the filename if necessary
1417         filename = fileSearch(string(), filename, "lyx");
1418
1419         docstring const disp_fn = makeDisplayPath(filename);
1420         // emit message signal.
1421         message(bformat(_("Inserting document %1$s..."), disp_fn));
1422
1423         docstring res;
1424         Buffer buf("", false);
1425         if (lyx::loadLyXFile(&buf, makeAbsPath(filename))) {
1426                 ErrorList & el = buffer_->errorList("Parse");
1427                 // Copy the inserted document error list into the current buffer one.
1428                 el = buf.errorList("Parse");
1429                 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1430                                              buf.params().textclass, el);
1431                 res = _("Document %1$s inserted.");
1432         } else
1433                 res = _("Could not insert document %1$s");
1434
1435         // emit message signal.
1436         message(bformat(res, disp_fn));
1437         buffer_->errors("Parse");
1438         resize();
1439 }
1440
1441
1442 } // namespace lyx