From b3ad05094b4e778d92a351a743cdf15e7bd990b2 Mon Sep 17 00:00:00 2001 From: Bruce Hill Date: Wed, 24 Sep 2025 20:37:08 -0400 Subject: Autoformatting with clang-format --- .clang-format | 274 ++++++++++++++++++++++++++++++++++++ .clangd | 3 + bb.c | 446 +++++++++++++++++++++++++--------------------------------- draw.c | 151 ++++++++------------ draw.h | 14 +- terminal.c | 197 ++++++++++++++++---------- terminal.h | 144 +++++++++++++------ types.h | 8 +- utils.c | 15 +- utils.h | 46 +++--- 10 files changed, 797 insertions(+), 501 deletions(-) create mode 100644 .clang-format create mode 100644 .clangd diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..82e3ce3 --- /dev/null +++ b/.clang-format @@ -0,0 +1,274 @@ +--- +Language: Cpp +AccessModifierOffset: -2 +AlignAfterOpenBracket: Align +AlignArrayOfStructures: None +AlignConsecutiveAssignments: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: true +AlignConsecutiveBitFields: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveDeclarations: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveMacros: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveShortCaseStatements: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCaseArrows: false + AlignCaseColons: false +AlignConsecutiveTableGenBreakingDAGArgColons: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveTableGenCondOperatorColons: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignConsecutiveTableGenDefinitionColons: + Enabled: false + AcrossEmptyLines: false + AcrossComments: false + AlignCompound: false + AlignFunctionPointers: false + PadOperators: false +AlignEscapedNewlines: Right +AlignOperands: Align +AlignTrailingComments: + Kind: Never + OverEmptyLines: 0 +AllowAllArgumentsOnNextLine: true +AllowAllParametersOfDeclarationOnNextLine: true +AllowBreakBeforeNoexceptSpecifier: Never +AllowShortBlocksOnASingleLine: Never +AllowShortCaseExpressionOnASingleLine: true +AllowShortCaseLabelsOnASingleLine: true +AllowShortCompoundRequirementOnASingleLine: true +AllowShortEnumsOnASingleLine: true +AllowShortFunctionsOnASingleLine: All +AllowShortIfStatementsOnASingleLine: AllIfsAndElse +AllowShortLambdasOnASingleLine: All +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AttributeMacros: + - __capability +BinPackArguments: true +BinPackParameters: true +BitFieldColonSpacing: Both +BraceWrapping: + AfterCaseLabel: false + AfterClass: false + AfterControlStatement: Never + AfterEnum: false + AfterExternBlock: false + AfterFunction: false + AfterNamespace: false + AfterObjCDeclaration: false + AfterStruct: false + AfterUnion: false + BeforeCatch: false + BeforeElse: false + BeforeLambdaBody: false + BeforeWhile: false + IndentBraces: false + SplitEmptyFunction: true + SplitEmptyRecord: true + SplitEmptyNamespace: true +BreakAdjacentStringLiterals: true +BreakAfterAttributes: Leave +BreakAfterJavaFieldAnnotations: false +BreakAfterReturnType: None +BreakArrays: true +BreakBeforeBinaryOperators: NonAssignment +BreakBeforeConceptDeclarations: Always +BreakBeforeBraces: Attach +BreakBeforeInlineASMColon: OnlyMultiline +BreakBeforeTernaryOperators: true +BreakConstructorInitializers: BeforeColon +BreakFunctionDefinitionParameters: false +BreakInheritanceList: BeforeColon +BreakStringLiterals: true +BreakTemplateDeclarations: MultiLine +ColumnLimit: 120 +CommentPragmas: '^ IWYU pragma:' +CompactNamespaces: false +ConstructorInitializerIndentWidth: 4 +ContinuationIndentWidth: 4 +Cpp11BracedListStyle: true +DerivePointerAlignment: false +DisableFormat: false +EmptyLineAfterAccessModifier: Never +EmptyLineBeforeAccessModifier: LogicalBlock +ExperimentalAutoDetectBinPacking: false +FixNamespaceComments: true +ForEachMacros: + - foreach + - Q_FOREACH + - BOOST_FOREACH +IfMacros: + - KJ_IF_MAYBE +IncludeBlocks: Preserve +IncludeCategories: + - Regex: '^"(llvm|llvm-c|clang|clang-c)/' + Priority: 2 + SortPriority: 0 + CaseSensitive: false + - Regex: '^(<|"(gtest|gmock|isl|json)/)' + Priority: 3 + SortPriority: 0 + CaseSensitive: false + - Regex: '.*' + Priority: 1 + SortPriority: 0 + CaseSensitive: false +IncludeIsMainRegex: '(Test)?$' +IncludeIsMainSourceRegex: '' +IndentAccessModifiers: false +IndentCaseBlocks: false +IndentCaseLabels: false +IndentExternBlock: AfterExternBlock +IndentGotoLabels: true +IndentPPDirectives: None +IndentRequiresClause: true +IndentWidth: 4 +IndentWrappedFunctionNames: false +InsertBraces: false +InsertNewlineAtEOF: false +InsertTrailingCommas: None +IntegerLiteralSeparator: + Binary: 0 + BinaryMinDigits: 0 + Decimal: 0 + DecimalMinDigits: 0 + Hex: 0 + HexMinDigits: 0 +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLines: + AtEndOfFile: false + AtStartOfBlock: true + AtStartOfFile: true +LambdaBodyIndentation: Signature +LineEnding: DeriveLF +MacroBlockBegin: '' +MacroBlockEnd: '' +MainIncludeChar: Quote +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None +ObjCBinPackProtocolList: Auto +ObjCBlockIndentWidth: 2 +ObjCBreakBeforeNestedBlockParam: true +ObjCSpaceAfterProperty: false +ObjCSpaceBeforeProtocolList: true +PackConstructorInitializers: BinPack +PenaltyBreakAssignment: 2 +PenaltyBreakBeforeFirstCallParameter: 19 +PenaltyBreakComment: 300 +PenaltyBreakFirstLessLess: 120 +PenaltyBreakOpenParenthesis: 0 +PenaltyBreakScopeResolution: 500 +PenaltyBreakString: 1000 +PenaltyBreakTemplateDeclaration: 10 +PenaltyExcessCharacter: 1000000 +PenaltyIndentedWhitespace: 0 +PenaltyReturnTypeOnItsOwnLine: 60 +PointerAlignment: Right +PPIndentWidth: -1 +QualifierAlignment: Leave +ReferenceAlignment: Pointer +ReflowComments: true +RemoveBracesLLVM: false +RemoveParentheses: Leave +RemoveSemicolon: false +RequiresClausePosition: OwnLine +RequiresExpressionIndentation: OuterScope +SeparateDefinitionBlocks: Leave +ShortNamespaceLines: 1 +SkipMacroDefinitionBody: false +SortIncludes: CaseSensitive +SortJavaStaticImport: Before +SortUsingDeclarations: LexicographicNumeric +SpaceAfterCStyleCast: false +SpaceAfterLogicalNot: false +SpaceAfterTemplateKeyword: true +SpaceAroundPointerQualifiers: Default +SpaceBeforeAssignmentOperators: true +SpaceBeforeCaseColon: false +SpaceBeforeCpp11BracedList: false +SpaceBeforeCtorInitializerColon: true +SpaceBeforeInheritanceColon: true +SpaceBeforeJsonColon: false +SpaceBeforeParens: ControlStatements +SpaceBeforeParensOptions: + AfterControlStatements: true + AfterForeachMacros: true + AfterFunctionDefinitionName: false + AfterFunctionDeclarationName: false + AfterIfMacros: true + AfterOverloadedOperator: false + AfterPlacementOperator: true + AfterRequiresInClause: false + AfterRequiresInExpression: false + BeforeNonEmptyParentheses: false +SpaceBeforeRangeBasedForLoopColon: true +SpaceBeforeSquareBrackets: false +SpaceInEmptyBlock: false +SpacesBeforeTrailingComments: 1 +SpacesInAngles: Never +SpacesInContainerLiterals: true +SpacesInLineCommentPrefix: + Minimum: 1 + Maximum: -1 +SpacesInParens: Never +SpacesInParensOptions: + ExceptDoubleParentheses: false + InCStyleCasts: false + InConditionalStatements: false + InEmptyParentheses: false + Other: false +SpacesInSquareBrackets: false +Standard: Latest +StatementAttributeLikeMacros: + - Q_EMIT +StatementMacros: + - Q_UNUSED + - QT_REQUIRE_VERSION +TableGenBreakInsideDAGArg: DontBreak +TabWidth: 4 +UseTab: Never +VerilogBreakBetweenInstancePorts: true +WhitespaceSensitiveMacros: + - BOOST_PP_STRINGIZE + - CF_SWIFT_NAME + - NS_SWIFT_NAME + - PP_STRINGIZE + - STRINGIZE +... + diff --git a/.clangd b/.clangd new file mode 100644 index 0000000..6cf2eba --- /dev/null +++ b/.clangd @@ -0,0 +1,3 @@ +CompileFlags: + Add: [-xc] +Checks: '-bugprone-suspicious-missing-comma' diff --git a/bb.c b/bb.c index 7502db1..709dfaa 100644 --- a/bb.c +++ b/bb.c @@ -34,10 +34,15 @@ #define BB_VERSION "0.31.0" #define MAX_BINDINGS 1024 -#define SCROLLOFF MIN(5, (winsize.ws_row-4)/2) +#define SCROLLOFF MIN(5, (winsize.ws_row - 4) / 2) #define ONSCREEN (winsize.ws_row - 3) -#define LOG(...) do { FILE *f = fopen("log.txt", "a"); fprintf(f, __VA_ARGS__); fclose(f); } while (0) +#define LOG(...) \ + do { \ + FILE *f = fopen("log.txt", "a"); \ + fprintf(f, __VA_ARGS__); \ + fclose(f); \ + } while (0) // Functions void bb_browse(bb_t *bb, int argc, char *argv[]); @@ -45,14 +50,13 @@ static void check_cmdfile(bb_t *bb); static void cleanup(void); static void cleanup_and_raise(int sig); static int compare_files(const void *v1, const void *v2); -__attribute__((format(printf,2,3))) -void flash_warn(bb_t *bb, const char *fmt, ...); +__attribute__((format(printf, 2, 3))) void flash_warn(bb_t *bb, const char *fmt, ...); static void handle_next_key_binding(bb_t *bb); static void init_term(void); static int is_simple_bbcmd(const char *s); -static entry_t* load_entry(bb_t *bb, const char *path); +static entry_t *load_entry(bb_t *bb, const char *path); static int matches_cmd(const char *str, const char *cmd); -static char* normalize_path(const char *path, char *pbuf); +static char *normalize_path(const char *path, char *pbuf); static int populate_files(bb_t *bb, const char *path); static void print_bindings(FILE *f); static void run_bbcmd(bb_t *bb, const char *cmd); @@ -73,12 +77,14 @@ static void update_term_size(int sig); static int wait_for_process(proc_t **proc); // Constants -static const char *T_ENTER_BBMODE = T_OFF(T_SHOW_CURSOR ";" T_WRAP) T_ON(T_ALT_SCREEN ";" T_MOUSE_XY ";" T_MOUSE_CELL ";" T_MOUSE_SGR); -static const char *T_LEAVE_BBMODE = T_OFF(T_MOUSE_XY ";" T_MOUSE_CELL ";" T_MOUSE_SGR ";" T_ALT_SCREEN) T_ON(T_SHOW_CURSOR ";" T_WRAP); +static const char *T_ENTER_BBMODE = + T_OFF(T_SHOW_CURSOR ";" T_WRAP) T_ON(T_ALT_SCREEN ";" T_MOUSE_XY ";" T_MOUSE_CELL ";" T_MOUSE_SGR); +static const char *T_LEAVE_BBMODE = + T_OFF(T_MOUSE_XY ";" T_MOUSE_CELL ";" T_MOUSE_SGR ";" T_ALT_SCREEN) T_ON(T_SHOW_CURSOR ";" T_WRAP); static const char *T_LEAVE_BBMODE_PARTIAL = T_OFF(T_MOUSE_XY ";" T_MOUSE_CELL ";" T_MOUSE_SGR) T_ON(T_WRAP); -static const char *description_str = BB_NAME" - an itty bitty console TUI file browser\n"; -static const char *usage_str = "Usage: "BB_NAME" (-h/--help | -v/--version | -s | -d | -0 | +command)* [[--] directory]\n"; - +static const char *description_str = BB_NAME " - an itty bitty console TUI file browser\n"; +static const char *usage_str = + "Usage: " BB_NAME " (-h/--help | -v/--version | -s | -d | -0 | +command)* [[--] directory]\n"; // Variables used within this file to track global state static binding_t bindings[MAX_BINDINGS]; @@ -95,21 +101,20 @@ typedef struct { char filename[PATH_MAX]; } outbuf_t; outbuf_t output_buffers[] = { - {.name="stdout", .orig_fd=STDOUT_FILENO, .dup_fd=-1, .tmp_fd=-1}, - {.name="stderr", .orig_fd=STDERR_FILENO, .dup_fd=-1, .tmp_fd=-1}, + {.name = "stdout", .orig_fd = STDOUT_FILENO, .dup_fd = -1, .tmp_fd = -1}, + {.name = "stderr", .orig_fd = STDERR_FILENO, .dup_fd = -1, .tmp_fd = -1}, }; // // Use bb to browse the filesystem. // -void bb_browse(bb_t *bb, int argc, char *argv[]) -{ +void bb_browse(bb_t *bb, int argc, char *argv[]) { const char *initial_path; - if (argc >= 3 && streq(argv[argc-2], "--")) { - initial_path = argv[argc-1]; + if (argc >= 3 && streq(argv[argc - 2], "--")) { + initial_path = argv[argc - 1]; argc -= 2; - } else if (argc >= 2 && argv[argc-1][0] != '-' && argv[argc-1][0] != '+') { - initial_path = argv[argc-1]; + } else if (argc >= 2 && argv[argc - 1][0] != '-' && argv[argc - 1][0] != '+') { + initial_path = argv[argc - 1]; argc -= 1; } else { initial_path = "."; @@ -124,7 +129,7 @@ void bb_browse(bb_t *bb, int argc, char *argv[]) if (!S_ISDIR(path_stat.st_mode)) { char *slash = strrchr(full_initial_path, '/'); *slash = '\0'; - goto_file = slash+1; + goto_file = slash + 1; } if (populate_files(bb, full_initial_path)) @@ -137,8 +142,7 @@ void bb_browse(bb_t *bb, int argc, char *argv[]) system("bbstartup"); FILE *cmdfile = fopen(cmdfilename, "a"); - if (goto_file) - fprintf(cmdfile, "%cgoto:%s", '\0', goto_file); + if (goto_file) fprintf(cmdfile, "%cgoto:%s", '\0', goto_file); for (int i = 0; i < argc; i++) { if (argv[i][0] == '+') { char *cmd = argv[i] + 1; @@ -166,8 +170,7 @@ void bb_browse(bb_t *bb, int argc, char *argv[]) // Check the bb command file and run any and all commands that have been // written to it. // -static void check_cmdfile(bb_t *bb) -{ +static void check_cmdfile(bb_t *bb) { FILE *cmdfile = fopen(cmdfilename, "r"); if (!cmdfile) return; char *cmd = NULL; @@ -177,7 +180,7 @@ static void check_cmdfile(bb_t *bb) run_bbcmd(bb, cmd); if (bb->should_quit) break; } - delete(&cmd); + delete (&cmd); fclose(cmdfile); unlink(cmdfilename); } @@ -185,8 +188,7 @@ static void check_cmdfile(bb_t *bb) // // Clean up the terminal before going to the default signal handling behavior. // -static void cleanup_and_raise(int sig) -{ +static void cleanup_and_raise(int sig) { cleanup(); int childsig = (sig == SIGTSTP || sig == SIGSTOP) ? sig : SIGHUP; if (current_bb) { @@ -205,8 +207,7 @@ static void cleanup_and_raise(int sig) // // Reset the screen, delete the cmdfile, and print the stdout/stderr buffers // -static void cleanup(void) -{ +static void cleanup(void) { if (cmdfilename[0]) { unlink(cmdfilename); cmdfilename[0] = '\0'; @@ -216,13 +217,13 @@ static void cleanup(void) fflush(tty_out); tcsetattr(fileno(tty_out), TCSANOW, &orig_termios); } - FOREACH(outbuf_t*, ob, output_buffers) { + FOREACH(outbuf_t *, ob, output_buffers) { if (ob->tmp_fd == -1) continue; fflush(ob->orig_fd == STDOUT_FILENO ? stdout : stderr); dup2(ob->dup_fd, ob->orig_fd); lseek(ob->tmp_fd, 0, SEEK_SET); char buf[256]; - for (ssize_t len; (len = read(ob->tmp_fd, buf, LEN(buf))) > 0; ) + for (ssize_t len; (len = read(ob->tmp_fd, buf, LEN(buf))) > 0;) write(ob->orig_fd, buf, len); close(ob->tmp_fd); ob->tmp_fd = ob->dup_fd = -1; @@ -234,12 +235,14 @@ static void cleanup(void) // Used for sorting, this function compares files according to the sorting-related options, // like bb->sort // -static int compare_files(const void *v1, const void *v2) -{ -#define COMPARE(a, b) if ((a) != (b)) { return sign*((a) < (b) ? 1 : -1); } +static int compare_files(const void *v1, const void *v2) { +#define COMPARE(a, b) \ + if ((a) != (b)) { \ + return sign * ((a) < (b) ? 1 : -1); \ + } #define COMPARE_TIME(t1, t2) COMPARE((t1).tv_sec, (t2).tv_sec) COMPARE((t1).tv_nsec, (t2).tv_nsec) bb_t *bb = current_bb; - const entry_t *e1 = *((const entry_t**)v1), *e2 = *((const entry_t**)v2); + const entry_t *e1 = *((const entry_t **)v1), *e2 = *((const entry_t **)v2); int sign = 1; if (!bb->interleave_dirs) { @@ -262,8 +265,8 @@ static int compare_files(const void *v1, const void *v2) while (*n1 && *n2) { char c1 = tolower(*n1), c2 = tolower(*n2); if ('0' <= c1 && c1 <= '9' && '0' <= c2 && c2 <= '9') { - long i1 = strtol(n1, (char**)&n1, 10); - long i2 = strtol(n2, (char**)&n2, 10); + long i1 = strtol(n1, (char **)&n1, 10); + long i2 = strtol(n2, (char **)&n2, 10); // Shorter numbers always go before longer. In practice, I assume // filenames padded to the same number of digits should be grouped // together, instead of @@ -273,7 +276,8 @@ static int compare_files(const void *v1, const void *v2) COMPARE(i2, i1); } else { COMPARE(c2, c1); - ++n1; ++n2; + ++n1; + ++n2; } } COMPARE(tolower(*n2), tolower(*n1)); @@ -297,7 +301,7 @@ static int compare_files(const void *v1, const void *v2) // Flash a warning message at the bottom of the screen. // void flash_warn(bb_t *bb, const char *fmt, ...) { - move_cursor(tty_out, 0, winsize.ws_row-1); + move_cursor(tty_out, 0, winsize.ws_row - 1); fputs("\033[41;33;1m", tty_out); va_list args; va_start(args, fmt); @@ -305,7 +309,8 @@ void flash_warn(bb_t *bb, const char *fmt, ...) { va_end(args); fputs(" Press any key to continue...\033[0m ", tty_out); fflush(tty_out); - while (bgetkey(tty_in, NULL, NULL) == -1) usleep(100); + while (bgetkey(tty_in, NULL, NULL) == -1) + usleep(100); bb->dirty = 1; } @@ -313,8 +318,7 @@ void flash_warn(bb_t *bb, const char *fmt, ...) { // Wait until the user has pressed a key with an associated key binding and run // that binding. // -static void handle_next_key_binding(bb_t *bb) -{ +static void handle_next_key_binding(bb_t *bb) { int key, mouse_x, mouse_y; binding_t *binding; do { @@ -322,13 +326,12 @@ static void handle_next_key_binding(bb_t *bb) struct winsize prevsize = winsize; key = bgetkey(tty_in, &mouse_x, &mouse_y); // Window size changed while waiting for keypress: - if (winsize.ws_row != prevsize.ws_row || winsize.ws_col != prevsize.ws_col) - bb->dirty = 1; + if (winsize.ws_row != prevsize.ws_row || winsize.ws_col != prevsize.ws_col) bb->dirty = 1; if (key == -1 && bb->dirty) return; } while (key == -1); binding = NULL; - FOREACH(binding_t*, b, bindings) { + FOREACH(binding_t *, b, bindings) { if (key == b->key) { binding = b; break; @@ -338,7 +341,7 @@ static void handle_next_key_binding(bb_t *bb) char bbmousecol[2] = {0, 0}, bbclicked[PATH_MAX]; if (mouse_x != -1 && mouse_y != -1) { - int *colwidths = get_column_widths(bb->columns, winsize.ws_col-1); + int *colwidths = get_column_widths(bb->columns, winsize.ws_col - 1); // Get bb column: for (int col = 0, x = 0; bb->columns[col]; col++, x++) { x += colwidths[col]; @@ -349,8 +352,7 @@ static void handle_next_key_binding(bb_t *bb) } if (mouse_y == 1) { strcpy(bbclicked, ""); - } else if (2 <= mouse_y && mouse_y <= winsize.ws_row - 2 - && bb->scroll + (mouse_y - 2) <= bb->nfiles - 1) { + } else if (2 <= mouse_y && mouse_y <= winsize.ws_row - 2 && bb->scroll + (mouse_y - 2) <= bb->nfiles - 1) { strcpy(bbclicked, bb->files[bb->scroll + (mouse_y - 2)]->fullname); } else { bbclicked[0] = '\0'; @@ -362,15 +364,14 @@ static void handle_next_key_binding(bb_t *bb) if (is_simple_bbcmd(binding->script)) { run_bbcmd(bb, binding->script); } else { - move_cursor(tty_out, 0, winsize.ws_row-1); + move_cursor(tty_out, 0, winsize.ws_row - 1); fputs("\033[K", tty_out); restore_term(&orig_termios); run_script(bb, binding->script); for (entry_t *next, *e = bb->selected; e; e = next) { next = e->selected.next; struct stat buf; - if (stat(e->fullname, &buf) != 0) - set_selected(bb, e, 0); + if (stat(e->fullname, &buf) != 0) set_selected(bb, e, 0); } init_term(); set_title(bb); @@ -386,8 +387,7 @@ static void handle_next_key_binding(bb_t *bb) // Initialize the terminal files for /dev/tty and set up some desired // attributes like passing Ctrl-c as a key instead of interrupting // -static void init_term(void) -{ +static void init_term(void) { nonnegative(tcsetattr(fileno(tty_out), TCSANOW, &bb_termios)); update_term_size(0); // Initiate mouse tracking and disable text wrapping: @@ -399,16 +399,14 @@ static void init_term(void) // Return whether or not 's' is a simple bb command that doesn't need // a full shell instance (e.g. "bbcmd cd:.." or "bbcmd move:+1"). // -static int is_simple_bbcmd(const char *s) -{ +static int is_simple_bbcmd(const char *s) { if (!s) return 0; - while (*s == ' ') ++s; - if (strncmp(s, "bbcmd ", strlen("bbcmd ")) != 0) - return 0; + while (*s == ' ') + ++s; + if (strncmp(s, "bbcmd ", strlen("bbcmd ")) != 0) return 0; const char *special = ";$&<>|\n*?\\\"'"; for (const char *p = special; *p; ++p) { - if (strchr(s, *p)) - return 0; + if (strchr(s, *p)) return 0; } return 1; } @@ -419,22 +417,19 @@ static int is_simple_bbcmd(const char *s) // Warning: this does not deduplicate entries, and it's best if there aren't // duplicate entries hanging around. // -static entry_t* load_entry(bb_t *bb, const char *path) -{ +static entry_t *load_entry(bb_t *bb, const char *path) { struct stat linkedstat, filestat; if (!path || !path[0]) return NULL; if (lstat(path, &filestat) == -1) return NULL; char pbuf[PATH_MAX]; - if (path[0] == '/') - strcpy(pbuf, path); - else - sprintf(pbuf, "%s%s", bb->path, path); - if (pbuf[strlen(pbuf)-1] == '/' && pbuf[1]) - pbuf[strlen(pbuf)-1] = '\0'; + if (path[0] == '/') strcpy(pbuf, path); + else sprintf(pbuf, "%s%s", bb->path, path); + if (pbuf[strlen(pbuf) - 1] == '/' && pbuf[1]) pbuf[strlen(pbuf) - 1] = '\0'; // Check for pre-existing: for (entry_t *e = bb->hash[(int)filestat.st_ino & HASH_MASK]; e; e = e->hash.next) { - if (e->info.st_ino == filestat.st_ino && e->info.st_dev == filestat.st_dev + if (e->info.st_ino == filestat.st_ino + && e->info.st_dev == filestat.st_dev // Need to check filename in case of hard links && streq(pbuf, e->fullname)) return e; @@ -445,25 +440,22 @@ static entry_t* load_entry(bb_t *bb, const char *path) if (S_ISLNK(filestat.st_mode)) { linkpathlen = nonnegative(readlink(pbuf, linkbuf, sizeof(linkbuf)), "Couldn't read link: '%s'", pbuf); linkbuf[linkpathlen] = '\0'; - while (linkpathlen > 0 && linkbuf[linkpathlen-1] == '/') linkbuf[--linkpathlen] = '\0'; + while (linkpathlen > 0 && linkbuf[linkpathlen - 1] == '/') + linkbuf[--linkpathlen] = '\0'; if (stat(pbuf, &linkedstat) == -1) memset(&linkedstat, 0, sizeof(linkedstat)); } size_t pathlen = strlen(pbuf); size_t entry_size = sizeof(entry_t) + (pathlen + 1) + (size_t)(linkpathlen + 1); entry_t *entry = new_bytes(entry_size); char *end = stpcpy(entry->fullname, pbuf); - if (linkpathlen >= 0) - entry->linkname = strcpy(end + 1, linkbuf); + if (linkpathlen >= 0) entry->linkname = strcpy(end + 1, linkbuf); if (streq(entry->fullname, "/")) { entry->name = entry->fullname; } else { - if (strncmp(entry->fullname, bb->path, strlen(bb->path)) == 0) - entry->name = entry->fullname + strlen(bb->path); - else - entry->name = strrchr(entry->fullname, '/') + 1; // Last path component + if (strncmp(entry->fullname, bb->path, strlen(bb->path)) == 0) entry->name = entry->fullname + strlen(bb->path); + else entry->name = strrchr(entry->fullname, '/') + 1; // Last path component } - if (S_ISLNK(filestat.st_mode)) - entry->linkedmode = linkedstat.st_mode; + if (S_ISLNK(filestat.st_mode)) entry->linkedmode = linkedstat.st_mode; entry->info = filestat; LL_PREPEND(bb->hash[(int)filestat.st_ino & HASH_MASK], entry, hash); entry->index = -1; @@ -475,11 +467,10 @@ static entry_t* load_entry(bb_t *bb, const char *path) // Return whether a string matches a command // e.g. matches_cmd("sel:x", "select:") == 1, matches_cmd("q", "quit") == 1 // -static int matches_cmd(const char *str, const char *cmd) -{ - if ((strchr(cmd, ':') == NULL) != (strchr(str, ':') == NULL)) - return 0; - while (*str == *cmd && *cmd && *cmd != ':') ++str, ++cmd; +static int matches_cmd(const char *str, const char *cmd) { + if ((strchr(cmd, ':') == NULL) != (strchr(str, ':') == NULL)) return 0; + while (*str == *cmd && *cmd && *cmd != ':') + ++str, ++cmd; return *str == '\0' || *str == ':'; } @@ -487,8 +478,7 @@ static int matches_cmd(const char *str, const char *cmd) // Prepend `./` to relative paths, replace "~" with $HOME. // The normalized path is stored in `normalized`. // -static char *normalize_path(const char *path, char *normalized) -{ +static char *normalize_path(const char *path, char *normalized) { char pbuf[PATH_MAX] = {0}; if (path[0] == '~' && (path[1] == '\0' || path[1] == '/')) { char *home; @@ -510,25 +500,19 @@ static char *normalize_path(const char *path, char *normalized) // Remove all the files currently stored in bb->files and if `bb->path` is // non-NULL, update `bb` with a listing of the files in `path` // -static int populate_files(bb_t *bb, const char *path) -{ +static int populate_files(bb_t *bb, const char *path) { int clear_future_history = 0; if (path == NULL) ; else if (streq(path, "-")) { - if (!bb->history) - return -1; - if (bb->history->prev) - bb->history = bb->history->prev; + if (!bb->history) return -1; + if (bb->history->prev) bb->history = bb->history->prev; path = bb->history->path; } else if (streq(path, "+")) { - if (!bb->history) - return -1; - if (bb->history->next) - bb->history = bb->history->next; + if (!bb->history) return -1; + if (bb->history->next) bb->history = bb->history->next; path = bb->history->path; - } else - clear_future_history = 1; + } else clear_future_history = 1; int samedir = path && streq(bb->path, path); int old_scroll = bb->scroll; @@ -539,10 +523,8 @@ static int populate_files(bb_t *bb, const char *path) char pbuf[PATH_MAX] = {0}, prev[PATH_MAX] = {0}; strcpy(prev, bb->path); if (path != NULL) { - if (!normalize_path(path, pbuf)) - flash_warn(bb, "Could not normalize path: \"%s\"", path); - if (pbuf[strlen(pbuf)-1] != '/') - strcat(pbuf, "/"); + if (!normalize_path(path, pbuf)) flash_warn(bb, "Could not normalize path: \"%s\"", path); + if (pbuf[strlen(pbuf) - 1] != '/') strcat(pbuf, "/"); if (chdir(pbuf)) { flash_warn(bb, "Could not cd to: \"%s\"", pbuf); return -1; @@ -552,10 +534,10 @@ static int populate_files(bb_t *bb, const char *path) if (clear_future_history && !samedir) { for (bb_history_t *next, *h = bb->history ? bb->history->next : NULL; h; h = next) { next = h->next; - delete(&h); + delete (&h); } - bb_history_t *h = new(bb_history_t); + bb_history_t *h = new (bb_history_t); strcpy(h->path, pbuf); h->prev = bb->history; if (bb->history) bb->history->next = h; @@ -573,21 +555,20 @@ static int populate_files(bb_t *bb, const char *path) try_free_entry(bb->files[i]); bb->files[i] = NULL; } - delete(&bb->files); + delete (&bb->files); } bb->nfiles = 0; bb->cursor = 0; bb->scroll = 0; - if (!bb->path[0]) - return 0; + if (!bb->path[0]) return 0; size_t space = 0; glob_t globbuf = {0}; char *pat, *tmpglob = check_strdup(bb->globpats); while ((pat = strsep(&tmpglob, " ")) != NULL) - glob(pat, GLOB_NOSORT|GLOB_APPEND, NULL, &globbuf); - delete(&tmpglob); + glob(pat, GLOB_NOSORT | GLOB_APPEND, NULL, &globbuf); + delete (&tmpglob); for (size_t i = 0; i < globbuf.gl_pathc; i++) { // Don't normalize path so we can get "." and ".." entry_t *entry = load_entry(bb, globbuf.gl_pathv[i]); @@ -596,8 +577,7 @@ static int populate_files(bb_t *bb, const char *path) continue; } entry->index = bb->nfiles; - if ((size_t)bb->nfiles + 1 > space) - bb->files = grow(bb->files, space += 100); + if ((size_t)bb->nfiles + 1 > space) bb->files = grow(bb->files, space += 100); bb->files[bb->nfiles++] = entry; } globfree(&globbuf); @@ -609,7 +589,7 @@ static int populate_files(bb_t *bb, const char *path) seed ^= ((bb->files[i]->info.st_ino ^ 89869747UL) ^ (bb->files[i]->info.st_ino << 16)) * 3644798167UL; srand((unsigned int)seed); for (int i = 0; i < bb->nfiles; i++) { - int j = rand() % (i+1); // This introduces some RNG bias, but it's not important here + int j = rand() % (i + 1); // This introduces some RNG bias, but it's not important here bb->files[i]->shufflepos = bb->files[j]->shufflepos; bb->files[j]->shufflepos = i; } @@ -617,7 +597,7 @@ static int populate_files(bb_t *bb, const char *path) sort_files(bb); if (samedir) { set_scroll(bb, old_scroll); - bb->cursor = old_cursor > bb->nfiles-1 ? bb->nfiles-1 : old_cursor; + bb->cursor = old_cursor > bb->nfiles - 1 ? bb->nfiles - 1 : old_cursor; if (old_selected[0]) { entry_t *e = load_entry(bb, old_selected); if (e) set_cursor(bb, e->index); @@ -635,25 +615,25 @@ static int populate_files(bb_t *bb, const char *path) // // Print the current key bindings // -static void print_bindings(FILE *f) -{ - FOREACH(binding_t*, b, bindings) { +static void print_bindings(FILE *f) { + FOREACH(binding_t *, b, bindings) { if (!b->description) break; if (b->key == -1) { const char *label = b->description; - fprintf(f, "\n\033[33;1;4m\033[%dG%s\033[0m\n", (winsize.ws_col-(int)strlen(label))/2, label); + fprintf(f, "\n\033[33;1;4m\033[%dG%s\033[0m\n", (winsize.ws_col - (int)strlen(label)) / 2, label); continue; } char buf[1000]; char *p = buf; - for (binding_t *next = b; next < &bindings[LEN(bindings)] && next->script && streq(b->description, next->description); next++) { + for (binding_t *next = b; + next < &bindings[LEN(bindings)] && next->script && streq(b->description, next->description); next++) { if (next > b) p = stpcpy(p, ", "); p = bkeyname(next->key, p); b = next; } *p = '\0'; - fprintf(f, "\033[1m\033[%dG%s\033[0m", winsize.ws_col/2 - 1 - (int)strlen(buf), buf); - fprintf(f, "\033[1m\033[%dG\033[34m%s\033[0m", winsize.ws_col/2 + 1, b->description); + fprintf(f, "\033[1m\033[%dG%s\033[0m", winsize.ws_col / 2 - 1 - (int)strlen(buf), buf); + fprintf(f, "\033[1m\033[%dG\033[34m%s\033[0m", winsize.ws_col / 2 + 1, b->description); fprintf(f, "\033[0m\n"); } fprintf(f, "\n"); @@ -663,19 +643,22 @@ static void print_bindings(FILE *f) // Run a bb internal command (e.g. "+refresh") and return an indicator of what // needs to happen next. // -static void run_bbcmd(bb_t *bb, const char *cmd) -{ - while (*cmd == ' ' || *cmd == '\n') ++cmd; +static void run_bbcmd(bb_t *bb, const char *cmd) { + while (*cmd == ' ' || *cmd == '\n') + ++cmd; if (strncmp(cmd, "bbcmd ", strlen("bbcmd ")) == 0) cmd = &cmd[strlen("bbcmd ")]; const char *value = strchr(cmd, ':'); if (value) ++value; if (matches_cmd(cmd, "bind:")) { // +bind::