1414
1515#include <assert.h>
1616#include <stdlib.h>
17+ #include <stdbool.h>
1718#include <string.h>
1819
1920typedef enum {
@@ -23,8 +24,8 @@ typedef enum {
2324
2425typedef struct {
2526 Jim_Scope_Kind kind ;
26- int tail ;
27- int key ;
27+ int tail ; // Not the first element in an array or an object
28+ int key ; // An object key was just placed
2829} Jim_Scope ;
2930
3031typedef struct {
@@ -34,12 +35,9 @@ typedef struct {
3435 Jim_Scope * scopes ;
3536 size_t scopes_count ;
3637 size_t scopes_capacity ;
38+ size_t pp ;
3739} Jim ;
3840
39- // TODO: implement pretty-printing based on how nested the scopes are.
40- // Introduce a separate boolean flag in the Jim struct to enable/disable
41- // the pretty-printing.
42-
4341void jim_begin (Jim * jim );
4442void jim_null (Jim * jim );
4543void jim_bool (Jim * jim , int boolean );
@@ -131,8 +129,20 @@ void jim_begin(Jim *jim)
131129void jim_element_begin (Jim * jim )
132130{
133131 Jim_Scope * scope = jim_current_scope (jim );
134- if (scope && scope -> tail && !scope -> key ) {
135- jim_write_cstr (jim , "," );
132+ if (scope ) {
133+ if (scope -> tail && !scope -> key ) {
134+ jim_write_cstr (jim , "," );
135+ }
136+ if (jim -> pp ) {
137+ if (scope -> key ) {
138+ jim_write_cstr (jim , " " );
139+ } else {
140+ jim_write_cstr (jim , "\n" );
141+ for (size_t i = 0 ; i < jim -> scopes_count * jim -> pp ; ++ i ) {
142+ jim_write_cstr (jim , " " );
143+ }
144+ }
145+ }
136146 }
137147}
138148
@@ -282,6 +292,13 @@ void jim_array_begin(Jim *jim)
282292
283293void jim_array_end (Jim * jim )
284294{
295+ Jim_Scope * scope = jim_current_scope (jim );
296+ if (jim -> pp && scope && scope -> tail ) {
297+ jim_write_cstr (jim , "\n" );
298+ for (size_t i = 0 ; i < (jim -> scopes_count - 1 )* jim -> pp ; ++ i ) {
299+ jim_write_cstr (jim , " " );
300+ }
301+ }
285302 jim_write_cstr (jim , "]" );
286303 jim_scope_pop (jim );
287304 jim_element_end (jim );
@@ -313,6 +330,13 @@ void jim_member_key_sized(Jim *jim, const char *str, size_t size)
313330
314331void jim_object_end (Jim * jim )
315332{
333+ Jim_Scope * scope = jim_current_scope (jim );
334+ if (jim -> pp && scope && scope -> tail ) {
335+ jim_write_cstr (jim , "\n" );
336+ for (size_t i = 0 ; i < (jim -> scopes_count - 1 )* jim -> pp ; ++ i ) {
337+ jim_write_cstr (jim , " " );
338+ }
339+ }
316340 jim_write_cstr (jim , "}" );
317341 jim_scope_pop (jim );
318342 jim_element_end (jim );
0 commit comments