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