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