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