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