We present an in-depth, high-resolution spectroscopic analysis of the M dwarf K2-18, which hosts a sub-Neptune exoplanet in its habitable zone. We show our technique to accurately normalize the observed spectrum, which is crucial for a proper spectral fitting. We also introduce a new automatic, line-by-line, model-fitting code, AutoSpecFit, which performs an iterative χ 2 minimization process to measure individual elemental abundances of cool dwarfs. We apply this code to the star K2-18, and measure the abundance of 10 elements: C, O, Na, Mg, Al, K, Ca, Sc, Ti, and Fe. We find these abundances to be moderately supersolar, except for Fe, with a slightly subsolar abundance. The accuracy of the inferred abundances is limited by the systematic errors due to uncertain stellar parameters. We also derive the abundance ratios associated with several planet-building elements such as Al/Mg, Ca/Mg, Fe/Mg, and (a solar-like) C/O = 0.568 ± 0.026, which can be used to constrain the chemical composition and the formation location of the exoplanet. On the other hand, the planet K2-18 b has attracted considerable interest, given the JWST measurements of its atmospheric composition. Early JWST studies reveal an unusual chemistry for the atmosphere of this planet, which is unlikely to be driven by formation in a disk of unusual composition. The comparison between the chemical abundances of K2-18 b from future JWST analyses and those of the host star can provide fundamental insights into the formation of this planetary system.