Skip to content

Commit

Permalink
add autoformat/indent
Browse files Browse the repository at this point in the history
  • Loading branch information
Paolo Prete committed Jun 15, 2024
1 parent b5094ac commit 491dd44
Show file tree
Hide file tree
Showing 31 changed files with 473 additions and 52 deletions.
5 changes: 5 additions & 0 deletions NEWS.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
--------------
Version 1.30
--------------
* add autoformat/indent

--------------
Version 1.25
--------------
Expand Down
12 changes: 11 additions & 1 deletion documentation/miscellaneous.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,16 @@ You can add them by setting "compile-additional-opts" configuration parameter:
click on "TOOLS--->Set configuration parameter", then insert "compile-additional-opts" as parameter, then insert all the additional options you need in the same entry. For example: "-I /my/include/directory -l WARN".
Don't forget to restart the SpontiniServer after the parameter is set.

### AUTOFORMAT/INDENT

It is possible to format or simply auto-indent LilyPond code through various options:

* By selecting a code snippet and clicking on "TOOLS--->Format/Indent selection"
* By enabling/disabling the auto-format/auto-indent option from the "TOOLS" menu ("TOOLS--->Enable/Disable autoformat", "TOOLS--->Enable/Disable autoindent"). Each time the file being edited is saved, the code will automatically be auto-formatted/auto-indented.
* By configuring the editor to have auto-format/auto-indent enabled/disabled by default: click on "TOOLS->Set configuration parameter", and enter "default-autoformat" (or "default-autoindent") as the parameter to configure and "on" or "off" as the value. Remember to restart SpontiniServer.
* If auto-format is enabled by default, it can be avoided for one or more sections of code that are between two lines starting with "% set autoformat off" and "% set autoformat on" (or "% set autoindent off" and "% set autoindent on"). If a line containing "% set autoformat off" (or "% set autoindent off") is placed at the beginning of the file, then auto-formatting/auto-indenting will be avoided for the entire file without needing to use the closing line ("% set autoformat on" or "% set autoindent on").
Be careful to insert a space between "%" and "set" for each of these lines.

### AXES

Once a score is loaded and rendered, four draggable axes, useful for graphically aligning objects, can be activated by selecting "TOOLS--->Toggle axes"
Expand Down Expand Up @@ -105,7 +115,7 @@ Then the svg drop-down menu is displayed after a double click on the left mouse

You can check the LilyPond compiling output in two ways:

* On the Javascript console of your browser (open "Web developer" ---> "Web console" on Firefox and "More tools" ---> "Developer tools" on Chrome/Chromium).
* On the Javascript console of your browser (open "Web developer" ---> "Web console" on Firefox and "More tools" ---> "Developer tools" on Chrome/Chromium)
* On the Spontini-Server's window or on the Spontini-Server's output (if the server is launched with "nogui" option)

### PAN-ZOOM
Expand Down
1 change: 1 addition & 0 deletions examples/easy-cross-staff-example-2.ly
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
% set autoformat off
%
% Created (24/01/2020) by Paolo-Prete.
% This file is part of Spontini-Editor project.
Expand Down
1 change: 1 addition & 0 deletions examples/easy-cross-staff-example-3.ly
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
% set autoformat off
%
% Created (24/01/2020) by Paolo-Prete.
% This file is part of Spontini-Editor project.
Expand Down
1 change: 1 addition & 0 deletions examples/easy-cross-staff-example-4.ly
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
% set autoformat off
%
% Created (24/06/2020) by Paolo-Prete.
% This file is part of Spontini-Editor project.
Expand Down
1 change: 1 addition & 0 deletions examples/easy-cross-staff-example-5.ly
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
% set autoformat off
%
% Created (24/06/2020) by Paolo-Prete.
% This file is part of Spontini-Editor project.
Expand Down
1 change: 1 addition & 0 deletions examples/easy-cross-staff-example-6.ly
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
% set autoformat off
%
% Created (24/06/2020) by Paolo-Prete.
% This file is part of Spontini-Editor project.
Expand Down
1 change: 1 addition & 0 deletions examples/easy-cross-staff-example-7.ly
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
% set autoformat off
%
% Created (24/06/2020) by Paolo-Prete.
% This file is part of Spontini-Editor project.
Expand Down
1 change: 1 addition & 0 deletions examples/easy-cross-staff-example-8.ly
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
% set autoformat off
%
% Created (24/01/2020) by Paolo-Prete.
% This file is part of Spontini-Editor project.
Expand Down
1 change: 1 addition & 0 deletions examples/easy-cross-staff-example-9.ly
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
% set autoformat off
%
% Created (24/01/2020) by Paolo-Prete.
% This file is part of Spontini-Editor project.
Expand Down
3 changes: 2 additions & 1 deletion examples/filter-example-1.ly
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
% set autoformat off
%
% Created (16/10/2021) by Paolo-Prete.
% This file is part of Spontini-Editor project.
Expand Down Expand Up @@ -72,4 +73,4 @@ r1 r \break
c'4 d' e' f' \break
\SECTIONEND

}
}
1 change: 1 addition & 0 deletions examples/filter-example-2.ly
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
% set autoformat off
%
% Created (28/11//2021) by Paolo-Prete.
% This file is part of Spontini-Editor project.
Expand Down
1 change: 1 addition & 0 deletions examples/filter-example-3.ly
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
% set autoformat off
%
% Created (16/10/2021) by Paolo-Prete.
% This file is part of Spontini-Editor project.
Expand Down
1 change: 1 addition & 0 deletions examples/oso-padding-example-1.ly
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
% set autoformat off
%
% Created (24/01/2020) by Paolo-Prete.
% This file is part of Spontini-Editor project.
Expand Down
1 change: 1 addition & 0 deletions examples/oso-padding-example-2.ly
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
% set autoformat off
%
% Created (24/01/2020) by Paolo-Prete.
% This file is part of Spontini-Editor project.
Expand Down
1 change: 1 addition & 0 deletions examples/padding-on-brackets-example.ly
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
% set autoformat off
%
% Created (24/01/2020) by Paolo-Prete.
% This file is part of Spontini-Editor project.
Expand Down
2 changes: 1 addition & 1 deletion examples/pdf-manipulate-example.ly
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
% pdf-manipulate-example-postengraving.py, inside the example's directory, will be executed
% and it will add a string + a vector image + a raster image on the generated PDF page.
%
% NOTE: don't engrave this example in SVG MODE, otherwise the python script will fail.
% NOTE: don't engrave this example in SVG MODE, otherwise the python script will fail.
%
% In general, given a FILENAME.ly file, You can associate to it two scripts that will be executed
% before and after the creation of the PDF: their filename must be in the form FILENAME-beforepdf.suffix
Expand Down
4 changes: 2 additions & 2 deletions examples/python-to-spontini-example.ly
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ scriptOutput = argv[1]
expr = ' '
for i in range (8):
expr +='a '
scriptOutput[0] = expr
%}
Expand All @@ -44,5 +44,5 @@ scriptOutput[0] = expr
\version "2.19.84"

{
%{__BLOCK__1%} a a a a a a a a %{%}
%{__BLOCK__1%} a a a a a a a a %{%}
}
1 change: 1 addition & 0 deletions examples/set-properties-example-1.ly
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
% set autoformat off
%
% Created (24/01/2020) by Paolo-Prete.
% This file is part of Spontini-Editor project.
Expand Down
1 change: 1 addition & 0 deletions examples/set-properties-example-2.ly
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
% set autoformat off
%
% Created (24/01/2020) by Paolo-Prete.
% This file is part of Spontini-Editor project.
Expand Down
1 change: 1 addition & 0 deletions examples/spanned-pedals-example.ly
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
% set autoformat off
%
% Created (24/01/2020) by Paolo-Prete.
% This file is part of Spontini-Editor project.
Expand Down
1 change: 1 addition & 0 deletions examples/string-quartet-template-example.ly
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
% set autoformat off
%
% Created (10/10/2020) by Paolo-Prete.
% This file is part of Spontini-Editor project.
Expand Down
112 changes: 112 additions & 0 deletions lib/python/python_ly_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@
import ly.words
import ly.lex.lilypond
import ly.pitch.transpose
import ly.indent
import ly.reformat
import re

def removeUnwantedSpacesInChord(text):

Expand Down Expand Up @@ -72,6 +75,115 @@ def removeChordOnSingleNote(text, lang):

return ret

def formatOrIndentOnlyScore(scoreToFormat, editorCurs, justIndent=False):

def updateEditorCurs(i, editorCurs, editorCursOffs):
editorCursInside = ""
if i == editorCurs[0]:
editorCursInside = [editorCursOffs, editorCurs[1]]
editorCursOffs += 1
return editorCursInside, editorCursOffs

errorLine = -1
if scoreToFormat.strip().startswith("% set autoformat off"):
return [scoreToFormat, editorCurs, errorLine]

lines = scoreToFormat.split('\n')

blocks = []
modScoreLines = []
editorCursOffs = 0
obscureKey = "% __oOo__DONOTTOUCH__oOo__ %"
i = 0
modBlocks = 0

editorCursInside = ""

while i < len(lines):
line = lines[i]
if re.match(r'^\s*\\easyCrossStaff', line) or\
re.match(r'^\s*\% set autoformat off', line) or\
re.match(r'^\s*\% set autoindent off', line):
endReg = r'^\s*#\'\('
if re.match(r'^\s*\% set autoformat off', line):
endReg = r'^\s*\% set autoformat on'
if re.match(r'^\s*\% set autoindent off', line):
endReg = r'^\s*\% set autoindent on'
iTemp = i
endRegFound = False
while i < len(lines):
if re.match(endReg, lines[i]):
endRegFound = True
i += 1
if not endRegFound:
return [scoreToFormat, editorCurs, iTemp + 1]

i = iTemp
blockStart = i
if i == editorCurs[0]:
editorCursInside = [editorCursOffs, editorCurs[1]]
editorCursOffs += 1
# Trovare il blocco che termina con la riga che inizia con "#'("
while i < len(lines) and not re.match(endReg, lines[i]):
editorCursInside, editorCursOffs = updateEditorCurs(i, editorCurs, editorCursOffs)
i += 1
if i < len(lines):
blockEnd = i
editorCursInside, editorCursOffs = updateEditorCurs(i, editorCurs, editorCursOffs)
blocks.append((blockStart, blockEnd, lines[blockStart:blockEnd + 1], obscureKey, editorCursInside))
if editorCursInside:
editorCursInside = ""
modScoreLines.append([obscureKey, False])
modBlocks += 1
elif re.match(r'^\s*\\tabularTwoStavesPoly', line):
blockStart = i
editorCursInside, editorCursOffs = updateEditorCurs(i, editorCurs, editorCursOffs)
i += 1
while i < len(lines) and re.match(r'^\s*\{', lines[i]):
editorCursInside, editorCursOffs = updateEditorCurs(i, editorCurs, editorCursOffs)
i += 1
i -= 1
if i < len(lines):
blockEnd = i
blocks.append((blockStart, blockEnd, lines[blockStart:blockEnd + 1], obscureKey, editorCursInside))
if editorCursInside:
editorCursInside = ""
modScoreLines.append([obscureKey, False])
modBlocks += 1
else:
modScoreLines.append([line, False])
i += 1

modScore = '\n'.join([item[0] for item in modScoreLines])

doc = ly.document.Document(modScore)
curs = ly.document.Cursor(doc)
indenter = ly.indent.Indenter()
if justIndent:
indenter.indent(curs)
else:
ly.reformat.reformat(curs, indenter)

restoredLines = doc.plaintext().split('\n')

blockCtr = 0
for i in range(0, len(restoredLines)):
if restoredLines[i].strip().startswith(obscureKey):

if blocks[blockCtr][4][0:]:
editorCurs = [blocks[blockCtr][4][0:][0] + i, editorCurs[1]]

restoredLines[i] = '\n'.join(blocks[blockCtr][2][0:])
blockCtr += 1

formattedScore = '\n'.join(restoredLines)

# guard
if formattedScore.strip() == "" or obscureKey in formattedScore:
formattedScore = scoreToFormat

return [formattedScore, editorCurs, errorLine]

def orderPitchesInChord(text, lang):

ret = text
Expand Down
26 changes: 25 additions & 1 deletion lib/python/spontini_server_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
from lib.python.python_ly_utils import translatePitches
from lib.python.python_ly_utils import orderPitchesInChord
from lib.python.python_ly_utils import convertPitchesToEnharmonic
from lib.python.python_ly_utils import formatOrIndentOnlyScore
from lib.python.spontini_server_utils import *
except:
# if the above imports fail, we are calling the ASGI server trhough CLI, then the following imports are valid:
Expand All @@ -69,6 +70,7 @@
from python_ly_utils import translatePitches
from python_ly_utils import orderPitchesInChord
from python_ly_utils import convertPitchesToEnharmonic
from python_ly_utils import formatOrIndentOnlyScore
from spontini_server_utils import *

os.chdir(os.path.join(getLibPythonPath(), '..'))
Expand Down Expand Up @@ -96,7 +98,10 @@
DEFAULT_MODE_PARAM = "default-mode"
COMPILE_ADDITIONAL_OPTS_PARAM = "compile-additional-opts"
DEFAULT_MIDI_INPUT_CHANNEL_PARAM = "default-midi-input-channel"
configurableParams = [WORKSPACE_PARAM, VERSION_PARAM, CAN_CONFIG_FROM_NON_LOCALHOST_PARAM, FORK_ACCESS_ONLY_PARAM, DEBUG_PARAM, LILYPOND_EXEC_PARAM, INKSCAPE_EXEC_PARAM, MIDI_ENABLED_PARAM, DEFAULT_MIDI_INPUT_CHANNEL_PARAM, SOUNDFONT_URL_PARAM, DEFAULT_MODE_PARAM, COMPILE_ADDITIONAL_OPTS_PARAM]
DEFAULT_AUTOFORMAT_PARAM = "default-autoformat"
DEFAULT_AUTOINDENT_PARAM = "default-autoindent"
configurableParams = [WORKSPACE_PARAM, VERSION_PARAM, CAN_CONFIG_FROM_NON_LOCALHOST_PARAM, FORK_ACCESS_ONLY_PARAM, DEBUG_PARAM,
LILYPOND_EXEC_PARAM, INKSCAPE_EXEC_PARAM, MIDI_ENABLED_PARAM, DEFAULT_MIDI_INPUT_CHANNEL_PARAM, SOUNDFONT_URL_PARAM, DEFAULT_MODE_PARAM, COMPILE_ADDITIONAL_OPTS_PARAM, DEFAULT_AUTOFORMAT_PARAM, DEFAULT_AUTOINDENT_PARAM]

debug = True
savedConFilename = "saved-config.txt"
Expand Down Expand Up @@ -198,6 +203,8 @@ def readConfigParams():
global INKSCAPE_EXEC_PARAM
global MIDI_ENABLED_PARAM
global DEFAULT_MIDI_INPUT_CHANNEL_PARAM
global DEFAULT_AUTOFORMAT_PARAM
global DEFAULT_AUTOINDENT_PARAM
global DEFAULT_MODE_PARAM
global SOUNDFONT_URL_PARAM
global COMPILE_ADDITIONAL_OPTS_PARAM
Expand All @@ -223,6 +230,8 @@ def readConfigParams():
setConfigParam(INKSCAPE_EXEC_PARAM, "")
setConfigParam(DEFAULT_MODE_PARAM, "svg")
setConfigParam(DEFAULT_MIDI_INPUT_CHANNEL_PARAM, "-1")
setConfigParam(DEFAULT_AUTOFORMAT_PARAM, "off")
setConfigParam(DEFAULT_AUTOINDENT_PARAM, "off")
confFile.close()

with open(savedConFilenameWithPath) as fp:
Expand Down Expand Up @@ -1521,6 +1530,21 @@ def doPostSync(message, request):
pass
return sendCompleteResponse("OK", ret)

if message['cmd'] == 'FORMAT' or message['cmd'] == 'INDENT':
ret = ""
if not checkMsgStructure(message, 2):
return sendMalformedMsgResponse()
try:
indentOnly = False
if message['cmd'] == "INDENT":
indentOnly = True
editorCurs = editorCursorList = [int(x) for x in message['param2'].split(',')]
ret, curs, badLine = formatOrIndentOnlyScore(message['param1'], editorCursorList, indentOnly)
except:
log(clientInfo + traceback.format_exc(), "E")

return sendCompleteResponse("OK", ret + sepTkn + str(curs[0])+","+str(curs[1]) + sepTkn + str(badLine))

if message['cmd'] == 'MERGE_TABLE_CELLS':
ret = ""
status = "OK"
Expand Down
2 changes: 1 addition & 1 deletion lib/version.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
1.25_alfa
1.30_alfa
2 changes: 2 additions & 0 deletions lib/webgui/js/global-stuff.js
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,8 @@ var currMouseCoordsOnSVG = {
}

var isHTML = false
var autoFormat = false
var autoIndent = false

function replaceAll(string, search, replace) {
return string.split(search).join(replace);
Expand Down
18 changes: 18 additions & 0 deletions lib/webgui/js/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,24 @@ else
}

var data = {
cmd: 'GET_CONFIG_PARAM',
param1: "default-autoformat"
}
sendMsgToSpontiniServer(data, function(statusTxt, responseTxt) {
if (responseTxt == "on")
autoFormat = true
})

data = {
cmd: 'GET_CONFIG_PARAM',
param1: "default-autoindent"
}
sendMsgToSpontiniServer(data, function(statusTxt, responseTxt) {
if (responseTxt == "on")
autoIndent = true
})

data = {
cmd: 'GET_CONFIG_PARAM',
param1: "default-mode"
}
Expand Down
Loading

0 comments on commit 491dd44

Please sign in to comment.