/*1* Copyright (C) 1984-2025 Mark Nudelman2*3* You may distribute under the terms of either the GNU General Public4* License or the Less License, as specified in the README file.5*6* For more information, see the README file.7*/8910/*11* Routines to perform bracket matching functions.12*/1314#include "less.h"15#include "position.h"1617/*18* Try to match the n-th open bracket19* which appears in the top displayed line (forwdir),20* or the n-th close bracket21* which appears in the bottom displayed line (!forwdir).22* The characters which serve as "open bracket" and23* "close bracket" are given.24*/25public void match_brac(char obrac, char cbrac, int forwdir, int n)26{27int c;28int nest;29POSITION pos;30int (*chget)();3132extern int ch_forw_get(), ch_back_get();3334/*35* Seek to the line containing the open bracket.36* This is either the top or bottom line on the screen,37* depending on the type of bracket.38*/39pos = position((forwdir) ? TOP : BOTTOM);40if (pos == NULL_POSITION || ch_seek(pos))41{42if (forwdir)43error("Nothing in top line", NULL_PARG);44else45error("Nothing in bottom line", NULL_PARG);46return;47}4849/*50* Look thru the line to find the open bracket to match.51*/52do53{54if ((c = ch_forw_get()) == '\n' || c == EOI)55{56if (forwdir)57error("No bracket in top line", NULL_PARG);58else59error("No bracket in bottom line", NULL_PARG);60return;61}62} while (c != obrac || --n > 0);6364/*65* Position the file just "after" the open bracket66* (in the direction in which we will be searching).67* If searching forward, we are already after the bracket.68* If searching backward, skip back over the open bracket.69*/70if (!forwdir)71(void) ch_back_get();7273/*74* Search the file for the matching bracket.75*/76chget = (forwdir) ? ch_forw_get : ch_back_get;77nest = 0;78while ((c = (*chget)()) != EOI)79{80if (c == obrac)81{82if (nest == INT_MAX)83break;84nest++;85}86else if (c == cbrac && --nest < 0)87{88/*89* Found the matching bracket.90* If searching backward, put it on the top line.91* If searching forward, put it on the bottom line.92*/93jump_line_loc(ch_tell(), forwdir ? -1 : 1);94return;95}96}97error("No matching bracket", NULL_PARG);98}99100101