]> git.lyx.org Git - lyx.git/blob - src/BufferView.cpp
make some bufferview related stuff more local
[lyx.git] / src / BufferView.cpp
1 /**
2  * \file BufferView.cpp
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 "bufferview_funcs.h"
24 #include "callback.h" // added for Dispatch functions
25 #include "CoordCache.h"
26 #include "CutAndPaste.h"
27 #include "debug.h"
28 #include "DispatchResult.h"
29 #include "ErrorList.h"
30 #include "factory.h"
31 #include "FloatList.h"
32 #include "FuncRequest.h"
33 #include "FuncStatus.h"
34 #include "gettext.h"
35 #include "Intl.h"
36 #include "InsetIterator.h"
37 #include "Language.h"
38 #include "LaTeXFeatures.h"
39 #include "LyX.h"
40 #include "lyxfind.h"
41 #include "LyXFunc.h"
42 #include "Layout.h"
43 #include "LyXRC.h"
44 #include "MetricsInfo.h"
45 #include "Paragraph.h"
46 #include "paragraph_funcs.h"
47 #include "ParagraphParameters.h"
48 #include "ParIterator.h"
49 #include "Session.h"
50 #include "TexRow.h"
51 #include "Text.h"
52 #include "TextClass.h"
53 #include "toc.h"
54 #include "Undo.h"
55 #include "VSpace.h"
56 #include "WordLangTuple.h"
57
58 #include "insets/InsetBibtex.h"
59 #include "insets/InsetCommand.h" // ChangeRefs
60 #include "insets/InsetRef.h"
61 #include "insets/InsetText.h"
62
63 #include "frontends/alert.h"
64 #include "frontends/FileDialog.h"
65 #include "frontends/FontMetrics.h"
66 #include "frontends/Painter.h"
67 #include "frontends/Selection.h"
68
69 #include "graphics/Previews.h"
70
71 #include "support/convert.h"
72 #include "support/FileFilterList.h"
73 #include "support/filetools.h"
74 #include "support/Package.h"
75 #include "support/types.h"
76
77 #include <boost/bind.hpp>
78 #include <boost/current_function.hpp>
79
80 #include <functional>
81 #include <vector>
82
83 using std::distance;
84 using std::endl;
85 using std::istringstream;
86 using std::make_pair;
87 using std::min;
88 using std::max;
89 using std::mem_fun_ref;
90 using std::string;
91 using std::vector;
92
93
94 namespace lyx {
95
96 using support::addPath;
97 using support::bformat;
98 using support::FileFilterList;
99 using support::FileName;
100 using support::fileSearch;
101 using support::isDirWriteable;
102 using support::isFileReadable;
103 using support::makeDisplayPath;
104 using support::package;
105
106 namespace Alert = frontend::Alert;
107
108 namespace {
109
110 /// Return an inset of this class if it exists at the current cursor position
111 template <class T>
112 T * getInsetByCode(Cursor const & cur, Inset::Code code)
113 {
114         DocIterator it = cur;
115         Inset * inset = it.nextInset();
116         if (inset && inset->lyxCode() == code)
117                 return static_cast<T*>(inset);
118         return 0;
119 }
120
121
122 bool findInset(DocIterator & dit, vector<Inset_code> const & codes,
123         bool same_content);
124
125 bool findNextInset(DocIterator & dit, vector<Inset_code> const & codes,
126         string const & contents)
127 {
128         DocIterator tmpdit = dit;
129
130         while (tmpdit) {
131                 Inset const * inset = tmpdit.nextInset();
132                 if (inset
133                     && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()
134                     && (contents.empty() ||
135                     static_cast<InsetCommand const *>(inset)->getContents() == contents)) {
136                         dit = tmpdit;
137                         return true;
138                 }
139                 tmpdit.forwardInset();
140         }
141
142         return false;
143 }
144
145
146 /// Looks for next inset with one of the the given code
147 bool findInset(DocIterator & dit, vector<Inset_code> const & codes,
148         bool same_content)
149 {
150         string contents;
151         DocIterator tmpdit = dit;
152         tmpdit.forwardInset();
153         if (!tmpdit)
154                 return false;
155
156         if (same_content) {
157                 Inset const * inset = tmpdit.nextInset();
158                 if (inset
159                     && find(codes.begin(), codes.end(), inset->lyxCode()) != codes.end()) {
160                         contents = static_cast<InsetCommand const *>(inset)->getContents();
161                 }
162         }
163
164         if (!findNextInset(tmpdit, codes, contents)) {
165                 if (dit.depth() != 1 || dit.pit() != 0 || dit.pos() != 0) {
166                         tmpdit  = doc_iterator_begin(tmpdit.bottom().inset());
167                         if (!findNextInset(tmpdit, codes, contents))
168                                 return false;
169                 } else
170                         return false;
171         }
172
173         dit = tmpdit;
174         return true;
175 }
176
177
178 /// Looks for next inset with the given code
179 void findInset(DocIterator & dit, Inset_code code, bool same_content)
180 {
181         findInset(dit, vector<Inset_code>(1, code), same_content);
182 }
183
184
185 /// Moves cursor to the next inset with one of the given codes.
186 void gotoInset(BufferView * bv, vector<Inset_code> const & codes,
187                bool same_content)
188 {
189         Cursor tmpcur = bv->cursor();
190         if (!findInset(tmpcur, codes, same_content)) {
191                 bv->cursor().message(_("No more insets"));
192                 return;
193         }
194
195         tmpcur.clearSelection();
196         bv->setCursor(tmpcur);
197 }
198
199
200 /// Moves cursor to the next inset with given code.
201 void gotoInset(BufferView * bv, Inset_code code, bool same_content)
202 {
203         gotoInset(bv, vector<Inset_code>(1, code), same_content);
204 }
205
206
207 } // anon namespace
208
209
210 BufferView::BufferView(Buffer & buf)
211         : width_(0), height_(0), buffer_(buf), wh_(0),
212           cursor_(*this),
213           multiparsel_cache_(false), anchor_ref_(0), offset_ref_(0),
214           need_centering_(false), intl_(new Intl), last_inset_(0)
215 {
216         xsel_cache_.set = false;
217         intl_->initKeyMapper(lyxrc.use_kbmap);
218
219         cursor_.push(buffer_.inset());
220         cursor_.resetAnchor();
221         cursor_.setCurrentFont();
222
223         if (graphics::Previews::status() != LyXRC::PREVIEW_OFF)
224                 graphics::Previews::get().generateBufferPreviews(buffer_);
225 }
226
227
228 BufferView::~BufferView()
229 {
230         // current buffer is going to be switched-off, save cursor pos
231         // Ideally, the whole cursor stack should be saved, but session
232         // currently can only handle bottom (whole document) level pit and pos.
233         // That is to say, if a cursor is in a nested inset, it will be
234         // restore to the left of the top level inset.
235         LyX::ref().session().lastFilePos().save(
236                 support::FileName(buffer_.fileName()),
237                 boost::tie(cursor_.bottom().pit(), cursor_.bottom().pos()) );
238 }
239
240
241 Buffer & BufferView::buffer()
242 {
243         return buffer_;
244 }
245
246
247 Buffer const & BufferView::buffer() const
248 {
249         return buffer_;
250 }
251
252
253 bool BufferView::fitCursor()
254 {
255         if (bv_funcs::status(this, cursor_) == bv_funcs::CUR_INSIDE) {
256                 frontend::FontMetrics const & fm =
257                         theFontMetrics(cursor_.getFont());
258                 int const asc = fm.maxAscent();
259                 int const des = fm.maxDescent();
260                 Point const p = bv_funcs::getPos(*this, cursor_, cursor_.boundary());
261                 if (p.y_ - asc >= 0 && p.y_ + des < height_)
262                         return false;
263         }
264         center();
265         return true;
266 }
267
268
269 bool BufferView::multiParSel()
270 {
271         if (!cursor_.selection())
272                 return false;
273         bool ret = multiparsel_cache_;
274         multiparsel_cache_ = cursor_.selBegin().pit() != cursor_.selEnd().pit();
275         // Either this, or previous selection spans paragraphs
276         return ret || multiparsel_cache_;
277 }
278
279
280 bool BufferView::update(Update::flags flags)
281 {
282         // last_inset_ points to the last visited inset. This pointer may become
283         // invalid because of keyboard editing. Since all such operations
284         // causes screen update(), I reset last_inset_ to avoid such a problem.
285         last_inset_ = 0;
286         // This is close to a hot-path.
287         LYXERR(Debug::DEBUG)
288                 << BOOST_CURRENT_FUNCTION
289                 << "[fitcursor = " << (flags & Update::FitCursor)
290                 << ", forceupdate = " << (flags & Update::Force)
291                 << ", singlepar = " << (flags & Update::SinglePar)
292                 << "]  buffer: " << &buffer_ << endl;
293
294         // Update macro store
295         if (!(cursor().inMathed() && cursor().inMacroMode()))
296                 buffer_.buildMacros();
297
298         // Now do the first drawing step if needed. This consists on updating
299         // the CoordCache in updateMetrics().
300         // The second drawing step is done in WorkArea::redraw() if needed.
301
302         // Case when no explicit update is requested.
303         if (!flags) {
304                 // no need to redraw anything.
305                 metrics_info_.update_strategy = NoScreenUpdate;
306                 return false;
307         }
308
309         if (flags == Update::Decoration) {
310                 metrics_info_.update_strategy = DecorationUpdate;
311                 return true;
312         }
313
314         if (flags == Update::FitCursor
315                 || flags == (Update::Decoration | Update::FitCursor)) {
316                 bool const fit_cursor = fitCursor();
317                 // tell the frontend to update the screen if needed.
318                 if (fit_cursor) {
319                         updateMetrics(false);
320                         return true;
321                 }
322                 if (flags & Update::Decoration) {
323                         metrics_info_.update_strategy = DecorationUpdate;
324                         return true;
325                 }
326                 // no screen update is needed.
327                 metrics_info_.update_strategy = NoScreenUpdate;
328                 return false;
329         }
330
331         bool full_metrics = flags & Update::Force;
332         if (flags & Update::MultiParSel)
333                 full_metrics |= multiParSel();
334
335         bool const single_par = !full_metrics;
336         updateMetrics(single_par);
337
338         if (flags & Update::FitCursor) {
339                 //FIXME: updateMetrics() does not update paragraph position
340                 // This is done at draw() time. So we need a redraw!
341                 buffer_.changed();
342                 if (fitCursor())
343                         updateMetrics(false);
344                 else
345                         // The screen has already been updated thanks to the
346                         // 'buffer_.changed()' call three line above. So no need
347                         // to redraw again.
348                         return false;
349         }
350
351         // tell the frontend to update the screen.
352         return true;
353 }
354
355
356 void BufferView::updateScrollbar()
357 {
358         Text & t = buffer_.text();
359         TextMetrics & tm = text_metrics_[&t];
360
361         int const parsize = int(t.paragraphs().size() - 1);
362         if (anchor_ref_ >  parsize)  {
363                 anchor_ref_ = parsize;
364                 offset_ref_ = 0;
365         }
366
367         LYXERR(Debug::GUI)
368                 << BOOST_CURRENT_FUNCTION
369                 << " Updating scrollbar: height: " << t.paragraphs().size()
370                 << " curr par: " << cursor_.bottom().pit()
371                 << " default height " << defaultRowHeight() << endl;
372
373         // It would be better to fix the scrollbar to understand
374         // values in [0..1] and divide everything by wh
375
376         // estimated average paragraph height:
377         if (wh_ == 0)
378                 wh_ = height_ / 4;
379
380         int h = tm.parMetrics(anchor_ref_).height();
381
382         // Normalize anchor/offset (MV):
383         while (offset_ref_ > h && anchor_ref_ < parsize) {
384                 anchor_ref_++;
385                 offset_ref_ -= h;
386                 h = tm.parMetrics(anchor_ref_).height();
387         }
388         // Look at paragraph heights on-screen
389         int sumh = 0;
390         int nh = 0;
391         for (pit_type pit = anchor_ref_; pit <= parsize; ++pit) {
392                 if (sumh > height_)
393                         break;
394                 int const h2 = tm.parMetrics(pit).height();
395                 sumh += h2;
396                 nh++;
397         }
398
399         BOOST_ASSERT(nh);
400         int const hav = sumh / nh;
401         // More realistic average paragraph height
402         if (hav > wh_)
403                 wh_ = hav;
404
405         BOOST_ASSERT(h);
406         scrollbarParameters_.height = (parsize + 1) * wh_;
407         scrollbarParameters_.position = anchor_ref_ * wh_ + int(offset_ref_ * wh_ / float(h));
408         scrollbarParameters_.lineScrollHeight = int(wh_ * defaultRowHeight() / float(h));
409 }
410
411
412 ScrollbarParameters const & BufferView::scrollbarParameters() const
413 {
414         return scrollbarParameters_;
415 }
416
417
418 void BufferView::scrollDocView(int value)
419 {
420         LYXERR(Debug::GUI) << BOOST_CURRENT_FUNCTION
421                            << "[ value = " << value << "]" << endl;
422
423         Text & t = buffer_.text();
424         TextMetrics & tm = text_metrics_[&t];
425
426         float const bar = value / float(wh_ * t.paragraphs().size());
427
428         anchor_ref_ = int(bar * t.paragraphs().size());
429         if (anchor_ref_ >  int(t.paragraphs().size()) - 1)
430                 anchor_ref_ = int(t.paragraphs().size()) - 1;
431
432         tm.redoParagraph(anchor_ref_);
433         int const h = tm.parMetrics(anchor_ref_).height();
434         offset_ref_ = int((bar * t.paragraphs().size() - anchor_ref_) * h);
435         updateMetrics(false);
436         buffer_.changed();
437 }
438
439
440 void BufferView::setCursorFromScrollbar()
441 {
442         TextMetrics & tm = text_metrics_[&buffer_.text()];
443
444         int const height = 2 * defaultRowHeight();
445         int const first = height;
446         int const last = height_ - height;
447         Cursor & cur = cursor_;
448
449         bv_funcs::CurStatus st = bv_funcs::status(this, cur);
450
451         switch (st) {
452         case bv_funcs::CUR_ABOVE:
453                 // We reset the cursor because bv_funcs::status() does not
454                 // work when the cursor is within mathed.
455                 cur.reset(buffer_.inset());
456                 tm.setCursorFromCoordinates(cur, 0, first);
457                 cur.clearSelection();
458                 break;
459         case bv_funcs::CUR_BELOW:
460                 // We reset the cursor because bv_funcs::status() does not
461                 // work when the cursor is within mathed.
462                 cur.reset(buffer_.inset());
463                 tm.setCursorFromCoordinates(cur, 0, last);
464                 cur.clearSelection();
465                 break;
466         case bv_funcs::CUR_INSIDE:
467                 int const y = bv_funcs::getPos(*this, cur, cur.boundary()).y_;
468                 int const newy = min(last, max(y, first));
469                 if (y != newy) {
470                         cur.reset(buffer_.inset());
471                         tm.setCursorFromCoordinates(cur, 0, newy);
472                 }
473         }
474 }
475
476
477 Change const BufferView::getCurrentChange() const
478 {
479         if (!cursor_.selection())
480                 return Change(Change::UNCHANGED);
481
482         DocIterator dit = cursor_.selectionBegin();
483         return dit.paragraph().lookupChange(dit.pos());
484 }
485
486
487 void BufferView::saveBookmark(unsigned int idx)
488 {
489         // tenatively save bookmark, id and pos will be used to
490         // acturately locate a bookmark in a 'live' lyx session.
491         // pit and pos will be updated with bottom level pit/pos
492         // when lyx exits.
493         LyX::ref().session().bookmarks().save(
494                 FileName(buffer_.fileName()),
495                 cursor_.bottom().pit(),
496                 cursor_.bottom().pos(),
497                 cursor_.paragraph().id(),
498                 cursor_.pos(),
499                 idx
500         );
501         if (idx)
502                 // emit message signal.
503                 message(_("Save bookmark"));
504 }
505
506
507 bool BufferView::moveToPosition(pit_type bottom_pit, pos_type bottom_pos,
508         int top_id, pos_type top_pos)
509 {
510         bool success = false;
511         DocIterator doc_it;
512
513         cursor_.clearSelection();
514
515         // if a valid par_id is given, try it first
516         // This is the case for a 'live' bookmark when unique paragraph ID
517         // is used to track bookmarks.
518         if (top_id > 0) {
519                 ParIterator par = buffer_.getParFromID(top_id);
520                 if (par != buffer_.par_iterator_end()) {
521                         doc_it = makeDocIterator(par, min(par->size(), top_pos));
522                         // Some slices of the iterator may not be
523                         // reachable (e.g. closed collapsable inset)
524                         // so the dociterator may need to be
525                         // shortened. Otherwise, setCursor may crash
526                         // lyx when the cursor can not be set to these
527                         // insets.
528                         size_t const n = doc_it.depth();
529                         for (size_t i = 0; i < n; ++i)
530                                 if (doc_it[i].inset().editable() != Inset::HIGHLY_EDITABLE) {
531                                         doc_it.resize(i);
532                                         break;
533                                 }
534                         success = true;
535                 }
536         }
537
538         // if top_id == 0, or searching through top_id failed
539         // This is the case for a 'restored' bookmark when only bottom
540         // (document level) pit was saved. Because of this, bookmark
541         // restoration is inaccurate. If a bookmark was within an inset,
542         // it will be restored to the left of the outmost inset that contains
543         // the bookmark.
544         if (static_cast<size_t>(bottom_pit) < buffer_.paragraphs().size()) {
545                 doc_it = doc_iterator_begin(buffer_.inset());
546                 doc_it.pit() = bottom_pit;
547                 doc_it.pos() = min(bottom_pos, doc_it.paragraph().size());
548                 success = true;
549         }
550
551         if (success) {
552                 // Note: only bottom (document) level pit is set.
553                 setCursor(doc_it);
554                 // set the current font.
555                 cursor_.setCurrentFont();
556                 // center the screen on this new position.
557                 center();
558         }
559
560         return success;
561 }
562
563
564 void BufferView::translateAndInsert(char_type c, Text * t, Cursor & cur)
565 {
566         if (lyxrc.rtl_support) {
567                 if (cursor_.real_current_font.isRightToLeft()) {
568                         if (intl_->keymap == Intl::PRIMARY)
569                                 intl_->keyMapSec();
570                 } else {
571                         if (intl_->keymap == Intl::SECONDARY)
572                                 intl_->keyMapPrim();
573                 }
574         }
575
576         intl_->getTransManager().translateAndInsert(c, t, cur);
577 }
578
579
580 int BufferView::workWidth() const
581 {
582         return width_;
583 }
584
585
586 void BufferView::updateOffsetRef()
587 {
588         // No need to update offset_ref_ in this case.
589         if (!need_centering_)
590                 return;
591
592         // We are not properly started yet, delay until resizing is
593         // done.
594         if (height_ == 0)
595                 return;
596
597         CursorSlice & bot = cursor_.bottom();
598         TextMetrics & tm = text_metrics_[bot.text()];
599         ParagraphMetrics const & pm = tm.parMetrics(bot.pit());
600         Point p = bv_funcs::coordOffset(*this, cursor_, cursor_.boundary());
601         offset_ref_ = p.y_ + pm.ascent() - height_ / 2;
602
603         need_centering_ = false;
604 }
605
606
607 void BufferView::center()
608 {
609         anchor_ref_ = cursor_.bottom().pit();
610         need_centering_ = true;
611 }
612
613
614 FuncStatus BufferView::getStatus(FuncRequest const & cmd)
615 {
616         FuncStatus flag;
617
618         Cursor & cur = cursor_;
619
620         switch (cmd.action) {
621
622         case LFUN_UNDO:
623                 flag.enabled(!buffer_.undostack().empty());
624                 break;
625         case LFUN_REDO:
626                 flag.enabled(!buffer_.redostack().empty());
627                 break;
628         case LFUN_FILE_INSERT:
629         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
630         case LFUN_FILE_INSERT_PLAINTEXT:
631         case LFUN_BOOKMARK_SAVE:
632                 // FIXME: Actually, these LFUNS should be moved to Text
633                 flag.enabled(cur.inTexted());
634                 break;
635         case LFUN_FONT_STATE:
636         case LFUN_LABEL_INSERT:
637         case LFUN_PARAGRAPH_GOTO:
638         // FIXME handle non-trivially
639         case LFUN_OUTLINE_UP:
640         case LFUN_OUTLINE_DOWN:
641         case LFUN_OUTLINE_IN:
642         case LFUN_OUTLINE_OUT:
643         case LFUN_NOTE_NEXT:
644         case LFUN_REFERENCE_NEXT:
645         case LFUN_WORD_FIND:
646         case LFUN_WORD_REPLACE:
647         case LFUN_MARK_OFF:
648         case LFUN_MARK_ON:
649         case LFUN_MARK_TOGGLE:
650         case LFUN_SCREEN_RECENTER:
651         case LFUN_BIBTEX_DATABASE_ADD:
652         case LFUN_BIBTEX_DATABASE_DEL:
653         case LFUN_WORDS_COUNT:
654         case LFUN_NEXT_INSET_TOGGLE:
655                 flag.enabled(true);
656                 break;
657
658         case LFUN_LABEL_GOTO: {
659                 flag.enabled(!cmd.argument().empty()
660                     || getInsetByCode<InsetRef>(cur, Inset::REF_CODE));
661                 break;
662         }
663
664         case LFUN_CHANGES_TRACK:
665                 flag.enabled(true);
666                 flag.setOnOff(buffer_.params().trackChanges);
667                 break;
668
669         case LFUN_CHANGES_OUTPUT:
670                 flag.enabled(true);
671                 flag.setOnOff(buffer_.params().outputChanges);
672                 break;
673
674         case LFUN_CHANGES_MERGE:
675         case LFUN_CHANGE_NEXT:
676         case LFUN_ALL_CHANGES_ACCEPT:
677         case LFUN_ALL_CHANGES_REJECT:
678                 // TODO: context-sensitive enabling of LFUNs
679                 // In principle, these command should only be enabled if there
680                 // is a change in the document. However, without proper
681                 // optimizations, this will inevitably result in poor performance.
682                 flag.enabled(true);
683                 break;
684
685         case LFUN_BUFFER_TOGGLE_COMPRESSION: {
686                 flag.setOnOff(buffer_.params().compressed);
687                 break;
688         }
689
690         case LFUN_SCREEN_UP:
691         case LFUN_SCREEN_DOWN:
692                 flag.enabled(true);
693                 break;
694
695         // FIXME: LFUN_SCREEN_DOWN_SELECT should be removed from
696         // everywhere else before this can enabled:
697         case LFUN_SCREEN_UP_SELECT:
698         case LFUN_SCREEN_DOWN_SELECT:
699                 flag.enabled(false);
700                 break;
701
702         default:
703                 flag.enabled(false);
704         }
705
706         return flag;
707 }
708
709
710 Update::flags BufferView::dispatch(FuncRequest const & cmd)
711 {
712         //lyxerr << BOOST_CURRENT_FUNCTION
713         //       << [ cmd = " << cmd << "]" << endl;
714
715         // Make sure that the cached BufferView is correct.
716         LYXERR(Debug::ACTION) << BOOST_CURRENT_FUNCTION
717                 << " action[" << cmd.action << ']'
718                 << " arg[" << to_utf8(cmd.argument()) << ']'
719                 << " x[" << cmd.x << ']'
720                 << " y[" << cmd.y << ']'
721                 << " button[" << cmd.button() << ']'
722                 << endl;
723
724         Cursor & cur = cursor_;
725         // Default Update flags.
726         Update::flags updateFlags = Update::Force | Update::FitCursor;
727
728         switch (cmd.action) {
729
730         case LFUN_UNDO:
731                 cur.message(_("Undo"));
732                 cur.clearSelection();
733                 if (!textUndo(*this)) {
734                         cur.message(_("No further undo information"));
735                         updateFlags = Update::None;
736                 }
737                 break;
738
739         case LFUN_REDO:
740                 cur.message(_("Redo"));
741                 cur.clearSelection();
742                 if (!textRedo(*this)) {
743                         cur.message(_("No further redo information"));
744                         updateFlags = Update::None;
745                 }
746                 break;
747
748         case LFUN_FILE_INSERT:
749                 // FIXME UNICODE
750                 menuInsertLyXFile(to_utf8(cmd.argument()));
751                 break;
752
753         case LFUN_FILE_INSERT_PLAINTEXT_PARA:
754                 // FIXME UNICODE
755                 insertPlaintextFile(this, to_utf8(cmd.argument()), true);
756                 break;
757
758         case LFUN_FILE_INSERT_PLAINTEXT:
759                 // FIXME UNICODE
760                 insertPlaintextFile(this, to_utf8(cmd.argument()), false);
761                 break;
762
763         case LFUN_FONT_STATE:
764                 cur.message(cur.currentState());
765                 break;
766
767         case LFUN_BOOKMARK_SAVE:
768                 saveBookmark(convert<unsigned int>(to_utf8(cmd.argument())));
769                 break;
770
771         case LFUN_LABEL_GOTO: {
772                 docstring label = cmd.argument();
773                 if (label.empty()) {
774                         InsetRef * inset =
775                                 getInsetByCode<InsetRef>(cursor_,
776                                                          Inset::REF_CODE);
777                         if (inset) {
778                                 label = inset->getParam("reference");
779                                 // persistent=false: use temp_bookmark
780                                 saveBookmark(0);
781                         }
782                 }
783
784                 if (!label.empty())
785                         gotoLabel(label);
786                 break;
787         }
788
789         case LFUN_PARAGRAPH_GOTO: {
790                 int const id = convert<int>(to_utf8(cmd.argument()));
791                 int i = 0;
792                 for (Buffer * b = &buffer_; i == 0 || b != &buffer_;
793                         b = theBufferList().next(b)) {
794
795                         ParIterator par = b->getParFromID(id);
796                         if (par == b->par_iterator_end()) {
797                                 LYXERR(Debug::INFO)
798                                         << "No matching paragraph found! ["
799                                         << id << "]." << endl;
800                         } else {
801                                 LYXERR(Debug::INFO)
802                                         << "Paragraph " << par->id()
803                                         << " found in buffer `"
804                                         << b->fileName() << "'." << endl;
805
806                                 if (b == &buffer_) {
807                                         // Set the cursor
808                                         setCursor(makeDocIterator(par, 0));
809                                 } else {
810                                         // Switch to other buffer view and resend cmd
811                                         theLyXFunc().dispatch(FuncRequest(
812                                                 LFUN_BUFFER_SWITCH, b->fileName()));
813                                         theLyXFunc().dispatch(cmd);
814                                         updateFlags = Update::None;
815                                 }
816                                 break;
817                         }
818                         ++i;
819                 }
820                 break;
821         }
822
823         case LFUN_OUTLINE_UP:
824                 toc::outline(toc::Up, cursor_);
825                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
826                 updateLabels(buffer_);
827                 break;
828         case LFUN_OUTLINE_DOWN:
829                 toc::outline(toc::Down, cursor_);
830                 cursor_.text()->setCursor(cursor_, cursor_.pit(), 0);
831                 updateLabels(buffer_);
832                 break;
833         case LFUN_OUTLINE_IN:
834                 toc::outline(toc::In, cursor_);
835                 updateLabels(buffer_);
836                 break;
837         case LFUN_OUTLINE_OUT:
838                 toc::outline(toc::Out, cursor_);
839                 updateLabels(buffer_);
840                 break;
841
842         case LFUN_NOTE_NEXT:
843                 gotoInset(this, Inset::NOTE_CODE, false);
844                 break;
845
846         case LFUN_REFERENCE_NEXT: {
847                 vector<Inset_code> tmp;
848                 tmp.push_back(Inset::LABEL_CODE);
849                 tmp.push_back(Inset::REF_CODE);
850                 gotoInset(this, tmp, true);
851                 break;
852         }
853
854         case LFUN_CHANGES_TRACK:
855                 buffer_.params().trackChanges = !buffer_.params().trackChanges;
856                 break;
857
858         case LFUN_CHANGES_OUTPUT:
859                 buffer_.params().outputChanges = !buffer_.params().outputChanges;
860                 if (buffer_.params().outputChanges) {
861                         bool dvipost    = LaTeXFeatures::isAvailable("dvipost");
862                         bool xcolorsoul = LaTeXFeatures::isAvailable("soul") &&
863                                           LaTeXFeatures::isAvailable("xcolor");
864
865                         if (!dvipost && !xcolorsoul) {
866                                 Alert::warning(_("Changes not shown in LaTeX output"),
867                                                _("Changes will not be highlighted in LaTeX output, "
868                                                  "because neither dvipost nor xcolor/soul are installed.\n"
869                                                  "Please install these packages or redefine "
870                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
871                         } else if (!xcolorsoul) {
872                                 Alert::warning(_("Changes not shown in LaTeX output"),
873                                                _("Changes will not be highlighted in LaTeX output "
874                                                  "when using pdflatex, because xcolor and soul are not installed.\n"
875                                                  "Please install both packages or redefine "
876                                                  "\\lyxadded and \\lyxdeleted in the LaTeX preamble."));
877                         }
878                 }
879                 break;
880
881         case LFUN_CHANGE_NEXT:
882                 findNextChange(this);
883                 break;
884
885         case LFUN_CHANGES_MERGE:
886                 if (findNextChange(this))
887                         showDialog("changes");
888                 break;
889
890         case LFUN_ALL_CHANGES_ACCEPT:
891                 // select complete document
892                 cursor_.reset(buffer_.inset());
893                 cursor_.selHandle(true);
894                 buffer_.text().cursorBottom(cursor_);
895                 // accept everything in a single step to support atomic undo
896                 buffer_.text().acceptOrRejectChanges(cursor_, Text::ACCEPT);
897                 break;
898
899         case LFUN_ALL_CHANGES_REJECT:
900                 // select complete document
901                 cursor_.reset(buffer_.inset());
902                 cursor_.selHandle(true);
903                 buffer_.text().cursorBottom(cursor_);
904                 // reject everything in a single step to support atomic undo
905                 // Note: reject does not work recursively; the user may have to repeat the operation
906                 buffer_.text().acceptOrRejectChanges(cursor_, Text::REJECT);
907                 break;
908
909         case LFUN_WORD_FIND:
910                 find(this, cmd);
911                 break;
912
913         case LFUN_WORD_REPLACE: {
914                 bool has_deleted = false;
915                 if (cur.selection()) {
916                         DocIterator beg = cur.selectionBegin();
917                         DocIterator end = cur.selectionEnd();
918                         if (beg.pit() == end.pit()) {
919                                 for (pos_type p = beg.pos() ; p < end.pos() ; ++p) {
920                                         if (cur.paragraph().isDeleted(p))
921                                                 has_deleted = true;
922                                 }
923                         }
924                 }
925                 replace(this, cmd, has_deleted);
926                 break;
927         }
928
929         case LFUN_MARK_OFF:
930                 cur.clearSelection();
931                 cur.resetAnchor();
932                 cur.message(from_utf8(N_("Mark off")));
933                 break;
934
935         case LFUN_MARK_ON:
936                 cur.clearSelection();
937                 cur.mark() = true;
938                 cur.resetAnchor();
939                 cur.message(from_utf8(N_("Mark on")));
940                 break;
941
942         case LFUN_MARK_TOGGLE:
943                 cur.clearSelection();
944                 if (cur.mark()) {
945                         cur.mark() = false;
946                         cur.message(from_utf8(N_("Mark removed")));
947                 } else {
948                         cur.mark() = true;
949                         cur.message(from_utf8(N_("Mark set")));
950                 }
951                 cur.resetAnchor();
952                 break;
953
954         case LFUN_SCREEN_RECENTER:
955                 center();
956                 break;
957
958         case LFUN_BIBTEX_DATABASE_ADD: {
959                 Cursor tmpcur = cursor_;
960                 findInset(tmpcur, Inset::BIBTEX_CODE, false);
961                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
962                                                 Inset::BIBTEX_CODE);
963                 if (inset) {
964                         if (inset->addDatabase(to_utf8(cmd.argument())))
965                                 buffer_.updateBibfilesCache();
966                 }
967                 break;
968         }
969
970         case LFUN_BIBTEX_DATABASE_DEL: {
971                 Cursor tmpcur = cursor_;
972                 findInset(tmpcur, Inset::BIBTEX_CODE, false);
973                 InsetBibtex * inset = getInsetByCode<InsetBibtex>(tmpcur,
974                                                 Inset::BIBTEX_CODE);
975                 if (inset) {
976                         if (inset->delDatabase(to_utf8(cmd.argument())))
977                                 buffer_.updateBibfilesCache();
978                 }
979                 break;
980         }
981
982         case LFUN_WORDS_COUNT: {
983                 DocIterator from, to;
984                 if (cur.selection()) {
985                         from = cur.selectionBegin();
986                         to = cur.selectionEnd();
987                 } else {
988                         from = doc_iterator_begin(buffer_.inset());
989                         to = doc_iterator_end(buffer_.inset());
990                 }
991                 int const count = countWords(from, to);
992                 docstring message;
993                 if (count != 1) {
994                         if (cur.selection())
995                                 message = bformat(_("%1$d words in selection."),
996                                           count);
997                                 else
998                                         message = bformat(_("%1$d words in document."),
999                                                           count);
1000                 }
1001                 else {
1002                         if (cur.selection())
1003                                 message = _("One word in selection.");
1004                         else
1005                                 message = _("One word in document.");
1006                 }
1007
1008                 Alert::information(_("Count words"), message);
1009         }
1010                 break;
1011
1012         case LFUN_BUFFER_TOGGLE_COMPRESSION:
1013                 // turn compression on/off
1014                 buffer_.params().compressed = !buffer_.params().compressed;
1015                 break;
1016
1017         case LFUN_NEXT_INSET_TOGGLE: {
1018                 // this is the real function we want to invoke
1019                 FuncRequest tmpcmd = FuncRequest(LFUN_INSET_TOGGLE, cmd.origin);
1020                 // if there is an inset at cursor, see whether it
1021                 // wants to toggle.
1022                 Inset * inset = cur.nextInset();
1023                 if (inset) {
1024                         if (inset->isActive()) {
1025                                 Cursor tmpcur = cur;
1026                                 tmpcur.pushLeft(*inset);
1027                                 inset->dispatch(tmpcur, tmpcmd);
1028                                 if (tmpcur.result().dispatched()) {
1029                                         cur.dispatched();
1030                                 }
1031                         } else if (inset->editable() == Inset::IS_EDITABLE) {
1032                                 inset->edit(cur, true);
1033                         }
1034                 }
1035                 // if it did not work, try the underlying inset.
1036                 if (!cur.result().dispatched())
1037                         cur.dispatch(tmpcmd);
1038
1039                 if (cur.result().dispatched())
1040                         cur.clearSelection();
1041
1042                 break;
1043         }
1044
1045         case LFUN_SCREEN_UP:
1046         case LFUN_SCREEN_DOWN: {
1047                 Point p = bv_funcs::getPos(*this, cur, cur.boundary());
1048                 if (p.y_ < 0 || p.y_ > height_) {
1049                         // The cursor is off-screen so recenter before proceeding.
1050                         center();
1051                         updateMetrics(false);
1052                         //FIXME: updateMetrics() does not update paragraph position
1053                         // This is done at draw() time. So we need a redraw!
1054                         buffer_.changed();
1055                         p = bv_funcs::getPos(*this, cur, cur.boundary());
1056                 }
1057                 scroll(cmd.action == LFUN_SCREEN_UP? - height_ : height_);
1058                 cur.reset(buffer_.inset());
1059                 text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1060                 //FIXME: what to do with cur.x_target()?
1061                 finishUndo();
1062                 // The metrics are already up to date. see scroll()
1063                 updateFlags = Update::None;
1064                 break;
1065         }
1066
1067         case LFUN_SCREEN_UP_SELECT:
1068         case LFUN_SCREEN_DOWN_SELECT: {
1069                 cur.selHandle(true);
1070                 size_t initial_depth = cur.depth();
1071                 Point const p = bv_funcs::getPos(*this, cur, cur.boundary());
1072                 scroll(cmd.action == LFUN_SCREEN_UP_SELECT? - height_ : height_);
1073                 // FIXME: We need to verify if the cursor stayed within an inset...
1074                 //cur.reset(buffer_.inset());
1075                 text_metrics_[&buffer_.text()].editXY(cur, p.x_, p.y_);
1076                 finishUndo();
1077                 while (cur.depth() > initial_depth) {
1078                         cur.forwardInset();
1079                 }
1080                 // FIXME: we need to do a redraw again because of the selection
1081                 buffer_.changed();
1082                 updateFlags = Update::Force | Update::FitCursor;
1083                 break;
1084         }
1085
1086         default:
1087                 updateFlags = Update::None;
1088         }
1089
1090         return updateFlags;
1091 }
1092
1093
1094 docstring const BufferView::requestSelection()
1095 {
1096         Cursor & cur = cursor_;
1097
1098         if (!cur.selection()) {
1099                 xsel_cache_.set = false;
1100                 return docstring();
1101         }
1102
1103         if (!xsel_cache_.set ||
1104             cur.top() != xsel_cache_.cursor ||
1105             cur.anchor_.top() != xsel_cache_.anchor)
1106         {
1107                 xsel_cache_.cursor = cur.top();
1108                 xsel_cache_.anchor = cur.anchor_.top();
1109                 xsel_cache_.set = cur.selection();
1110                 return cur.selectionAsString(false);
1111         }
1112         return docstring();
1113 }
1114
1115
1116 void BufferView::clearSelection()
1117 {
1118         cursor_.clearSelection();
1119         // Clear the selection buffer. Otherwise a subsequent
1120         // middle-mouse-button paste would use the selection buffer,
1121         // not the more current external selection.
1122         cap::clearSelection();
1123         xsel_cache_.set = false;
1124         // The buffer did not really change, but this causes the
1125         // redraw we need because we cleared the selection above.
1126         buffer_.changed();
1127 }
1128
1129
1130 void BufferView::resize(int width, int height)
1131 {
1132         // Update from work area
1133         width_ = width;
1134         height_ = height;
1135
1136         updateMetrics(false);
1137 }
1138
1139
1140 Inset const * BufferView::getCoveringInset(Text const & text, int x, int y)
1141 {
1142         TextMetrics & tm = text_metrics_[&text];
1143         Inset * inset = tm.checkInsetHit(x, y);
1144         if (!inset)
1145                 return 0;
1146
1147         if (!inset->descendable())
1148                 // No need to go further down if the inset is not
1149                 // descendable.
1150                 return inset;
1151
1152         size_t cell_number = inset->nargs();
1153         // Check all the inner cell.
1154         for (size_t i = 0; i != cell_number; ++i) {
1155                 Text const * inner_text = inset->getText(i);
1156                 if (inner_text) {
1157                         // Try deeper.
1158                         Inset const * inset_deeper =
1159                                 getCoveringInset(*inner_text, x, y);
1160                         if (inset_deeper)
1161                                 return inset_deeper;
1162                 }
1163         }
1164
1165         return inset;
1166 }
1167
1168
1169 bool BufferView::workAreaDispatch(FuncRequest const & cmd0)
1170 {
1171         //lyxerr << BOOST_CURRENT_FUNCTION << "[ cmd0 " << cmd0 << "]" << endl;
1172
1173         // This is only called for mouse related events including
1174         // LFUN_FILE_OPEN generated by drag-and-drop.
1175         FuncRequest cmd = cmd0;
1176
1177         Cursor cur(*this);
1178         cur.push(buffer_.inset());
1179         cur.selection() = cursor_.selection();
1180
1181         // Either the inset under the cursor or the
1182         // surrounding Text will handle this event.
1183
1184         // make sure we stay within the screen...
1185         cmd.y = min(max(cmd.y, -1), height_);
1186
1187         if (cmd.action == LFUN_MOUSE_MOTION && cmd.button() == mouse_button::none) {
1188
1189                 // Get inset under mouse, if there is one.
1190                 Inset const * covering_inset =
1191                         getCoveringInset(buffer_.text(), cmd.x, cmd.y);
1192                 if (covering_inset == last_inset_)
1193                         // Same inset, no need to do anything...
1194                         return false;
1195
1196                 bool need_redraw = false;
1197                 // const_cast because of setMouseHover().
1198                 Inset * inset = const_cast<Inset *>(covering_inset);
1199                 if (last_inset_)
1200                         // Remove the hint on the last hovered inset (if any).
1201                         need_redraw |= last_inset_->setMouseHover(false);
1202                 if (inset)
1203                         // Highlighted the newly hovered inset (if any).
1204                         need_redraw |= inset->setMouseHover(true);
1205                 last_inset_ = inset;
1206                 if (!need_redraw)
1207                         return false;
1208
1209                 // if last metrics update was in singlepar mode, WorkArea::redraw() will
1210                 // not expose the button for redraw. We adjust here the metrics dimension
1211                 // to enable a full redraw in any case as this is not costly.
1212                 TextMetrics & tm = text_metrics_[&buffer_.text()];
1213                 std::pair<pit_type, ParagraphMetrics const *> firstpm = tm.first();
1214                 std::pair<pit_type, ParagraphMetrics const *> lastpm = tm.last();
1215                 int y1 = firstpm.second->position() - firstpm.second->ascent();
1216                 int y2 = lastpm.second->position() + lastpm.second->descent();
1217                 metrics_info_ = ViewMetricsInfo(firstpm.first, lastpm.first, y1, y2,
1218                         FullScreenUpdate, buffer_.text().paragraphs().size());
1219                 // Reinitialize anchor to first pit.
1220                 anchor_ref_ = firstpm.first;
1221                 offset_ref_ = -y1;
1222                 LYXERR(Debug::PAINTING)
1223                         << "Mouse hover detected at: (" << cmd.x << ", " << cmd.y << ")"
1224                         << "\nTriggering redraw: y1: " << y1 << " y2: " << y2
1225                         << " pit1: " << firstpm.first << " pit2: " << lastpm.first << endl;
1226
1227                 // This event (moving without mouse click) is not passed further.
1228                 // This should be changed if it is further utilized.
1229                 return true;
1230         }
1231
1232         // Build temporary cursor.
1233         Inset * inset = text_metrics_[&buffer_.text()].editXY(cur, cmd.x, cmd.y);
1234
1235         // Put anchor at the same position.
1236         cur.resetAnchor();
1237
1238         // Try to dispatch to an non-editable inset near this position
1239         // via the temp cursor. If the inset wishes to change the real
1240         // cursor it has to do so explicitly by using
1241         //  cur.bv().cursor() = cur;  (or similar)
1242         if (inset) {
1243                 inset->dispatch(cur, cmd);
1244         }
1245
1246         // Now dispatch to the temporary cursor. If the real cursor should
1247         // be modified, the inset's dispatch has to do so explicitly.
1248         if (!cur.result().dispatched())
1249                 cur.dispatch(cmd);
1250
1251         //Do we have a selection?
1252         theSelection().haveSelection(cursor().selection());
1253
1254         // Redraw if requested and necessary.
1255         if (cur.result().dispatched() && cur.result().update())
1256                 return update(cur.result().update());
1257
1258         return false;
1259 }
1260
1261
1262 void BufferView::scroll(int y)
1263 {
1264         if (y > 0)
1265                 scrollDown(y);
1266         else if (y < 0)
1267                 scrollUp(-y);
1268 }
1269
1270
1271 void BufferView::scrollDown(int offset)
1272 {
1273         Text * text = &buffer_.text();
1274         TextMetrics & tm = text_metrics_[text];
1275         int ymax = height_ + offset;
1276         while (true) {
1277                 std::pair<pit_type, ParagraphMetrics const *> last = tm.last();
1278                 int bottom_pos = last.second->position() + last.second->descent();
1279                 if (last.first + 1 == int(text->paragraphs().size())) {
1280                         if (bottom_pos <= height_)
1281                                 return;
1282                         offset = min(offset, bottom_pos - height_);
1283                         break;
1284                 }
1285                 if (bottom_pos > ymax)
1286                         break;
1287                 tm.newParMetricsDown();
1288         }
1289         offset_ref_ += offset;
1290         updateMetrics(false);
1291         buffer_.changed();
1292 }
1293
1294
1295 void BufferView::scrollUp(int offset)
1296 {
1297         Text * text = &buffer_.text();
1298         TextMetrics & tm = text_metrics_[text];
1299         int ymin = - offset;
1300         while (true) {
1301                 std::pair<pit_type, ParagraphMetrics const *> first = tm.first();
1302                 int top_pos = first.second->position() - first.second->ascent();
1303                 if (first.first == 0) {
1304                         if (top_pos >= 0)
1305                                 return;
1306                         offset = min(offset, - top_pos);
1307                         break;
1308                 }
1309                 if (top_pos < ymin)
1310                         break;
1311                 tm.newParMetricsUp();
1312         }
1313         offset_ref_ -= offset;
1314         updateMetrics(false);
1315         buffer_.changed();
1316 }
1317
1318
1319 void BufferView::setCursorFromRow(int row)
1320 {
1321         int tmpid = -1;
1322         int tmppos = -1;
1323
1324         buffer_.texrow().getIdFromRow(row, tmpid, tmppos);
1325
1326         cursor_.reset(buffer_.inset());
1327         if (tmpid == -1)
1328                 buffer_.text().setCursor(cursor_, 0, 0);
1329         else
1330                 buffer_.text().setCursor(cursor_, buffer_.getParFromID(tmpid).pit(), tmppos);
1331 }
1332
1333
1334 void BufferView::gotoLabel(docstring const & label)
1335 {
1336         for (InsetIterator it = inset_iterator_begin(buffer_.inset()); it; ++it) {
1337                 vector<docstring> labels;
1338                 it->getLabelList(buffer_, labels);
1339                 if (std::find(labels.begin(), labels.end(), label) != labels.end()) {
1340                         setCursor(it);
1341                         update();
1342                         return;
1343                 }
1344         }
1345 }
1346
1347
1348 TextMetrics const & BufferView::textMetrics(Text const * t) const
1349 {
1350         return const_cast<BufferView *>(this)->textMetrics(t);
1351 }
1352
1353
1354 TextMetrics & BufferView::textMetrics(Text const * t)
1355 {
1356         TextMetricsCache::iterator tmc_it  = text_metrics_.find(t);
1357         if (tmc_it == text_metrics_.end()) {
1358                 tmc_it = text_metrics_.insert(
1359                         make_pair(t, TextMetrics(this, const_cast<Text *>(t)))).first;
1360         }
1361         return tmc_it->second;
1362 }
1363
1364
1365 ParagraphMetrics const & BufferView::parMetrics(Text const * t,
1366                 pit_type pit) const
1367 {
1368         return textMetrics(t).parMetrics(pit);
1369 }
1370
1371
1372 int BufferView::workHeight() const
1373 {
1374         return height_;
1375 }
1376
1377
1378 void BufferView::setCursor(DocIterator const & dit)
1379 {
1380         size_t const n = dit.depth();
1381         for (size_t i = 0; i < n; ++i)
1382                 dit[i].inset().edit(cursor_, true);
1383
1384         cursor_.setCursor(dit);
1385         cursor_.selection() = false;
1386 }
1387
1388
1389 bool BufferView::checkDepm(Cursor & cur, Cursor & old)
1390 {
1391         // Would be wrong to delete anything if we have a selection.
1392         if (cur.selection())
1393                 return false;
1394
1395         bool need_anchor_change = false;
1396         bool changed = cursor_.text()->deleteEmptyParagraphMechanism(cur, old,
1397                 need_anchor_change);
1398
1399         if (need_anchor_change)
1400                 cur.resetAnchor();
1401
1402         if (!changed)
1403                 return false;
1404
1405         updateLabels(buffer_);
1406
1407         updateMetrics(false);
1408         buffer_.changed();
1409         return true;
1410 }
1411
1412
1413 bool BufferView::mouseSetCursor(Cursor & cur)
1414 {
1415         BOOST_ASSERT(&cur.bv() == this);
1416
1417         // this event will clear selection so we save selection for
1418         // persistent selection
1419         cap::saveSelection(cursor());
1420
1421         // Has the cursor just left the inset?
1422         bool badcursor = false;
1423         bool leftinset = (&cursor_.inset() != &cur.inset());
1424         if (leftinset)
1425                 badcursor = notifyCursorLeaves(cursor_, cur);
1426
1427         // do the dEPM magic if needed
1428         // FIXME: (1) move this to InsetText::notifyCursorLeaves?
1429         // FIXME: (2) if we had a working InsetText::notifyCursorLeaves,
1430         // the leftinset bool would not be necessary (badcursor instead).
1431         bool update = leftinset;
1432         if (!badcursor && cursor_.inTexted())
1433                 update |= checkDepm(cur, cursor_);
1434
1435         // if the cursor was in an empty script inset and the new
1436         // position is in the nucleus of the inset, notifyCursorLeaves
1437         // will kill the script inset itself. So we check all the
1438         // elements of the cursor to make sure that they are correct.
1439         // For an example, see bug 2933:
1440         // http://bugzilla.lyx.org/show_bug.cgi?id=2933
1441         // The code below could maybe be moved to a DocIterator method.
1442         //lyxerr << "cur before " << cur <<std::endl;
1443         DocIterator dit(cur.inset());
1444         dit.push_back(cur.bottom());
1445         size_t i = 1;
1446         while (i < cur.depth() && dit.nextInset() == &cur[i].inset()) {
1447                 dit.push_back(cur[i]);
1448                 ++i;
1449         }
1450         //lyxerr << "5 cur after" << dit <<std::endl;
1451
1452         cursor_.setCursor(dit);
1453         cursor_.boundary(cur.boundary());
1454         cursor_.clearSelection();
1455         finishUndo();
1456         return update;
1457 }
1458
1459
1460 void BufferView::putSelectionAt(DocIterator const & cur,
1461                                 int length, bool backwards)
1462 {
1463         cursor_.clearSelection();
1464
1465         setCursor(cur);
1466
1467         if (length) {
1468                 if (backwards) {
1469                         cursor_.pos() += length;
1470                         cursor_.setSelection(cursor_, -length);
1471                 } else
1472                         cursor_.setSelection(cursor_, length);
1473         }
1474 }
1475
1476
1477 Cursor & BufferView::cursor()
1478 {
1479         return cursor_;
1480 }
1481
1482
1483 Cursor const & BufferView::cursor() const
1484 {
1485         return cursor_;
1486 }
1487
1488
1489 pit_type BufferView::anchor_ref() const
1490 {
1491         return anchor_ref_;
1492 }
1493
1494
1495 ViewMetricsInfo const & BufferView::viewMetricsInfo()
1496 {
1497         return metrics_info_;
1498 }
1499
1500
1501 bool BufferView::singleParUpdate()
1502 {
1503         Text & buftext = buffer_.text();
1504         pit_type const bottom_pit = cursor_.bottom().pit();
1505         TextMetrics & tm = textMetrics(&buftext);
1506         int old_height = tm.parMetrics(bottom_pit).height();
1507
1508         // In Single Paragraph mode, rebreak only
1509         // the (main text, not inset!) paragraph containing the cursor.
1510         // (if this paragraph contains insets etc., rebreaking will
1511         // recursively descend)
1512         tm.redoParagraph(bottom_pit);
1513         ParagraphMetrics const & pm = tm.parMetrics(bottom_pit);                
1514         if (pm.height() != old_height)
1515                 // Paragraph height has changed so we cannot proceed to
1516                 // the singlePar optimisation.
1517                 return false;
1518
1519         int y1 = pm.position() - pm.ascent();
1520         int y2 = pm.position() + pm.descent();
1521         metrics_info_ = ViewMetricsInfo(bottom_pit, bottom_pit, y1, y2,
1522                 SingleParUpdate, buftext.paragraphs().size());
1523         LYXERR(Debug::PAINTING)
1524                 << BOOST_CURRENT_FUNCTION
1525                 << "\ny1: " << y1
1526                 << " y2: " << y2
1527                 << " pit: " << bottom_pit
1528                 << " singlepar: 1"
1529                 << endl;
1530         return true;
1531 }
1532
1533
1534 void BufferView::updateMetrics(bool singlepar)
1535 {
1536         if (singlepar && singleParUpdate())
1537                 // No need to update the full screen metrics.
1538                 return;
1539
1540         Text & buftext = buffer_.text();
1541         pit_type const npit = int(buftext.paragraphs().size());
1542
1543         if (anchor_ref_ > int(npit - 1)) {
1544                 anchor_ref_ = int(npit - 1);
1545                 offset_ref_ = 0;
1546         }
1547
1548         // Clear out the position cache in case of full screen redraw,
1549         coord_cache_.clear();
1550
1551         // Clear out paragraph metrics to avoid having invalid metrics
1552         // in the cache from paragraphs not relayouted below
1553         // The complete text metrics will be redone.
1554         text_metrics_.clear();
1555
1556         TextMetrics & tm = textMetrics(&buftext);
1557
1558         pit_type const pit = anchor_ref_;
1559         int pit1 = pit;
1560         int pit2 = pit;
1561
1562         // Rebreak anchor paragraph.
1563         tm.redoParagraph(pit);
1564
1565         // Take care of anchor offset if case a recentering is needed.
1566         updateOffsetRef();
1567
1568         int y0 = tm.parMetrics(pit).ascent() - offset_ref_;
1569
1570         // Redo paragraphs above anchor if necessary.
1571         int y1 = y0;
1572         while (y1 > 0 && pit1 > 0) {
1573                 y1 -= tm.parMetrics(pit1).ascent();
1574                 --pit1;
1575                 tm.redoParagraph(pit1);
1576                 y1 -= tm.parMetrics(pit1).descent();
1577         }
1578
1579         // Take care of ascent of first line
1580         y1 -= tm.parMetrics(pit1).ascent();
1581
1582         // Normalize anchor for next time
1583         anchor_ref_ = pit1;
1584         offset_ref_ = -y1;
1585
1586         // Grey at the beginning is ugly
1587         if (pit1 == 0 && y1 > 0) {
1588                 y0 -= y1;
1589                 y1 = 0;
1590                 anchor_ref_ = 0;
1591         }
1592
1593         // Redo paragraphs below the anchor if necessary.
1594         int y2 = y0;
1595         while (y2 < height_ && pit2 < int(npit) - 1) {
1596                 y2 += tm.parMetrics(pit2).descent();
1597                 ++pit2;
1598                 tm.redoParagraph(pit2);
1599                 y2 += tm.parMetrics(pit2).ascent();
1600         }
1601
1602         // Take care of descent of last line
1603         y2 += tm.parMetrics(pit2).descent();
1604
1605         LYXERR(Debug::PAINTING)
1606                 << BOOST_CURRENT_FUNCTION
1607                 << "\n y1: " << y1
1608                 << " y2: " << y2
1609                 << " pit1: " << pit1
1610                 << " pit2: " << pit2
1611                 << " npit: " << npit
1612                 << " singlepar: 0"
1613                 << endl;
1614
1615         metrics_info_ = ViewMetricsInfo(pit1, pit2, y1, y2,
1616                 FullScreenUpdate, npit);
1617
1618         if (lyxerr.debugging(Debug::WORKAREA)) {
1619                 LYXERR(Debug::WORKAREA) << "BufferView::updateMetrics" << endl;
1620                 coord_cache_.dump();
1621         }
1622 }
1623
1624
1625 void BufferView::menuInsertLyXFile(string const & filenm)
1626 {
1627         BOOST_ASSERT(cursor_.inTexted());
1628         string filename = filenm;
1629
1630         if (filename.empty()) {
1631                 // Launch a file browser
1632                 // FIXME UNICODE
1633                 string initpath = lyxrc.document_path;
1634                 string const trypath = buffer_.filePath();
1635                 // If directory is writeable, use this as default.
1636                 if (isDirWriteable(FileName(trypath)))
1637                         initpath = trypath;
1638
1639                 // FIXME UNICODE
1640                 FileDialog fileDlg(_("Select LyX document to insert"),
1641                         LFUN_FILE_INSERT,
1642                         make_pair(_("Documents|#o#O"), from_utf8(lyxrc.document_path)),
1643                         make_pair(_("Examples|#E#e"),
1644                                     from_utf8(addPath(package().system_support().absFilename(),
1645                                     "examples"))));
1646
1647                 FileDialog::Result result =
1648                         fileDlg.open(from_utf8(initpath),
1649                                      FileFilterList(_("LyX Documents (*.lyx)")),
1650                                      docstring());
1651
1652                 if (result.first == FileDialog::Later)
1653                         return;
1654
1655                 // FIXME UNICODE
1656                 filename = to_utf8(result.second);
1657
1658                 // check selected filename
1659                 if (filename.empty()) {
1660                         // emit message signal.
1661                         message(_("Canceled."));
1662                         return;
1663                 }
1664         }
1665
1666         // Get absolute path of file and add ".lyx"
1667         // to the filename if necessary
1668         filename = fileSearch(string(), filename, "lyx").absFilename();
1669
1670         docstring const disp_fn = makeDisplayPath(filename);
1671         // emit message signal.
1672         message(bformat(_("Inserting document %1$s..."), disp_fn));
1673
1674         docstring res;
1675         Buffer buf("", false);
1676         if (lyx::loadLyXFile(&buf, FileName(filename))) {
1677                 ErrorList & el = buffer_.errorList("Parse");
1678                 // Copy the inserted document error list into the current buffer one.
1679                 el = buf.errorList("Parse");
1680                 recordUndo(cursor_);
1681                 cap::pasteParagraphList(cursor_, buf.paragraphs(),
1682                                              buf.params().getTextClassPtr(), el);
1683                 res = _("Document %1$s inserted.");
1684         } else
1685                 res = _("Could not insert document %1$s");
1686
1687         // emit message signal.
1688         message(bformat(res, disp_fn));
1689         buffer_.errors("Parse");
1690         updateMetrics(false);
1691 }
1692
1693
1694 void BufferView::draw(frontend::Painter & pain)
1695 {
1696         PainterInfo pi(this, pain);
1697         // Should the whole screen, including insets, be refreshed?
1698         // FIXME: We should also distinguish DecorationUpdate to avoid text
1699         // drawing if possible. This is not possible to do easily right now
1700         // because of the single backing pixmap.
1701         pi.full_repaint = metrics_info_.update_strategy != SingleParUpdate;
1702
1703         if (pi.full_repaint)
1704                 // Clear background (if not delegated to rows)
1705                 pain.fillRectangle(0, metrics_info_.y1, width_,
1706                         metrics_info_.y2 - metrics_info_.y1,
1707                         buffer_.inset().backgroundColor());
1708
1709         LYXERR(Debug::PAINTING) << "\t\t*** START DRAWING ***" << endl;
1710         Text & text = buffer_.text();
1711         TextMetrics const & tm = text_metrics_[&text];
1712         int y = metrics_info_.y1 + tm.parMetrics(metrics_info_.p1).ascent();
1713         if (!pi.full_repaint)
1714                 tm.drawParagraph(pi, metrics_info_.p1, 0, y);
1715         else
1716                 tm.draw(pi, 0, y);
1717         LYXERR(Debug::PAINTING) << "\n\t\t*** END DRAWING  ***" << endl;
1718
1719         // and grey out above (should not happen later)
1720 //      lyxerr << "par ascent: " << text.getPar(metrics_info_.p1).ascent() << endl;
1721         if (metrics_info_.y1 > 0
1722                 && metrics_info_.update_strategy == FullScreenUpdate)
1723                 pain.fillRectangle(0, 0, width_, metrics_info_.y1, Color::bottomarea);
1724
1725         // and possibly grey out below
1726 //      lyxerr << "par descent: " << text.getPar(metrics_info_.p1).ascent() << endl;
1727         if (metrics_info_.y2 < height_
1728                 && metrics_info_.update_strategy == FullScreenUpdate)
1729                 pain.fillRectangle(0, metrics_info_.y2, width_,
1730                         height_ - metrics_info_.y2, Color::bottomarea);
1731 }
1732
1733 } // namespace lyx