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