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