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