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