buffer: Add WITH_BUFFER macro to simplify global buffer modification

Most internal functions to modify buffers operate on the current buffer and
require temporary switchs. This macro is a temporary workaround until a cleaner
refactoring of the internal API is performed.
This commit is contained in:
Thiago de Arruda 2015-03-05 18:07:09 -03:00
parent 2b90aed831
commit 8b6b06c2e0
2 changed files with 41 additions and 28 deletions

View File

@ -553,34 +553,6 @@ Dictionary api_metadata(void)
return copy_object(DICTIONARY_OBJ(metadata)).data.dictionary;
}
// Find a window that contains "buf" and switch to it.
// If there is no such window, use the current window and change "curbuf".
// Caller must initialize save_curbuf to NULL.
// restore_win_for_buf() MUST be called later!
void switch_to_win_for_buf(buf_T *buf,
win_T **save_curwinp,
tabpage_T **save_curtabp,
buf_T **save_curbufp)
{
win_T *wp;
tabpage_T *tp;
if (!find_win_for_buf(buf, &wp, &tp)
|| switch_win(save_curwinp, save_curtabp, wp, tp, true) == FAIL)
switch_buffer(save_curbufp, buf);
}
void restore_win_for_buf(win_T *save_curwin,
tabpage_T *save_curtab,
buf_T *save_curbuf)
{
if (save_curbuf == NULL) {
restore_win(save_curwin, save_curtab, true);
} else {
restore_buffer(save_curbuf);
}
}
static void init_error_type_metadata(Dictionary *metadata)
{
Dictionary types = ARRAY_DICT_INIT;

View File

@ -1,6 +1,7 @@
#ifndef NVIM_BUFFER_H
#define NVIM_BUFFER_H
#include "nvim/window.h"
#include "nvim/pos.h" // for linenr_T
#include "nvim/ex_cmds_defs.h" // for exarg_T
@ -45,4 +46,44 @@ enum bfa_values {
#ifdef INCLUDE_GENERATED_DECLARATIONS
# include "buffer.h.generated.h"
#endif
// Find a window that contains "buf" and switch to it.
// If there is no such window, use the current window and change "curbuf".
// Caller must initialize save_curbuf to NULL.
// restore_win_for_buf() MUST be called later!
static inline void switch_to_win_for_buf(buf_T *buf,
win_T **save_curwinp,
tabpage_T **save_curtabp,
buf_T **save_curbufp)
{
win_T *wp;
tabpage_T *tp;
if (!find_win_for_buf(buf, &wp, &tp)
|| switch_win(save_curwinp, save_curtabp, wp, tp, true) == FAIL)
switch_buffer(save_curbufp, buf);
}
static inline void restore_win_for_buf(win_T *save_curwin,
tabpage_T *save_curtab,
buf_T *save_curbuf)
{
if (save_curbuf == NULL) {
restore_win(save_curwin, save_curtab, true);
} else {
restore_buffer(save_curbuf);
}
}
#define WITH_BUFFER(b, code) \
do { \
buf_T *save_curbuf = NULL; \
win_T *save_curwin = NULL; \
tabpage_T *save_curtab = NULL; \
switch_to_win_for_buf(b, &save_curwin, &save_curtab, &save_curbuf); \
code; \
restore_win_for_buf(save_curwin, save_curtab, save_curbuf); \
} while (0)
#endif // NVIM_BUFFER_H