]> git.lyx.org Git - lyx.git/blob - src/buffer_funcs.cpp
PrefShortcuts: list all shortcuts (bound and unbound), using a better implementation
[lyx.git] / src / buffer_funcs.cpp
1 /**
2  * \file buffer_funcs.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author Alfredo Braunstein
8  *
9  * Full author contact details are available in file CREDITS.
10  *
11  */
12
13 #include <config.h>
14
15 #include "buffer_funcs.h"
16 #include "Buffer.h"
17 #include "BufferList.h"
18 #include "BufferParams.h"
19 #include "debug.h"
20 #include "DocIterator.h"
21 #include "Counters.h"
22 #include "ErrorList.h"
23 #include "Floating.h"
24 #include "FloatList.h"
25 #include "gettext.h"
26 #include "InsetList.h"
27 #include "InsetIterator.h"
28 #include "Language.h"
29 #include "LaTeX.h"
30 #include "Layout.h"
31 #include "LyX.h"
32 #include "lyxlayout_ptr_fwd.h"
33 #include "TextClass.h"
34 #include "TextClassList.h"
35 #include "Paragraph.h"
36 #include "paragraph_funcs.h"
37 #include "ParagraphList.h"
38 #include "ParagraphParameters.h"
39 #include "ParIterator.h"
40 #include "LyXVC.h"
41 #include "TexRow.h"
42 #include "Text.h"
43 #include "TocBackend.h"
44 #include "VCBackend.h"
45
46 #include "frontends/alert.h"
47
48 #include "insets/InsetBibitem.h"
49 #include "insets/InsetInclude.h"
50
51 #include "support/filetools.h"
52 #include "support/fs_extras.h"
53 #include "support/lyxlib.h"
54
55 #include <boost/bind.hpp>
56 #include <boost/filesystem/operations.hpp>
57
58 using std::min;
59 using std::string;
60
61
62 namespace lyx {
63
64 using namespace std;
65
66 using support::bformat;
67 using support::FileName;
68 using support::libFileSearch;
69 using support::makeAbsPath;
70 using support::makeDisplayPath;
71 using support::onlyFilename;
72 using support::onlyPath;
73 using support::unlink;
74
75 namespace Alert = frontend::Alert;
76 namespace fs = boost::filesystem;
77
78 namespace {
79
80 bool readFile(Buffer * const b, FileName const & s)
81 {
82         BOOST_ASSERT(b);
83
84         // File information about normal file
85         if (!fs::exists(s.toFilesystemEncoding())) {
86                 docstring const file = makeDisplayPath(s.absFilename(), 50);
87                 docstring text = bformat(_("The specified document\n%1$s"
88                                                      "\ncould not be read."), file);
89                 Alert::error(_("Could not read document"), text);
90                 return false;
91         }
92
93         // Check if emergency save file exists and is newer.
94         FileName const e(s.absFilename() + ".emergency");
95
96         if (fs::exists(e.toFilesystemEncoding()) &&
97             fs::exists(s.toFilesystemEncoding()) &&
98             fs::last_write_time(e.toFilesystemEncoding()) > fs::last_write_time(s.toFilesystemEncoding()))
99         {
100                 docstring const file = makeDisplayPath(s.absFilename(), 20);
101                 docstring const text =
102                         bformat(_("An emergency save of the document "
103                                   "%1$s exists.\n\n"
104                                                "Recover emergency save?"), file);
105                 switch (Alert::prompt(_("Load emergency save?"), text, 0, 2,
106                                       _("&Recover"),  _("&Load Original"),
107                                       _("&Cancel")))
108                 {
109                 case 0:
110                         // the file is not saved if we load the emergency file.
111                         b->markDirty();
112                         return b->readFile(e);
113                 case 1:
114                         break;
115                 default:
116                         return false;
117                 }
118         }
119
120         // Now check if autosave file is newer.
121         FileName const a(onlyPath(s.absFilename()) + '#' + onlyFilename(s.absFilename()) + '#');
122
123         if (fs::exists(a.toFilesystemEncoding()) &&
124             fs::exists(s.toFilesystemEncoding()) &&
125             fs::last_write_time(a.toFilesystemEncoding()) > fs::last_write_time(s.toFilesystemEncoding()))
126         {
127                 docstring const file = makeDisplayPath(s.absFilename(), 20);
128                 docstring const text =
129                         bformat(_("The backup of the document "
130                                   "%1$s is newer.\n\nLoad the "
131                                                "backup instead?"), file);
132                 switch (Alert::prompt(_("Load backup?"), text, 0, 2,
133                                       _("&Load backup"), _("Load &original"),
134                                       _("&Cancel") ))
135                 {
136                 case 0:
137                         // the file is not saved if we load the autosave file.
138                         b->markDirty();
139                         return b->readFile(a);
140                 case 1:
141                         // Here we delete the autosave
142                         unlink(a);
143                         break;
144                 default:
145                         return false;
146                 }
147         }
148         return b->readFile(s);
149 }
150
151
152 } // namespace anon
153
154
155
156 bool loadLyXFile(Buffer * b, FileName const & s)
157 {
158         BOOST_ASSERT(b);
159
160         if (fs::is_readable(s.toFilesystemEncoding())) {
161                 if (readFile(b, s)) {
162                         b->lyxvc().file_found_hook(s);
163                         if (!fs::is_writable(s.toFilesystemEncoding()))
164                                 b->setReadonly(true);
165                         return true;
166                 }
167         } else {
168                 docstring const file = makeDisplayPath(s.absFilename(), 20);
169                 // Here we probably should run
170                 if (LyXVC::file_not_found_hook(s)) {
171                         docstring const text =
172                                 bformat(_("Do you want to retrieve the document"
173                                                        " %1$s from version control?"), file);
174                         int const ret = Alert::prompt(_("Retrieve from version control?"),
175                                 text, 0, 1, _("&Retrieve"), _("&Cancel"));
176
177                         if (ret == 0) {
178                                 // How can we know _how_ to do the checkout?
179                                 // With the current VC support it has to be,
180                                 // a RCS file since CVS do not have special ,v files.
181                                 RCS::retrieve(s);
182                                 return loadLyXFile(b, s);
183                         }
184                 }
185         }
186         return false;
187 }
188
189
190 bool checkIfLoaded(FileName const & fn)
191 {
192         return theBufferList().getBuffer(fn.absFilename());
193 }
194
195
196 Buffer * checkAndLoadLyXFile(FileName const & filename)
197 {
198         // File already open?
199         Buffer * checkBuffer = theBufferList().getBuffer(filename.absFilename());
200         if (checkBuffer) {
201                 if (checkBuffer->isClean())
202                         return checkBuffer;
203                 docstring const file = makeDisplayPath(filename.absFilename(), 20);
204                 docstring text = bformat(_(
205                                 "The document %1$s is already loaded and has unsaved changes.\n"
206                                 "Do you want to abandon your changes and reload the version on disk?"), file);
207                 if (Alert::prompt(_("Reload saved document?"),
208                                 text, 0, 1,  _("&Reload"), _("&Keep Changes")))
209                         return checkBuffer;
210
211                 // FIXME: should be LFUN_REVERT
212                 if (theBufferList().close(checkBuffer, false))
213                         // Load it again.
214                         return checkAndLoadLyXFile(filename);
215                 else
216                         // The file could not be closed.
217                         return 0;
218         }
219
220         if (isFileReadable(filename)) {
221                 Buffer * b = theBufferList().newBuffer(filename.absFilename());
222                 if (!lyx::loadLyXFile(b, filename)) {
223                         theBufferList().release(b);
224                         return 0;
225                 }
226                 return b;
227         }
228
229         docstring text = bformat(_("The document %1$s does not yet "
230                 "exist.\n\nDo you want to create a new document?"),
231                 from_utf8(filename.absFilename()));
232         if (!Alert::prompt(_("Create new document?"),
233                         text, 0, 1, _("&Create"), _("Cancel")))
234                 return newFile(filename.absFilename(), string(), true);
235
236         return 0;
237 }
238
239 // FIXME newFile() should probably be a member method of Application...
240 Buffer * newFile(string const & filename, string const & templatename,
241                  bool const isNamed)
242 {
243         // get a free buffer
244         Buffer * b = theBufferList().newBuffer(filename);
245         BOOST_ASSERT(b);
246
247         FileName tname;
248         // use defaults.lyx as a default template if it exists.
249         if (templatename.empty())
250                 tname = libFileSearch("templates", "defaults.lyx");
251         else
252                 tname = makeAbsPath(templatename);
253
254         if (!tname.empty()) {
255                 if (!b->readFile(tname)) {
256                         docstring const file = makeDisplayPath(tname.absFilename(), 50);
257                         docstring const text  = bformat(
258                                 _("The specified document template\n%1$s\ncould not be read."),
259                                 file);
260                         Alert::error(_("Could not read template"), text);
261                         theBufferList().release(b);
262                         return 0;
263                 }
264         }
265
266         if (!isNamed) {
267                 b->setUnnamed();
268                 b->setFileName(filename);
269         }
270
271         b->setReadonly(false);
272         b->fully_loaded(true);
273
274         return b;
275 }
276
277
278 void bufferErrors(Buffer const & buf, TeXErrors const & terr,
279                                   ErrorList & errorList)
280 {
281         TeXErrors::Errors::const_iterator cit = terr.begin();
282         TeXErrors::Errors::const_iterator end = terr.end();
283
284         for (; cit != end; ++cit) {
285                 int id_start = -1;
286                 int pos_start = -1;
287                 int errorrow = cit->error_in_line;
288                 bool found = buf.texrow().getIdFromRow(errorrow, id_start,
289                                                        pos_start);
290                 int id_end = -1;
291                 int pos_end = -1;
292                 do {
293                         ++errorrow;
294                         found = buf.texrow().getIdFromRow(errorrow, id_end,
295                                                           pos_end);
296                 } while (found && id_start == id_end && pos_start == pos_end);
297
298                 errorList.push_back(ErrorItem(cit->error_desc,
299                         cit->error_text, id_start, pos_start, pos_end));
300         }
301 }
302
303
304 string const bufferFormat(Buffer const & buffer)
305 {
306         if (buffer.isDocBook())
307                 return "docbook";
308         else if (buffer.isLiterate())
309                 return "literate";
310         else
311                 return "latex";
312 }
313
314
315 int countWords(DocIterator const & from, DocIterator const & to)
316 {
317         int count = 0;
318         bool inword = false;
319         for (DocIterator dit = from ; dit != to ; dit.forwardPos()) {
320                 // Copied and adapted from isLetter() in ControlSpellChecker
321                 if (dit.inTexted()
322                     && dit.pos() != dit.lastpos()
323                     && dit.paragraph().isLetter(dit.pos())
324                     && !dit.paragraph().isDeleted(dit.pos())) {
325                         if (!inword) {
326                                 ++count;
327                                 inword = true;
328                         }
329                 } else if (inword)
330                         inword = false;
331         }
332
333         return count;
334 }
335
336
337 namespace {
338
339 depth_type getDepth(DocIterator const & it)
340 {
341         depth_type depth = 0;
342         for (size_t i = 0 ; i < it.depth() ; ++i)
343                 if (!it[i].inset().inMathed())
344                         depth += it[i].paragraph().getDepth() + 1;
345         // remove 1 since the outer inset does not count
346         return depth - 1;
347 }
348
349 depth_type getItemDepth(ParIterator const & it)
350 {
351         Paragraph const & par = *it;
352         LabelType const labeltype = par.layout()->labeltype;
353
354         if (labeltype != LABEL_ENUMERATE && labeltype != LABEL_ITEMIZE)
355                 return 0;
356
357         // this will hold the lowest depth encountered up to now.
358         depth_type min_depth = getDepth(it);
359         ParIterator prev_it = it;
360         while (true) {
361                 if (prev_it.pit())
362                         --prev_it.top().pit();
363                 else {
364                         // start of nested inset: go to outer par
365                         prev_it.pop_back();
366                         if (prev_it.empty()) {
367                                 // start of document: nothing to do
368                                 return 0;
369                         }
370                 }
371
372                 // We search for the first paragraph with same label
373                 // that is not more deeply nested.
374                 Paragraph & prev_par = *prev_it;
375                 depth_type const prev_depth = getDepth(prev_it);
376                 if (labeltype == prev_par.layout()->labeltype) {
377                         if (prev_depth < min_depth) {
378                                 return prev_par.itemdepth + 1;
379                         }
380                         else if (prev_depth == min_depth) {
381                                 return prev_par.itemdepth;
382                         }
383                 }
384                 min_depth = std::min(min_depth, prev_depth);
385                 // small optimization: if we are at depth 0, we won't
386                 // find anything else
387                 if (prev_depth == 0) {
388                         return 0;
389                 }
390         }
391 }
392
393
394 bool needEnumCounterReset(ParIterator const & it)
395 {
396         Paragraph const & par = *it;
397         BOOST_ASSERT(par.layout()->labeltype == LABEL_ENUMERATE);
398         depth_type const cur_depth = par.getDepth();
399         ParIterator prev_it = it;
400         while (prev_it.pit()) {
401                 --prev_it.top().pit();
402                 Paragraph const & prev_par = *prev_it;
403                 if (prev_par.getDepth() <= cur_depth)
404                         return  prev_par.layout()->labeltype != LABEL_ENUMERATE;
405         }
406         // start of nested inset: reset
407         return true;
408 }
409
410
411 // set the label of a paragraph. This includes the counters.
412 void setLabel(Buffer const & buf, ParIterator & it)
413 {
414         TextClass const & textclass = buf.params().getTextClass();
415         Paragraph & par = it.paragraph();
416         LayoutPtr const & layout = par.layout();
417         Counters & counters = textclass.counters();
418
419         if (par.params().startOfAppendix()) {
420                 // FIXME: only the counter corresponding to toplevel
421                 // sectionning should be reset
422                 counters.reset();
423                 counters.appendix(true);
424         }
425         par.params().appendix(counters.appendix());
426
427         // Compute the item depth of the paragraph
428         par.itemdepth = getItemDepth(it);
429
430         if (layout->margintype == MARGIN_MANUAL) {
431                 if (par.params().labelWidthString().empty())
432                         par.params().labelWidthString(par.translateIfPossible(layout->labelstring(), buf.params()));
433         } else {
434                 par.params().labelWidthString(docstring());
435         }
436
437         switch(layout->labeltype) {
438         case LABEL_COUNTER:
439                 if (layout->toclevel <= buf.params().secnumdepth
440                     && (layout->latextype != LATEX_ENVIRONMENT
441                         || isFirstInSequence(it.pit(), it.plist()))) {
442                         counters.step(layout->counter);
443                         par.params().labelString(
444                                 par.expandLabel(layout, buf.params()));
445                 } else
446                         par.params().labelString(docstring());
447                 break;
448
449         case LABEL_ITEMIZE: {
450                 // At some point of time we should do something more
451                 // clever here, like:
452                 //   par.params().labelString(
453                 //    buf.params().user_defined_bullet(par.itemdepth).getText());
454                 // for now, use a simple hardcoded label
455                 docstring itemlabel;
456                 switch (par.itemdepth) {
457                 case 0:
458                         itemlabel = char_type(0x2022);
459                         break;
460                 case 1:
461                         itemlabel = char_type(0x2013);
462                         break;
463                 case 2:
464                         itemlabel = char_type(0x2217);
465                         break;
466                 case 3:
467                         itemlabel = char_type(0x2219); // or 0x00b7
468                         break;
469                 }
470                 par.params().labelString(itemlabel);
471                 break;
472         }
473
474         case LABEL_ENUMERATE: {
475                 // FIXME: Yes I know this is a really, really! bad solution
476                 // (Lgb)
477                 docstring enumcounter = from_ascii("enum");
478
479                 switch (par.itemdepth) {
480                 case 2:
481                         enumcounter += 'i';
482                 case 1:
483                         enumcounter += 'i';
484                 case 0:
485                         enumcounter += 'i';
486                         break;
487                 case 3:
488                         enumcounter += "iv";
489                         break;
490                 default:
491                         // not a valid enumdepth...
492                         break;
493                 }
494
495                 // Maybe we have to reset the enumeration counter.
496                 if (needEnumCounterReset(it))
497                         counters.reset(enumcounter);
498
499                 counters.step(enumcounter);
500
501                 string format;
502
503                 switch (par.itemdepth) {
504                 case 0:
505                         format = N_("\\arabic{enumi}.");
506                         break;
507                 case 1:
508                         format = N_("(\\alph{enumii})");
509                         break;
510                 case 2:
511                         format = N_("\\roman{enumiii}.");
512                         break;
513                 case 3:
514                         format = N_("\\Alph{enumiv}.");
515                         break;
516                 default:
517                         // not a valid enumdepth...
518                         break;
519                 }
520
521                 par.params().labelString(counters.counterLabel(
522                         par.translateIfPossible(from_ascii(format), buf.params())));
523
524                 break;
525         }
526
527         case LABEL_SENSITIVE: {
528                 string const & type = counters.current_float();
529                 docstring full_label;
530                 if (type.empty())
531                         full_label = buf.B_("Senseless!!! ");
532                 else {
533                         docstring name = buf.B_(textclass.floats().getType(type).name());
534                         if (counters.hasCounter(from_utf8(type))) {
535                                 counters.step(from_utf8(type));
536                                 full_label = bformat(from_ascii("%1$s %2$s:"), 
537                                                      name, 
538                                                      counters.theCounter(from_utf8(type)));
539                         } else
540                                 full_label = bformat(from_ascii("%1$s #:"), name);      
541                 }
542                 par.params().labelString(full_label);   
543                 break;
544         }
545
546         case LABEL_NO_LABEL:
547                 par.params().labelString(docstring());
548                 break;
549
550         case LABEL_MANUAL:
551         case LABEL_TOP_ENVIRONMENT:
552         case LABEL_CENTERED_TOP_ENVIRONMENT:
553         case LABEL_STATIC:      
554         case LABEL_BIBLIO:
555                 par.params().labelString(
556                         par.translateIfPossible(layout->labelstring(), 
557                                                 buf.params()));
558                 break;
559         }
560 }
561
562 } // anon namespace
563
564 void updateLabels(Buffer const & buf, ParIterator & parit)
565 {
566         BOOST_ASSERT(parit.pit() == 0);
567
568         depth_type maxdepth = 0;
569         pit_type const lastpit = parit.lastpit();
570         for ( ; parit.pit() <= lastpit ; ++parit.pit()) {
571                 // reduce depth if necessary
572                 parit->params().depth(min(parit->params().depth(), maxdepth));
573                 maxdepth = parit->getMaxDepthAfter();
574
575                 // set the counter for this paragraph
576                 setLabel(buf, parit);
577
578                 // Now the insets
579                 InsetList::const_iterator iit = parit->insetList().begin();
580                 InsetList::const_iterator end = parit->insetList().end();
581                 for (; iit != end; ++iit) {
582                         parit.pos() = iit->pos;
583                         iit->inset->updateLabels(buf, parit);
584                 }
585         }
586         
587 }
588
589
590 // FIXME: buf should should be const because updateLabels() modifies
591 // the contents of the paragraphs.
592 void updateLabels(Buffer const & buf, bool childonly)
593 {
594         Buffer const * const master = buf.getMasterBuffer();
595         // Use the master text class also for child documents
596         TextClass const & textclass = master->params().getTextClass();
597
598         if (!childonly) {
599                 // If this is a child document start with the master
600                 if (master != &buf) {
601                         updateLabels(*master);
602                         return;
603                 }
604
605                 // start over the counters
606                 textclass.counters().reset();
607         }
608
609         Buffer & cbuf = const_cast<Buffer &>(buf);
610
611         if (buf.text().empty()) {
612                 // FIXME: we don't call continue with updateLabels()
613                 // here because it crashes on newly created documents.
614                 // But the TocBackend needs to be initialised
615                 // nonetheless so we update the tocBackend manually.
616                 cbuf.tocBackend().update();
617                 return;
618         }
619
620         // do the real work
621         ParIterator parit = par_iterator_begin(buf.inset());
622         updateLabels(buf, parit);
623
624         cbuf.tocBackend().update();
625         if (!childonly)
626                 cbuf.structureChanged();
627         // FIXME
628         // the embedding signal is emitted with structureChanged signal
629         // this is inaccurate so these two will be separated later.
630         //cbuf.embeddedFiles().update();
631         //cbuf.embeddingChanged();
632 }
633
634
635 void checkBufferStructure(Buffer & buffer, ParIterator const & par_it)
636 {
637         if (par_it->layout()->toclevel != Layout::NOT_IN_TOC) {
638                 Buffer * master = buffer.getMasterBuffer();
639                 master->tocBackend().updateItem(par_it);
640                 master->structureChanged();
641         }
642 }
643
644 textclass_type defaultTextclass()
645 {
646         // We want to return the article class. if `first' is
647         // true in the returned pair, then `second' is the textclass
648         // number; if it is false, second is 0. In both cases, second
649         // is what we want.
650         return textclasslist.numberOfClass("article").second;
651 }
652
653
654 void loadChildDocuments(Buffer const & buf)
655 {
656         bool parse_error = false;
657                 
658         for (InsetIterator it = inset_iterator_begin(buf.inset()); it; ++it) {
659                 if (it->lyxCode() != INCLUDE_CODE)
660                         continue;
661                 InsetInclude const & inset = static_cast<InsetInclude const &>(*it);
662                 InsetCommandParams const & ip = inset.params();
663                 Buffer * child = loadIfNeeded(buf, ip);
664                 if (!child)
665                         continue;
666                 parse_error |= !child->errorList("Parse").empty();
667                 loadChildDocuments(*child);
668         }
669
670         if (use_gui && buf.getMasterBuffer() == &buf)
671                 updateLabels(buf);
672 }
673 } // namespace lyx