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