在用Org–Babel编写可读的Python时,我需要能够控制缩进级别(显式地使用:indentation-level 3,或者隐式地使用一些巧妙的指示)。
下面是一个演示该问题的示例文件。
#+BEGIN_SRC python :tangle "sample.py"
class Test:
def __init__(self):
self.a = 'a test class'
#+END_SRC
#+BEGIN_SRC python :tangle "sample.py"
def say_hi(self):
print 'Hi from this Test object!'
print 'ID: {}'.format(repr(self))
print 'Data: {}'.format(str(self.__dict__))
#+END_SRC发布于 2014-01-03 19:50:13
将org-src-preserve-indentation设置为t。
发布于 2018-03-31 23:14:47
我不太喜欢Tobias' answer,因为当我设置( org-edit-special ) (C-c ')一个代码块时,我的python模式的buffer会对我大喊大叫(我有几个带有语法检查器的python小模式),因为带有独立方法的块会有意外的缩进(因为使用org-src-preserve-indentation set,我在各个块中的所有方法前面都会有缩进)。因此,我喜欢使用org-mode的:noweb头参数的解决方案:
#+BEGIN_SRC python :tangle "sample.py" :noweb yes
class Test:
<<init_method>> # these are indented
<<more_methods>> # these are indented
#+END_SRC
#+BEGIN_SRC python :noweb-ref init_method
def __init__(self):
self.a = 'a test class'
#+END_SRC
#+BEGIN_SRC python :noweb-ref more_methods
def say_hi(self):
print 'Hi from this Test object!'
print 'ID: {}'.format(repr(self))
print 'Data: {}'.format(str(self.__dict__))
#+END_SRC只要在类定义中缩进Noweb语法引用(双<< >>),其他块("init_method“和"more_methods")就会与缩进有关。因此,最终输出的"sample.py“文件如下所示:
class Test:
def __init__(self):
self.a = 'a test class'
def say_hi(self):
print 'Hi from this Test object!'
print 'ID: {}'.format(repr(self))
print 'Data: {}'.format(str(self.__dict__))好的!
发布于 2016-06-28 22:55:56
我知道这不是理想的解决方案,但作为一种变通办法,您可以在源代码块中插入注释(特定于您的编程语言),并在该注释后进行所需的缩进。这也将在退出edit-buffer时保留缩进。
#+BEGIN_SRC python :tangle "sample.py"
class Test:
def __init__(self):
self.a = 'a test class'
#+END_SRC
#+BEGIN_SRC python :tangle "sample.py"
# This is my dummy python comment to keep the correct indentation
def say_hi(self):
print 'Hi from this Test object!'
print 'ID: {}'.format(repr(self))
print 'Data: {}'.format(str(self.__dict__))
#+END_SRChttps://stackoverflow.com/questions/20894683
复制相似问题