]> git.lyx.org Git - lyx.git/blob - src/buffer.C
Fixing bugs 1844,1845: doc settings don't stick
[lyx.git] / src / buffer.C
1 /**
2  * \file buffer.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  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "buffer.h"
14
15 #include "author.h"
16 #include "BranchList.h"
17 #include "buffer_funcs.h"
18 #include "bufferlist.h"
19 #include "bufferparams.h"
20 #include "counters.h"
21 #include "Bullet.h"
22 #include "Chktex.h"
23 #include "debug.h"
24 #include "encoding.h"
25 #include "errorlist.h"
26 #include "exporter.h"
27 #include "format.h"
28 #include "funcrequest.h"
29 #include "gettext.h"
30 #include "insetiterator.h"
31 #include "language.h"
32 #include "LaTeX.h"
33 #include "LaTeXFeatures.h"
34 #include "LyXAction.h"
35 #include "lyxlex.h"
36 #include "lyxtext.h"
37 #include "lyxrc.h"
38 #include "lyxvc.h"
39 #include "lyx_main.h"
40 #include "messages.h"
41 #include "output.h"
42 #include "output_docbook.h"
43 #include "output_latex.h"
44 #include "output_linuxdoc.h"
45 #include "paragraph.h"
46 #include "paragraph_funcs.h"
47 #include "ParagraphParameters.h"
48 #include "pariterator.h"
49 #include "sgml.h"
50 #include "texrow.h"
51 #include "undo.h"
52 #include "version.h"
53
54 #include "insets/insetbibitem.h"
55 #include "insets/insetbibtex.h"
56 #include "insets/insetinclude.h"
57 #include "insets/insettext.h"
58
59 #include "mathed/math_macrotemplate.h"
60 #include "mathed/math_macrotable.h"
61 #include "mathed/math_support.h"
62
63 #include "frontends/Alert.h"
64
65 #include "graphics/Previews.h"
66
67 #include "support/filetools.h"
68 #include "support/fs_extras.h"
69 #ifdef USE_COMPRESSION
70 # include "support/gzstream.h"
71 #endif
72 #include "support/lyxlib.h"
73 #include "support/os.h"
74 #include "support/path.h"
75 #include "support/textutils.h"
76 #include "support/convert.h"
77
78 #include <boost/bind.hpp>
79 #include <boost/filesystem/operations.hpp>
80
81 #include <utime.h>
82
83 #include <iomanip>
84 #include <stack>
85 #include <sstream>
86 #include <fstream>
87
88
89 using lyx::pos_type;
90 using lyx::pit_type;
91
92 using lyx::support::AddName;
93 using lyx::support::bformat;
94 using lyx::support::ChangeExtension;
95 using lyx::support::cmd_ret;
96 using lyx::support::createBufferTmpDir;
97 using lyx::support::destroyDir;
98 using lyx::support::getFormatFromContents;
99 using lyx::support::IsDirWriteable;
100 using lyx::support::LibFileSearch;
101 using lyx::support::ltrim;
102 using lyx::support::MakeAbsPath;
103 using lyx::support::MakeDisplayPath;
104 using lyx::support::MakeLatexName;
105 using lyx::support::OnlyFilename;
106 using lyx::support::OnlyPath;
107 using lyx::support::Path;
108 using lyx::support::QuoteName;
109 using lyx::support::removeAutosaveFile;
110 using lyx::support::rename;
111 using lyx::support::RunCommand;
112 using lyx::support::split;
113 using lyx::support::subst;
114 using lyx::support::tempName;
115 using lyx::support::trim;
116
117 namespace os = lyx::support::os;
118 namespace fs = boost::filesystem;
119
120 using std::endl;
121 using std::for_each;
122 using std::make_pair;
123
124 using std::ifstream;
125 using std::ios;
126 using std::map;
127 using std::ostream;
128 using std::ostringstream;
129 using std::ofstream;
130 using std::pair;
131 using std::stack;
132 using std::vector;
133 using std::string;
134
135
136 // all these externs should eventually be removed.
137 extern BufferList bufferlist;
138
139 namespace {
140
141 int const LYX_FORMAT = 241;
142
143 } // namespace anon
144
145
146 typedef std::map<string, bool> DepClean;
147
148 class Buffer::Impl
149 {
150 public:
151         Impl(Buffer & parent, string const & file, bool readonly);
152
153         limited_stack<Undo> undostack;
154         limited_stack<Undo> redostack;
155         BufferParams params;
156         LyXVC lyxvc;
157         string temppath;
158         TexRow texrow;
159
160         /// need to regenerate .tex?
161         DepClean dep_clean;
162
163         /// is save needed?
164         mutable bool lyx_clean;
165
166         /// is autosave needed?
167         mutable bool bak_clean;
168
169         /// is this a unnamed file (New...)?
170         bool unnamed;
171
172         /// buffer is r/o
173         bool read_only;
174
175         /// name of the file the buffer is associated with.
176         string filename;
177
178         /// The path to the document file.
179         string filepath;
180
181         boost::scoped_ptr<Messages> messages;
182
183         /** Set to true only when the file is fully loaded.
184          *  Used to prevent the premature generation of previews
185          *  and by the citation inset.
186          */
187         bool file_fully_loaded;
188
189         /// our LyXText that should be wrapped in an InsetText
190         InsetText inset;
191
192         ///
193         MacroTable macros;
194 };
195
196
197 Buffer::Impl::Impl(Buffer & parent, string const & file, bool readonly_)
198         : lyx_clean(true), bak_clean(true), unnamed(false), read_only(readonly_),
199           filename(file), filepath(OnlyPath(file)), file_fully_loaded(false),
200                 inset(params)
201 {
202         inset.setAutoBreakRows(true);
203         lyxvc.buffer(&parent);
204         temppath = createBufferTmpDir();
205         // FIXME: And now do something if temppath == string(), because we
206         // assume from now on that temppath points to a valid temp dir.
207         // See http://www.mail-archive.com/lyx-devel@lists.lyx.org/msg67406.html
208 }
209
210
211 Buffer::Buffer(string const & file, bool ronly)
212         : pimpl_(new Impl(*this, file, ronly))
213 {
214         lyxerr[Debug::INFO] << "Buffer::Buffer()" << endl;
215 }
216
217
218 Buffer::~Buffer()
219 {
220         lyxerr[Debug::INFO] << "Buffer::~Buffer()" << endl;
221         // here the buffer should take care that it is
222         // saved properly, before it goes into the void.
223
224         closing();
225
226         if (!temppath().empty() && !destroyDir(temppath())) {
227                 Alert::warning(_("Could not remove temporary directory"),
228                         bformat(_("Could not remove the temporary directory %1$s"), temppath()));
229         }
230
231         // Remove any previewed LaTeX snippets associated with this buffer.
232         lyx::graphics::Previews::get().removeLoader(*this);
233 }
234
235
236 LyXText & Buffer::text() const
237 {
238         return const_cast<LyXText &>(pimpl_->inset.text_);
239 }
240
241
242 InsetBase & Buffer::inset() const
243 {
244         return const_cast<InsetText &>(pimpl_->inset);
245 }
246
247
248 limited_stack<Undo> & Buffer::undostack()
249 {
250         return pimpl_->undostack;
251 }
252
253
254 limited_stack<Undo> const & Buffer::undostack() const
255 {
256         return pimpl_->undostack;
257 }
258
259
260 limited_stack<Undo> & Buffer::redostack()
261 {
262         return pimpl_->redostack;
263 }
264
265
266 limited_stack<Undo> const & Buffer::redostack() const
267 {
268         return pimpl_->redostack;
269 }
270
271
272 BufferParams & Buffer::params()
273 {
274         return pimpl_->params;
275 }
276
277
278 BufferParams const & Buffer::params() const
279 {
280         return pimpl_->params;
281 }
282
283
284 ParagraphList & Buffer::paragraphs()
285 {
286         return text().paragraphs();
287 }
288
289
290 ParagraphList const & Buffer::paragraphs() const
291 {
292         return text().paragraphs();
293 }
294
295
296 LyXVC & Buffer::lyxvc()
297 {
298         return pimpl_->lyxvc;
299 }
300
301
302 LyXVC const & Buffer::lyxvc() const
303 {
304         return pimpl_->lyxvc;
305 }
306
307
308 string const & Buffer::temppath() const
309 {
310         return pimpl_->temppath;
311 }
312
313
314 TexRow & Buffer::texrow()
315 {
316         return pimpl_->texrow;
317 }
318
319
320 TexRow const & Buffer::texrow() const
321 {
322         return pimpl_->texrow;
323 }
324
325
326 string const Buffer::getLatexName(bool const no_path) const
327 {
328         string const name = ChangeExtension(MakeLatexName(fileName()), ".tex");
329         return no_path ? OnlyFilename(name) : name;
330 }
331
332
333 pair<Buffer::LogType, string> const Buffer::getLogName() const
334 {
335         string const filename = getLatexName(false);
336
337         if (filename.empty())
338                 return make_pair(Buffer::latexlog, string());
339
340         string const path = temppath();
341
342         string const fname = AddName(path,
343                                      OnlyFilename(ChangeExtension(filename,
344                                                                   ".log")));
345         string const bname =
346                 AddName(path, OnlyFilename(
347                         ChangeExtension(filename,
348                                         formats.extension("literate") + ".out")));
349
350         // If no Latex log or Build log is newer, show Build log
351
352         if (fs::exists(bname) &&
353             (!fs::exists(fname) || fs::last_write_time(fname) < fs::last_write_time(bname))) {
354                 lyxerr[Debug::FILES] << "Log name calculated as: " << bname << endl;
355                 return make_pair(Buffer::buildlog, bname);
356         }
357         lyxerr[Debug::FILES] << "Log name calculated as: " << fname << endl;
358         return make_pair(Buffer::latexlog, fname);
359 }
360
361
362 void Buffer::setReadonly(bool const flag)
363 {
364         if (pimpl_->read_only != flag) {
365                 pimpl_->read_only = flag;
366                 readonly(flag);
367         }
368 }
369
370
371 void Buffer::setFileName(string const & newfile)
372 {
373         pimpl_->filename = MakeAbsPath(newfile);
374         pimpl_->filepath = OnlyPath(pimpl_->filename);
375         setReadonly(fs::is_readonly(pimpl_->filename));
376         updateTitles();
377 }
378
379
380 // We'll remove this later. (Lgb)
381 namespace {
382
383 void unknownClass(string const & unknown)
384 {
385         Alert::warning(_("Unknown document class"),
386                 bformat(_("Using the default document class, because the "
387                         "class %1$s is unknown."), unknown));
388 }
389
390 } // anon
391
392
393 int Buffer::readHeader(LyXLex & lex)
394 {
395         int unknown_tokens = 0;
396         int line = -1;
397         int begin_header_line = -1;
398
399         // Initialize parameters that may be/go lacking in header:
400         params().branchlist().clear();
401         params().options.erase();
402         params().float_placement.erase();
403         params().paperwidth.erase();
404         params().paperheight.erase();
405         params().leftmargin.erase();
406         params().rightmargin.erase();
407         params().topmargin.erase();
408         params().bottommargin.erase();
409         params().headheight.erase();
410         params().headsep.erase();
411         params().footskip.erase();
412
413         while (lex.isOK()) {
414                 lex.next();
415                 string const token = lex.getString();
416
417                 if (token.empty())
418                         continue;
419
420                 if (token == "\\end_header")
421                         break;
422
423                 ++line;
424                 if (token == "\\begin_header") {
425                         begin_header_line = line;
426                         continue;
427                 }
428
429                 lyxerr[Debug::PARSER] << "Handling header token: `"
430                                       << token << '\'' << endl;
431
432                 string unknown = params().readToken(lex, token);
433                 if (!unknown.empty()) {
434                         if (unknown[0] != '\\' && token == "\\textclass") {
435                                 unknownClass(unknown);
436                         } else {
437                                 ++unknown_tokens;
438                                 string const s = bformat(_("Unknown token: "
439                                                            "%1$s %2$s\n"),
440                                                          token,
441                                                          lex.getString());
442                                 error(ErrorItem(_("Header error"), s,
443                                                 -1, 0, 0));
444                         }
445                 }
446         }
447         if (begin_header_line) {
448                 string const s = _("\\begin_header is missing");
449                 error(ErrorItem(_("Header error"), s, -1, 0, 0));
450         }
451         return unknown_tokens;
452 }
453
454
455 // Uwe C. Schroeder
456 // changed to be public and have one parameter
457 // Returns false if "\end_document" is not read (Asger)
458 bool Buffer::readDocument(LyXLex & lex)
459 {
460         lex.next();
461         string const token = lex.getString();
462         if (token != "\\begin_document") {
463                 string const s = _("\\begin_document is missing");
464                 error(ErrorItem(_("Header error"), s, -1, 0, 0));
465         }
466
467         if (paragraphs().empty()) {
468                 readHeader(lex);
469                 if (!params().getLyXTextClass().load()) {
470                         string theclass = params().getLyXTextClass().name();
471                         Alert::error(_("Can't load document class"), bformat(
472                                         "Using the default document class, because the "
473                                         " class %1$s could not be loaded.", theclass));
474                         params().textclass = 0;
475                 }
476         } else {
477                 // We don't want to adopt the parameters from the
478                 // document we insert, so read them into a temporary buffer
479                 // and then discard it
480
481                 Buffer tmpbuf("", false);
482                 tmpbuf.readHeader(lex);
483         }
484
485         return text().read(*this, lex);
486 }
487
488
489 // needed to insert the selection
490 void Buffer::insertStringAsLines(ParagraphList & pars,
491         pit_type & pit, pos_type & pos,
492         LyXFont const & fn, string const & str, bool autobreakrows)
493 {
494         LyXFont font = fn;
495
496         pars[pit].checkInsertChar(font);
497         // insert the string, don't insert doublespace
498         bool space_inserted = true;
499         for (string::const_iterator cit = str.begin();
500             cit != str.end(); ++cit) {
501                 Paragraph & par = pars[pit];
502                 if (*cit == '\n') {
503                         if (autobreakrows && (!par.empty() || par.allowEmpty())) {
504                                 breakParagraph(params(), pars, pit, pos,
505                                                par.layout()->isEnvironment());
506                                 ++pit;
507                                 pos = 0;
508                                 space_inserted = true;
509                         } else {
510                                 continue;
511                         }
512                         // do not insert consecutive spaces if !free_spacing
513                 } else if ((*cit == ' ' || *cit == '\t') &&
514                            space_inserted && !par.isFreeSpacing()) {
515                         continue;
516                 } else if (*cit == '\t') {
517                         if (!par.isFreeSpacing()) {
518                                 // tabs are like spaces here
519                                 par.insertChar(pos, ' ', font);
520                                 ++pos;
521                                 space_inserted = true;
522                         } else {
523                                 const pos_type n = 8 - pos % 8;
524                                 for (pos_type i = 0; i < n; ++i) {
525                                         par.insertChar(pos, ' ', font);
526                                         ++pos;
527                                 }
528                                 space_inserted = true;
529                         }
530                 } else if (!IsPrintable(*cit)) {
531                         // Ignore unprintables
532                         continue;
533                 } else {
534                         // just insert the character
535                         par.insertChar(pos, *cit, font);
536                         ++pos;
537                         space_inserted = (*cit == ' ');
538                 }
539
540         }
541 }
542
543
544 bool Buffer::readFile(string const & filename)
545 {
546         // Check if the file is compressed.
547         string const format = getFormatFromContents(filename);
548         if (format == "gzip" || format == "zip" || format == "compress") {
549                 params().compressed = true;
550         }
551
552         // remove dummy empty par
553         paragraphs().clear();
554         bool ret = readFile(filename, paragraphs().size());
555
556         // After we have read a file, we must ensure that the buffer
557         // language is set and used in the gui.
558         // If you know of a better place to put this, please tell me. (Lgb)
559         updateDocLang(params().language);
560
561         return ret;
562 }
563
564
565 bool Buffer::readFile(string const & filename, pit_type const pit)
566 {
567         LyXLex lex(0, 0);
568         lex.setFile(filename);
569         return readFile(lex, filename, pit);
570 }
571
572
573 bool Buffer::fully_loaded() const
574 {
575         return pimpl_->file_fully_loaded;
576 }
577
578
579 void Buffer::fully_loaded(bool const value)
580 {
581         pimpl_->file_fully_loaded = value;
582 }
583
584
585 bool Buffer::readFile(LyXLex & lex, string const & filename, pit_type const pit)
586 {
587         BOOST_ASSERT(!filename.empty());
588
589         if (!lex.isOK()) {
590                 Alert::error(_("Document could not be read"),
591                              bformat(_("%1$s could not be read."), filename));
592                 return false;
593         }
594
595         lex.next();
596         string const token(lex.getString());
597
598         if (!lex.isOK()) {
599                 Alert::error(_("Document could not be read"),
600                              bformat(_("%1$s could not be read."), filename));
601                 return false;
602         }
603
604         // the first token _must_ be...
605         if (token != "\\lyxformat") {
606                 lyxerr << "Token: " << token << endl;
607
608                 Alert::error(_("Document format failure"),
609                              bformat(_("%1$s is not a LyX document."),
610                                        filename));
611                 return false;
612         }
613
614         lex.next();
615         string tmp_format = lex.getString();
616         //lyxerr << "LyX Format: `" << tmp_format << '\'' << endl;
617         // if present remove ".," from string.
618         string::size_type dot = tmp_format.find_first_of(".,");
619         //lyxerr << "           dot found at " << dot << endl;
620         if (dot != string::npos)
621                         tmp_format.erase(dot, 1);
622         int const file_format = convert<int>(tmp_format);
623         //lyxerr << "format: " << file_format << endl;
624
625         if (file_format != LYX_FORMAT) {
626                 string const tmpfile = tempName();
627                 if (tmpfile.empty()) {
628                         Alert::error(_("Conversion failed"),
629                                      bformat(_("%1$s is from an earlier"
630                                               " version of LyX, but a temporary"
631                                               " file for converting it could"
632                                               " not be created."),
633                                               filename));
634                         return false;
635                 }
636                 string command =
637                         "python " + LibFileSearch("lyx2lyx", "lyx2lyx");
638                 if (command.empty()) {
639                         Alert::error(_("Conversion script not found"),
640                                      bformat(_("%1$s is from an earlier"
641                                                " version of LyX, but the"
642                                                " conversion script lyx2lyx"
643                                                " could not be found."),
644                                                filename));
645                         return false;
646                 }
647                 command += " -t"
648                         + convert<string>(LYX_FORMAT)
649                         + " -o " + tmpfile + ' '
650                         + QuoteName(filename);
651                 lyxerr[Debug::INFO] << "Running '"
652                                     << command << '\''
653                                     << endl;
654                 cmd_ret const ret = RunCommand(command);
655                 if (ret.first != 0) {
656                         Alert::error(_("Conversion script failed"),
657                                      bformat(_("%1$s is from an earlier version"
658                                               " of LyX, but the lyx2lyx script"
659                                               " failed to convert it."),
660                                               filename));
661                         return false;
662                 } else {
663                         bool const ret = readFile(tmpfile, pit);
664                         // Do stuff with tmpfile name and buffer name here.
665                         return ret;
666                 }
667
668         }
669
670         if (readDocument(lex)) {
671                 Alert::error(_("Document format failure"),
672                              bformat(_("%1$s ended unexpectedly, which means"
673                                        " that it is probably corrupted."),
674                                        filename));
675         }
676
677         //lyxerr << "removing " << MacroTable::localMacros().size()
678         //      << " temporary macro entries" << endl;
679         //MacroTable::localMacros().clear();
680         params().setPaperStuff();
681
682         pimpl_->file_fully_loaded = true;
683         return true;
684 }
685
686
687 // Should probably be moved to somewhere else: BufferView? LyXView?
688 bool Buffer::save() const
689 {
690         // We don't need autosaves in the immediate future. (Asger)
691         resetAutosaveTimers();
692
693         // make a backup
694         string s;
695         if (lyxrc.make_backup) {
696                 s = fileName() + '~';
697                 if (!lyxrc.backupdir_path.empty())
698                         s = AddName(lyxrc.backupdir_path,
699                                     subst(os::internal_path(s),'/','!'));
700
701                 // It might very well be that this variant is just
702                 // good enough. (Lgb)
703                 // But to use this we need fs::copy_file to actually do a copy,
704                 // even when the target file exists. (Lgb)
705                 if (fs::exists(fileName())) {
706                   //try {
707                     fs::copy_file(fileName(), s, false);
708                     //}
709                     //catch (fs::filesystem_error const & fe) {
710                     //lyxerr << "LyX was not able to make backup copy. Beware.\n"
711                     //     << fe.what() << endl;
712                     //}
713                 }
714         }
715
716         if (writeFile(fileName())) {
717                 markClean();
718                 removeAutosaveFile(fileName());
719         } else {
720                 // Saving failed, so backup is not backup
721                 if (lyxrc.make_backup)
722                         rename(s, fileName());
723                 return false;
724         }
725         return true;
726 }
727
728
729 bool Buffer::writeFile(string const & fname) const
730 {
731         if (pimpl_->read_only && fname == fileName())
732                 return false;
733
734         bool retval = false;
735
736         if (params().compressed) {
737 #ifdef USE_COMPRESSION
738                 gz::ogzstream ofs(fname.c_str(), ios::out|ios::trunc);
739                 if (!ofs)
740                         return false;
741
742                 retval = do_writeFile(ofs);
743 #else
744                 return false;
745 #endif
746         } else {
747                 ofstream ofs(fname.c_str(), ios::out|ios::trunc);
748                 if (!ofs)
749                         return false;
750
751                 retval = do_writeFile(ofs);
752         }
753
754         return retval;
755 }
756
757
758 bool Buffer::do_writeFile(ostream & ofs) const
759 {
760 #ifdef HAVE_LOCALE
761         // Use the standard "C" locale for file output.
762         ofs.imbue(std::locale::classic());
763 #endif
764
765         // The top of the file should not be written by params().
766
767         // write out a comment in the top of the file
768         ofs << "#LyX " << lyx_version
769             << " created this file. For more info see http://www.lyx.org/\n"
770             << "\\lyxformat " << LYX_FORMAT << "\n"
771             << "\\begin_document\n";
772
773         // now write out the buffer parameters.
774         ofs << "\\begin_header\n";
775         params().writeFile(ofs);
776         ofs << "\\end_header\n";
777
778         // write the text
779         ofs << "\n\\begin_body\n";
780         text().write(*this, ofs);
781         ofs << "\n\\end_body\n";
782
783         // Write marker that shows file is complete
784         ofs << "\\end_document" << endl;
785
786         // Shouldn't really be needed....
787         //ofs.close();
788
789         // how to check if close went ok?
790         // Following is an attempt... (BE 20001011)
791
792         // good() returns false if any error occured, including some
793         //        formatting error.
794         // bad()  returns true if something bad happened in the buffer,
795         //        which should include file system full errors.
796
797         bool status = true;
798         if (!ofs) {
799                 status = false;
800                 lyxerr << "File was not closed properly." << endl;
801         }
802
803         return status;
804 }
805
806
807 void Buffer::makeLaTeXFile(string const & fname,
808                            string const & original_path,
809                            OutputParams const & runparams,
810                            bool output_preamble, bool output_body)
811 {
812         lyxerr[Debug::LATEX] << "makeLaTeXFile..." << endl;
813
814         ofstream ofs;
815         if (!openFileWrite(ofs, fname))
816                 return;
817
818         makeLaTeXFile(ofs, original_path,
819                       runparams, output_preamble, output_body);
820
821         ofs.close();
822         if (ofs.fail())
823                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
824 }
825
826
827 void Buffer::makeLaTeXFile(ostream & os,
828                            string const & original_path,
829                            OutputParams const & runparams_in,
830                            bool const output_preamble, bool const output_body)
831 {
832         OutputParams runparams = runparams_in;
833
834         // validate the buffer.
835         lyxerr[Debug::LATEX] << "  Validating buffer..." << endl;
836         LaTeXFeatures features(*this, params(), runparams.nice);
837         validate(features);
838         lyxerr[Debug::LATEX] << "  Buffer validation done." << endl;
839
840         texrow().reset();
841
842         // The starting paragraph of the coming rows is the
843         // first paragraph of the document. (Asger)
844         texrow().start(paragraphs().begin()->id(), 0);
845
846         if (output_preamble && runparams.nice) {
847                 os << "%% LyX " << lyx_version << " created this file.  "
848                         "For more info, see http://www.lyx.org/.\n"
849                         "%% Do not edit unless you really know what "
850                         "you are doing.\n";
851                 texrow().newline();
852                 texrow().newline();
853         }
854         lyxerr[Debug::INFO] << "lyx header finished" << endl;
855         // There are a few differences between nice LaTeX and usual files:
856         // usual is \batchmode and has a
857         // special input@path to allow the including of figures
858         // with either \input or \includegraphics (what figinsets do).
859         // input@path is set when the actual parameter
860         // original_path is set. This is done for usual tex-file, but not
861         // for nice-latex-file. (Matthias 250696)
862         // Note that input@path is only needed for something the user does
863         // in the preamble, included .tex files or ERT, files included by
864         // LyX work without it.
865         if (output_preamble) {
866                 if (!runparams.nice) {
867                         // code for usual, NOT nice-latex-file
868                         os << "\\batchmode\n"; // changed
869                         // from \nonstopmode
870                         texrow().newline();
871                 }
872                 if (!original_path.empty()) {
873                         string inputpath = os::external_path(original_path);
874                         subst(inputpath, "~", "\\string~");
875                         if (inputpath.find(' ') != string::npos)
876                                 inputpath = '"' + inputpath + '"';
877                         os << "\\makeatletter\n"
878                             << "\\def\\input@path{{"
879                             << inputpath << "/}}\n"
880                             << "\\makeatother\n";
881                         texrow().newline();
882                         texrow().newline();
883                         texrow().newline();
884                 }
885
886                 // Write the preamble
887                 runparams.use_babel = params().writeLaTeX(os, features, texrow());
888
889                 if (!output_body)
890                         return;
891
892                 // make the body.
893                 os << "\\begin{document}\n";
894                 texrow().newline();
895         } // output_preamble
896         lyxerr[Debug::INFO] << "preamble finished, now the body." << endl;
897
898         if (!lyxrc.language_auto_begin) {
899                 os << subst(lyxrc.language_command_begin, "$$lang",
900                              params().language->babel())
901                     << endl;
902                 texrow().newline();
903         }
904
905         // if we are doing a real file with body, even if this is the
906         // child of some other buffer, let's cut the link here.
907         // This happens for example if only a child document is printed.
908         string save_parentname;
909         if (output_preamble) {
910                 save_parentname = params().parentname;
911                 params().parentname.erase();
912         }
913
914         // the real stuff
915         latexParagraphs(*this, paragraphs(), os, texrow(), runparams);
916
917         // Restore the parenthood if needed
918         if (output_preamble)
919                 params().parentname = save_parentname;
920
921         // add this just in case after all the paragraphs
922         os << endl;
923         texrow().newline();
924
925         if (!lyxrc.language_auto_end) {
926                 os << subst(lyxrc.language_command_end, "$$lang",
927                              params().language->babel())
928                     << endl;
929                 texrow().newline();
930         }
931
932         if (output_preamble) {
933                 os << "\\end{document}\n";
934                 texrow().newline();
935
936                 lyxerr[Debug::LATEX] << "makeLaTeXFile...done" << endl;
937         } else {
938                 lyxerr[Debug::LATEX] << "LaTeXFile for inclusion made."
939                                      << endl;
940         }
941
942         // Just to be sure. (Asger)
943         texrow().newline();
944
945         lyxerr[Debug::INFO] << "Finished making LaTeX file." << endl;
946         lyxerr[Debug::INFO] << "Row count was " << texrow().rows() - 1
947                             << '.' << endl;
948 }
949
950
951 bool Buffer::isLatex() const
952 {
953         return params().getLyXTextClass().outputType() == LATEX;
954 }
955
956
957 bool Buffer::isLinuxDoc() const
958 {
959         return params().getLyXTextClass().outputType() == LINUXDOC;
960 }
961
962
963 bool Buffer::isLiterate() const
964 {
965         return params().getLyXTextClass().outputType() == LITERATE;
966 }
967
968
969 bool Buffer::isDocBook() const
970 {
971         return params().getLyXTextClass().outputType() == DOCBOOK;
972 }
973
974
975 bool Buffer::isSGML() const
976 {
977         LyXTextClass const & tclass = params().getLyXTextClass();
978
979         return tclass.outputType() == LINUXDOC ||
980                tclass.outputType() == DOCBOOK;
981 }
982
983
984 void Buffer::makeLinuxDocFile(string const & fname,
985                               OutputParams const & runparams,
986                               bool const body_only)
987 {
988         ofstream ofs;
989         if (!openFileWrite(ofs, fname))
990                 return;
991
992         LaTeXFeatures features(*this, params(), runparams.nice);
993         validate(features);
994
995         texrow().reset();
996
997         LyXTextClass const & tclass = params().getLyXTextClass();
998
999         string const & top_element = tclass.latexname();
1000
1001         if (!body_only) {
1002                 ofs << tclass.class_header();
1003
1004                 string preamble = params().preamble;
1005                 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1006                          : fname;
1007                 preamble += features.getIncludedFiles(name);
1008                 preamble += features.getLyXSGMLEntities();
1009
1010                 if (!preamble.empty()) {
1011                         ofs << " [ " << preamble << " ]";
1012                 }
1013                 ofs << ">\n\n";
1014
1015                 if (params().options.empty())
1016                         sgml::openTag(ofs, top_element);
1017                 else {
1018                         string top = top_element;
1019                         top += ' ';
1020                         top += params().options;
1021                         sgml::openTag(ofs, top);
1022                 }
1023         }
1024
1025         ofs << "<!-- LyX "  << lyx_version
1026             << " created this file. For more info see http://www.lyx.org/"
1027             << " -->\n";
1028
1029         linuxdocParagraphs(*this, paragraphs(), ofs, runparams);
1030
1031         if (!body_only) {
1032                 ofs << "\n\n";
1033                 sgml::closeTag(ofs, top_element);
1034         }
1035
1036         ofs.close();
1037         if (ofs.fail())
1038                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1039 }
1040
1041
1042 void Buffer::makeDocBookFile(string const & fname,
1043                              OutputParams const & runparams,
1044                              bool const only_body)
1045 {
1046         ofstream ofs;
1047         if (!openFileWrite(ofs, fname))
1048                 return;
1049
1050         LaTeXFeatures features(*this, params(), runparams.nice);
1051         validate(features);
1052
1053         texrow().reset();
1054
1055         LyXTextClass const & tclass = params().getLyXTextClass();
1056         string const & top_element = tclass.latexname();
1057
1058         if (!only_body) {
1059                 if (runparams.flavor == OutputParams::XML)
1060                         ofs << "<?xml version=\"1.0\" encoding=\""
1061                             << params().language->encoding()->Name() << "\"?>\n";
1062
1063                 ofs << "<!DOCTYPE " << top_element << " ";
1064
1065                 if (! tclass.class_header().empty()) ofs << tclass.class_header();
1066                 else if (runparams.flavor == OutputParams::XML)
1067                         ofs << "PUBLIC \"-//OASIS//DTD DocBook XML//EN\" "
1068                             << "\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\"";
1069                 else
1070                         ofs << " PUBLIC \"-//OASIS//DTD DocBook V4.2//EN\"";
1071
1072                 string preamble = params().preamble;
1073                 if (runparams.flavor != OutputParams::XML ) {
1074                         preamble += "<!ENTITY % output.print.png \"IGNORE\">\n";
1075                         preamble += "<!ENTITY % output.print.pdf \"IGNORE\">\n";
1076                         preamble += "<!ENTITY % output.print.eps \"IGNORE\">\n";
1077                         preamble += "<!ENTITY % output.print.bmp \"IGNORE\">\n";
1078                 }
1079
1080                 string const name = runparams.nice ? ChangeExtension(pimpl_->filename, ".sgml")
1081                          : fname;
1082                 preamble += features.getIncludedFiles(name);
1083                 preamble += features.getLyXSGMLEntities();
1084
1085                 if (!preamble.empty()) {
1086                         ofs << "\n [ " << preamble << " ]";
1087                 }
1088                 ofs << ">\n\n";
1089         }
1090
1091         string top = top_element;
1092         top += " lang=\"";
1093         if (runparams.flavor == OutputParams::XML)
1094                 top += params().language->code();
1095         else
1096                 top += params().language->code().substr(0,2);
1097         top += '"';
1098
1099         if (!params().options.empty()) {
1100                 top += ' ';
1101                 top += params().options;
1102         }
1103
1104         ofs << "<!-- " << ((runparams.flavor == OutputParams::XML)? "XML" : "SGML")
1105             << " file was created by LyX " << lyx_version
1106             << "\n  See http://www.lyx.org/ for more information -->\n";
1107
1108         params().getLyXTextClass().counters().reset();
1109
1110         sgml::openTag(ofs, top);
1111         ofs << '\n';
1112         docbookParagraphs(paragraphs(), *this, ofs, runparams);
1113         sgml::closeTag(ofs, top_element);
1114
1115         ofs.close();
1116         if (ofs.fail())
1117                 lyxerr << "File '" << fname << "' was not closed properly." << endl;
1118 }
1119
1120
1121 // chktex should be run with these flags disabled: 3, 22, 25, 30, 38(?)
1122 // Other flags: -wall -v0 -x
1123 int Buffer::runChktex()
1124 {
1125         busy(true);
1126
1127         // get LaTeX-Filename
1128         string const name = getLatexName();
1129         string const path = temppath();
1130         string const org_path = filePath();
1131
1132         Path p(path); // path to LaTeX file
1133         message(_("Running chktex..."));
1134
1135         // Generate the LaTeX file if neccessary
1136         OutputParams runparams;
1137         runparams.flavor = OutputParams::LATEX;
1138         runparams.nice = false;
1139         makeLaTeXFile(name, org_path, runparams);
1140
1141         TeXErrors terr;
1142         Chktex chktex(lyxrc.chktex_command, name, filePath());
1143         int const res = chktex.run(terr); // run chktex
1144
1145         if (res == -1) {
1146                 Alert::error(_("chktex failure"),
1147                              _("Could not run chktex successfully."));
1148         } else if (res > 0) {
1149                 // Insert all errors as errors boxes
1150                 bufferErrors(*this, terr);
1151         }
1152
1153         busy(false);
1154
1155         return res;
1156 }
1157
1158
1159 void Buffer::validate(LaTeXFeatures & features) const
1160 {
1161         LyXTextClass const & tclass = params().getLyXTextClass();
1162
1163         if (features.isAvailable("dvipost") && params().tracking_changes
1164                 && params().output_changes) {
1165                 features.require("dvipost");
1166                 features.require("color");
1167         }
1168
1169         // AMS Style is at document level
1170         if (params().use_amsmath == BufferParams::AMS_ON
1171             || tclass.provides(LyXTextClass::amsmath))
1172                 features.require("amsmath");
1173
1174         for_each(paragraphs().begin(), paragraphs().end(),
1175                  boost::bind(&Paragraph::validate, _1, boost::ref(features)));
1176
1177         // the bullet shapes are buffer level not paragraph level
1178         // so they are tested here
1179         for (int i = 0; i < 4; ++i) {
1180                 if (params().user_defined_bullet(i) != ITEMIZE_DEFAULTS[i]) {
1181                         int const font = params().user_defined_bullet(i).getFont();
1182                         if (font == 0) {
1183                                 int const c = params()
1184                                         .user_defined_bullet(i)
1185                                         .getCharacter();
1186                                 if (c == 16
1187                                    || c == 17
1188                                    || c == 25
1189                                    || c == 26
1190                                    || c == 31) {
1191                                         features.require("latexsym");
1192                                 }
1193                         } else if (font == 1) {
1194                                 features.require("amssymb");
1195                         } else if ((font >= 2 && font <= 5)) {
1196                                 features.require("pifont");
1197                         }
1198                 }
1199         }
1200
1201         if (lyxerr.debugging(Debug::LATEX)) {
1202                 features.showStruct();
1203         }
1204 }
1205
1206
1207 void Buffer::getLabelList(vector<string> & list) const
1208 {
1209         /// if this is a child document and the parent is already loaded
1210         /// Use the parent's list instead  [ale990407]
1211         Buffer const * tmp = getMasterBuffer();
1212         if (!tmp) {
1213                 lyxerr << "getMasterBuffer() failed!" << endl;
1214                 BOOST_ASSERT(tmp);
1215         }
1216         if (tmp != this) {
1217                 tmp->getLabelList(list);
1218                 return;
1219         }
1220
1221         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it)
1222                 it.nextInset()->getLabelList(*this, list);
1223 }
1224
1225
1226 // This is also a buffer property (ale)
1227 void Buffer::fillWithBibKeys(vector<pair<string, string> > & keys)
1228         const
1229 {
1230         /// if this is a child document and the parent is already loaded
1231         /// use the parent's list instead  [ale990412]
1232         Buffer const * tmp = getMasterBuffer();
1233         BOOST_ASSERT(tmp);
1234         if (tmp != this) {
1235                 tmp->fillWithBibKeys(keys);
1236                 return;
1237         }
1238
1239         for (InsetIterator it = inset_iterator_begin(inset()); it; ++it) {
1240                 if (it->lyxCode() == InsetBase::BIBTEX_CODE) {
1241                         InsetBibtex const & inset =
1242                                 dynamic_cast<InsetBibtex const &>(*it);
1243                         inset.fillWithBibKeys(*this, keys);
1244                 } else if (it->lyxCode() == InsetBase::INCLUDE_CODE) {
1245                         InsetInclude const & inset =
1246                                 dynamic_cast<InsetInclude const &>(*it);
1247                         inset.fillWithBibKeys(*this, keys);
1248                 } else if (it->lyxCode() == InsetBase::BIBITEM_CODE) {
1249                         InsetBibitem const & inset =
1250                                 dynamic_cast<InsetBibitem const &>(*it);
1251                         string const key = inset.getContents();
1252                         string const opt = inset.getOptions();
1253                         string const ref; // = pit->asString(this, false);
1254                         string const info = opt + "TheBibliographyRef" + ref;
1255                         keys.push_back(pair<string, string>(key, info));
1256                 }
1257         }
1258 }
1259
1260
1261 bool Buffer::isDepClean(string const & name) const
1262 {
1263         DepClean::const_iterator const it = pimpl_->dep_clean.find(name);
1264         if (it == pimpl_->dep_clean.end())
1265                 return true;
1266         return it->second;
1267 }
1268
1269
1270 void Buffer::markDepClean(string const & name)
1271 {
1272         pimpl_->dep_clean[name] = true;
1273 }
1274
1275
1276 bool Buffer::dispatch(string const & command, bool * result)
1277 {
1278         return dispatch(lyxaction.lookupFunc(command), result);
1279 }
1280
1281
1282 bool Buffer::dispatch(FuncRequest const & func, bool * result)
1283 {
1284         bool dispatched = true;
1285
1286         switch (func.action) {
1287                 case LFUN_EXPORT: {
1288                         bool const tmp = Exporter::Export(this, func.argument, false);
1289                         if (result)
1290                                 *result = tmp;
1291                         break;
1292                 }
1293
1294                 default:
1295                         dispatched = false;
1296         }
1297         return dispatched;
1298 }
1299
1300
1301 void Buffer::changeLanguage(Language const * from, Language const * to)
1302 {
1303         BOOST_ASSERT(from);
1304         BOOST_ASSERT(to);
1305
1306         lyxerr << "Changing Language!" << endl;
1307
1308         // Take care of l10n/i18n
1309         updateDocLang(to);
1310
1311         for_each(par_iterator_begin(),
1312                  par_iterator_end(),
1313                  bind(&Paragraph::changeLanguage, _1, params(), from, to));
1314 }
1315
1316
1317 void Buffer::updateDocLang(Language const * nlang)
1318 {
1319         BOOST_ASSERT(nlang);
1320
1321         pimpl_->messages.reset(new Messages(nlang->code()));
1322 }
1323
1324
1325 bool Buffer::isMultiLingual() const
1326 {
1327         ParConstIterator end = par_iterator_end();
1328         for (ParConstIterator it = par_iterator_begin(); it != end; ++it)
1329                 if (it->isMultiLingual(params()))
1330                         return true;
1331
1332         return false;
1333 }
1334
1335
1336 ParIterator Buffer::getParFromID(int const id) const
1337 {
1338         ParConstIterator it = par_iterator_begin();
1339         ParConstIterator const end = par_iterator_end();
1340
1341         if (id < 0) {
1342                 // John says this is called with id == -1 from undo
1343                 lyxerr << "getParFromID(), id: " << id << endl;
1344                 return end;
1345         }
1346
1347         for (; it != end; ++it)
1348                 if (it->id() == id)
1349                         return it;
1350
1351         return end;
1352 }
1353
1354
1355 bool Buffer::hasParWithID(int const id) const
1356 {
1357         ParConstIterator const it = getParFromID(id);
1358         return it != par_iterator_end();
1359 }
1360
1361
1362 ParIterator Buffer::par_iterator_begin()
1363 {
1364         return ::par_iterator_begin(inset());
1365 }
1366
1367
1368 ParIterator Buffer::par_iterator_end()
1369 {
1370         return ::par_iterator_end(inset());
1371 }
1372
1373
1374 ParConstIterator Buffer::par_iterator_begin() const
1375 {
1376         return ::par_const_iterator_begin(inset());
1377 }
1378
1379
1380 ParConstIterator Buffer::par_iterator_end() const
1381 {
1382         return ::par_const_iterator_end(inset());
1383 }
1384
1385
1386 Language const * Buffer::getLanguage() const
1387 {
1388         return params().language;
1389 }
1390
1391
1392 string const Buffer::B_(string const & l10n) const
1393 {
1394         if (pimpl_->messages.get()) {
1395                 return pimpl_->messages->get(l10n);
1396         }
1397
1398         return _(l10n);
1399 }
1400
1401
1402 bool Buffer::isClean() const
1403 {
1404         return pimpl_->lyx_clean;
1405 }
1406
1407
1408 bool Buffer::isBakClean() const
1409 {
1410         return pimpl_->bak_clean;
1411 }
1412
1413
1414 void Buffer::markClean() const
1415 {
1416         if (!pimpl_->lyx_clean) {
1417                 pimpl_->lyx_clean = true;
1418                 updateTitles();
1419         }
1420         // if the .lyx file has been saved, we don't need an
1421         // autosave
1422         pimpl_->bak_clean = true;
1423 }
1424
1425
1426 void Buffer::markBakClean()
1427 {
1428         pimpl_->bak_clean = true;
1429 }
1430
1431
1432 void Buffer::setUnnamed(bool flag)
1433 {
1434         pimpl_->unnamed = flag;
1435 }
1436
1437
1438 bool Buffer::isUnnamed() const
1439 {
1440         return pimpl_->unnamed;
1441 }
1442
1443
1444 #ifdef WITH_WARNINGS
1445 #warning this function should be moved to buffer_pimpl.C
1446 #endif
1447 void Buffer::markDirty()
1448 {
1449         if (pimpl_->lyx_clean) {
1450                 pimpl_->lyx_clean = false;
1451                 updateTitles();
1452         }
1453         pimpl_->bak_clean = false;
1454
1455         DepClean::iterator it = pimpl_->dep_clean.begin();
1456         DepClean::const_iterator const end = pimpl_->dep_clean.end();
1457
1458         for (; it != end; ++it) {
1459                 it->second = false;
1460         }
1461 }
1462
1463
1464 string const & Buffer::fileName() const
1465 {
1466         return pimpl_->filename;
1467 }
1468
1469
1470 string const & Buffer::filePath() const
1471 {
1472         return pimpl_->filepath;
1473 }
1474
1475
1476 bool Buffer::isReadonly() const
1477 {
1478         return pimpl_->read_only;
1479 }
1480
1481
1482 void Buffer::setParentName(string const & name)
1483 {
1484         params().parentname = name;
1485 }
1486
1487
1488 Buffer const * Buffer::getMasterBuffer() const
1489 {
1490         if (!params().parentname.empty()
1491             && bufferlist.exists(params().parentname)) {
1492                 Buffer const * buf = bufferlist.getBuffer(params().parentname);
1493                 if (buf)
1494                         return buf->getMasterBuffer();
1495         }
1496
1497         return this;
1498 }
1499
1500
1501 MacroData const & Buffer::getMacro(std::string const & name) const
1502 {
1503         return pimpl_->macros.get(name);
1504 }
1505
1506
1507 bool Buffer::hasMacro(string const & name) const
1508 {
1509         return pimpl_->macros.has(name);
1510 }
1511
1512
1513 void Buffer::insertMacro(string const & name, MacroData const & data)
1514 {
1515         MacroTable::globalMacros().insert(name, data);
1516         pimpl_->macros.insert(name, data);
1517 }
1518
1519
1520 void Buffer::buildMacros()
1521 {
1522         // Start with global table.
1523         pimpl_->macros = MacroTable::globalMacros();
1524
1525         // Now add our own.
1526         ParagraphList & pars = text().paragraphs();
1527         for (size_t i = 0, n = pars.size(); i != n; ++i) {
1528                 //lyxerr << "searching main par " << i
1529                 //      << " for macro definitions" << std::endl;
1530                 InsetList::iterator it = pars[i].insetlist.begin();
1531                 InsetList::iterator end = pars[i].insetlist.end();
1532                 for ( ; it != end; ++it) {
1533                         //lyxerr << "found inset code " << it->inset->lyxCode() << std::endl;
1534                         if (it->inset->lyxCode() == InsetBase::MATHMACRO_CODE) {
1535                                 MathMacroTemplate & mac
1536                                         = static_cast<MathMacroTemplate &>(*it->inset);
1537                                 insertMacro(mac.name(), mac.asMacroData());
1538                         }
1539                 }
1540         }
1541 }