]> git.lyx.org Git - lyx.git/blob - src/Buffer.h
cosmetics. mainly replace #include "dostring.h" by #include "strfwd.h"
[lyx.git] / src / Buffer.h
1 // -*- C++ -*-
2 /**
3  * \file Buffer.h
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Lars Gullik Bjønnes
8  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #ifndef BUFFER_H
13 #define BUFFER_H
14
15 #include "insets/InsetCode.h"
16
17 #include "support/FileName.h"
18 #include "support/strfwd.h"
19 #include "support/types.h"
20
21 #include <string>
22 #include <vector>
23
24
25 namespace lyx {
26
27 class BufferParams;
28 class EmbeddedFiles;
29 class ErrorItem;
30 class ErrorList;
31 class FuncRequest;
32 class Inset;
33 class Font;
34 class Format;
35 class Lexer;
36 class LyXRC;
37 class Text;
38 class LyXVC;
39 class LaTeXFeatures;
40 class Language;
41 class MacroData;
42 class OutputParams;
43 class Paragraph;
44 class ParConstIterator;
45 class ParIterator;
46 class ParagraphList;
47 class TeXErrors;
48 class TexRow;
49 class TocBackend;
50 class Undo;
51
52 namespace frontend {
53 class GuiBufferDelegate;
54 class WorkAreaManager;
55 }
56
57 /** The buffer object.
58  * This is the buffer object. It contains all the informations about
59  * a document loaded into LyX.
60  * The buffer object owns the Text (wrapped in an InsetText), which
61  * contains the individual paragraphs of the document.
62  *
63  *
64  * I am not sure if the class is complete or
65  * minimal, probably not.
66  * \author Lars Gullik Bjønnes
67  */
68 class Buffer {
69 public:
70         /// What type of log will \c getLogName() return?
71         enum LogType {
72                 latexlog, ///< LaTeX log
73                 buildlog  ///< Literate build log
74         };
75
76         /// Result of \c readFile()
77         enum ReadStatus {
78                 failure, ///< The file could not be read
79                 success, ///< The file could not be read
80                 wrongversion ///< The version of the file does not match ours
81         };
82
83         /// Method to check if a file is externally modified, used by 
84         /// isExternallyModified()
85         /**
86          * timestamp is fast but inaccurate. For example, the granularity
87          * of timestamp on a FAT filesystem is 2 second. Also, various operations
88          * may touch the timestamp of a file even when its content is unchanged.
89          *
90          * checksum is accurate but slow, which can be a problem when it is 
91          * frequently used, or used for a large file on a slow (network) file
92          * system.
93          */
94         enum CheckMethod {
95                 checksum_method,  ///< Use file check sum
96                 timestamp_method, ///< Use timestamp, and checksum if timestamp has changed
97         };
98         
99         /** Constructor
100             \param file
101             \param b  optional \c false by default
102         */
103         explicit Buffer(std::string const & file, bool b = false);
104
105         /// Destructor
106         ~Buffer();
107
108         /** High-level interface to buffer functionality.
109             This function parses a command string and executes it
110         */
111         bool dispatch(std::string const & command, bool * result = 0);
112
113         /// Maybe we know the function already by number...
114         bool dispatch(FuncRequest const & func, bool * result = 0);
115
116         /// Load the autosaved file.
117         void loadAutoSaveFile();
118
119         /// read a new document from a string
120         bool readString(std::string const &);
121         /// load a new file
122         bool readFile(support::FileName const & filename);
123
124         /// read the header, returns number of unknown tokens
125         int readHeader(Lexer & lex);
126
127         /** Reads a file without header.
128             \param par if != 0 insert the file.
129             \return \c false if file is not completely read.
130         */
131         bool readDocument(Lexer &);
132
133         ///
134         void insertStringAsLines(ParagraphList & plist,
135                 pit_type &, pos_type &,
136                 Font const &, docstring const &, bool);
137         ///
138         ParIterator getParFromID(int id) const;
139         /// do we have a paragraph with this id?
140         bool hasParWithID(int id) const;
141
142         ///
143         frontend::WorkAreaManager & workAreaManager() const;
144
145         /** Save file.
146             Takes care of auto-save files and backup file if requested.
147             Returns \c true if the save is successful, \c false otherwise.
148         */
149         bool save() const;
150
151         /// Write document to stream. Returns \c false if unsuccesful.
152         bool write(std::ostream &) const;
153         /// Write file. Returns \c false if unsuccesful.
154         bool writeFile(support::FileName const &) const;
155
156   /// Loads LyX file \c filename into buffer, *  and \return success 
157         bool loadLyXFile(support::FileName const & s);
158
159         /// Fill in the ErrorList with the TeXErrors
160         void bufferErrors(TeXErrors const &, ErrorList &) const;
161
162         /// Just a wrapper for writeLaTeXSource, first creating the ofstream.
163         bool makeLaTeXFile(support::FileName const & filename,
164                            std::string const & original_path,
165                            OutputParams const &,
166                            bool output_preamble = true,
167                            bool output_body = true);
168         /** Export the buffer to LaTeX.
169             If \p os is a file stream, and params().inputenc is "auto" or
170             "default", and the buffer contains text in different languages
171             with more than one encoding, then this method will change the
172             encoding associated to \p os. Therefore you must not call this
173             method with a string stream if the output is supposed to go to a
174             file. \code
175             odocfstream ofs;
176             ofs.open("test.tex");
177             writeLaTeXSource(ofs, ...);
178             ofs.close();
179             \endcode is NOT equivalent to \code
180             odocstringstream oss;
181             writeLaTeXSource(oss, ...);
182             odocfstream ofs;
183             ofs.open("test.tex");
184             ofs << oss.str();
185             ofs.close();
186             \endcode
187          */
188         void writeLaTeXSource(odocstream & os,
189                            std::string const & original_path,
190                            OutputParams const &,
191                            bool output_preamble = true,
192                            bool output_body = true);
193         ///
194         void makeDocBookFile(support::FileName const & filename,
195                              OutputParams const & runparams_in,
196                              bool only_body = false);
197         ///
198         void writeDocBookSource(odocstream & os, std::string const & filename,
199                              OutputParams const & runparams_in,
200                              bool only_body = false);
201         /// returns the main language for the buffer (document)
202         Language const * language() const;
203         /// get l10n translated to the buffers language
204         docstring const B_(std::string const & l10n) const;
205
206         ///
207         int runChktex();
208         /// return true if the main lyx file does not need saving
209         bool isClean() const;
210         ///
211         bool isBakClean() const;
212         ///
213         bool isDepClean(std::string const & name) const;
214
215         /// whether or not disk file has been externally modified
216         bool isExternallyModified(CheckMethod method) const;
217
218         /// save timestamp and checksum of the given file.
219         void saveCheckSum(support::FileName const & file) const;
220
221         /// mark the main lyx file as not needing saving
222         void markClean() const;
223
224         ///
225         void markBakClean() const;
226
227         ///
228         void markDepClean(std::string const & name);
229
230         ///
231         void setUnnamed(bool flag = true);
232
233         ///
234         bool isUnnamed() const;
235
236         /// Mark this buffer as dirty.
237         void markDirty();
238
239         /// Returns the buffer's filename. It is always an absolute path.
240         std::string absFileName() const;
241
242         /// Returns the the path where the buffer lives.
243         /// It is always an absolute path.
244         std::string const & filePath() const;
245
246         /** A transformed version of the file name, adequate for LaTeX.
247             \param no_path optional if \c true then the path is stripped.
248         */
249         std::string latexName(bool no_path = true) const;
250
251         /// Get thee name and type of the log.
252         std::string logName(LogType * type = 0) const;
253
254         /// Change name of buffer. Updates "read-only" flag.
255         void setFileName(std::string const & newfile);
256
257         /// Name of the document's parent
258         void setParentName(std::string const &);
259
260         /** Get the document's master (or \c this if this is not a
261             child document)
262          */
263         Buffer const * masterBuffer() const;
264         /** Get the document's master (or \c this if this is not a
265             child document)
266          */
267         Buffer * masterBuffer();
268
269         /// Is buffer read-only?
270         bool isReadonly() const;
271
272         /// Set buffer read-only flag
273         void setReadonly(bool flag = true);
274
275         /// returns \c true if the buffer contains a LaTeX document
276         bool isLatex() const;
277         /// returns \c true if the buffer contains a DocBook document
278         bool isDocBook() const;
279         /// returns \c true if the buffer contains a Wed document
280         bool isLiterate() const;
281
282         /** Validate a buffer for LaTeX.
283             This validates the buffer, and returns a struct for use by
284             #makeLaTeX# and others. Its main use is to figure out what
285             commands and packages need to be included in the LaTeX file.
286             It (should) also check that the needed constructs are there
287             (i.e. that the \refs points to coresponding \labels). It
288             should perhaps inset "error" insets to help the user correct
289             obvious mistakes.
290         */
291         void validate(LaTeXFeatures &) const;
292
293         /// Update the cache with all bibfiles in use (including bibfiles
294         /// of loaded child documents).
295         void updateBibfilesCache();
296         /// Return the cache with all bibfiles in use (including bibfiles
297         /// of loaded child documents).
298         std::vector<support::FileName> const & getBibfilesCache() const;
299         ///
300         void getLabelList(std::vector<docstring> &) const;
301
302         ///
303         void changeLanguage(Language const * from, Language const * to);
304
305         ///
306         bool isMultiLingual() const;
307
308         ///
309         BufferParams & params();
310         BufferParams const & params() const;
311
312         /** The list of paragraphs.
313             This is a linked list of paragraph, this list holds the
314             whole contents of the document.
315          */
316         ParagraphList & paragraphs();
317         ParagraphList const & paragraphs() const;
318
319         /// LyX version control object.
320         LyXVC & lyxvc();
321         LyXVC const & lyxvc() const;
322
323         /// Where to put temporary files.
324         std::string const & temppath() const;
325
326         /// Used when typesetting to place errorboxes.
327         TexRow & texrow();
328         TexRow const & texrow() const;
329
330         ///
331         ParIterator par_iterator_begin();
332         ///
333         ParConstIterator par_iterator_begin() const;
334         ///
335         ParIterator par_iterator_end();
336         ///
337         ParConstIterator par_iterator_end() const;
338
339         /** \returns true only when the file is fully loaded.
340          *  Used to prevent the premature generation of previews
341          *  and by the citation inset.
342          */
343         bool isFullyLoaded() const;
344         /// Set by buffer_funcs' newFile.
345         void setFullyLoaded(bool);
346
347         /// Our main text (inside the top InsetText)
348         Text & text() const;
349
350         /// Our top InsetText
351         Inset & inset() const;
352
353         //
354         // Macro handling
355         //
356         /// Collect macros in paragraphs
357         void updateMacros();
358         /// Look for macro defined before par (or in the master buffer)
359         bool hasMacro(docstring const & name, Paragraph const & par) const;
360         /// Look for macro defined anywhere in the buffer (or in the master buffer)
361         bool hasMacro(docstring const & name) const;
362         /// Return macro defined before par (or in the master buffer)
363         MacroData const & getMacro(docstring const & name, Paragraph const & par) const;
364         /// Return macro defined anywhere in the buffer (or in the master buffer)
365         MacroData const & getMacro(docstring const & name) const;
366
367         /// Replace the inset contents for insets which InsetCode is equal
368         /// to the passed \p inset_code.
369         void changeRefsIfUnique(docstring const & from, docstring const & to,
370                 InsetCode code);
371
372         /// get source code (latex/docbook) for some paragraphs, or all paragraphs
373         /// including preamble
374         void getSourceCode(odocstream & os, pit_type par_begin, pit_type par_end,
375                 bool full_source);
376
377         /// Access to error list
378         ErrorList const & errorList(std::string const & type) const;
379         ErrorList & errorList(std::string const & type);
380
381         //@{
382         TocBackend & tocBackend();
383         TocBackend const & tocBackend() const;
384         //@}
385         
386         //@{
387         EmbeddedFiles & embeddedFiles();
388         EmbeddedFiles const & embeddedFiles() const;
389         //@}
390
391         Undo & undo();
392        
393         /// This function is called when the buffer is changed.
394         void changed() const;
395         /// This function is called when the buffer structure is changed.
396         void structureChanged() const;
397         /// This function is called when some parsing error shows up.
398         void errors(std::string const & err) const;
399         /// This function is called when the buffer busy status change.
400         void setBusy(bool on) const;
401         /// This function is called when the buffer readonly status change.
402         void setReadOnly(bool on) const;
403         /// Update window titles of all users.
404         void updateTitles() const;
405         /// Reset autosave timers for all users.
406         void resetAutosaveTimers() const;
407         ///
408         void message(docstring const & msg) const;
409
410         void setGuiDelegate(frontend::GuiBufferDelegate * gui);
411
412         ///
413         void autoSave() const;
414         ///
415         bool writeAs(std::string const & newname = std::string());
416         ///
417         bool menuWrite();
418         ///
419         void loadChildDocuments() const;
420         /// return the format of the buffer on a string
421         std::string bufferFormat() const;
422
423         ///
424         bool doExport(std::string const & format, bool put_in_tempdir,
425                 std::string & result_file);
426         ///
427         bool doExport(std::string const & format, bool put_in_tempdir);
428         ///
429         bool preview(std::string const & format);
430         ///
431         bool isExportable(std::string const & format) const;
432         ///
433         std::vector<Format const *> exportableFormats(bool only_viewable) const;
434
435 private:
436   /// 
437         bool readFileHelper(support::FileName const & s);
438         ///
439         std::vector<std::string> backends() const;
440         /** Inserts a file into a document
441             \return \c false if method fails.
442         */
443         ReadStatus readFile(Lexer &, support::FileName const & filename,
444                             bool fromString = false);
445
446         /// Use the Pimpl idiom to hide the internals.
447         class Impl;
448         /// The pointer never changes although *pimpl_'s contents may.
449         Impl * const pimpl_;
450
451         /// A cache for the bibfiles (including bibfiles of loaded child
452         /// documents), needed for appropriate update of natbib labels.
453         mutable std::vector<support::FileName> bibfilesCache_;
454
455         frontend::GuiBufferDelegate * gui_;
456 };
457
458
459 } // namespace lyx
460
461 #endif