首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用Org-Babel控制缩进

使用Org-Babel控制缩进
EN

Stack Overflow用户
提问于 2014-01-03 08:54:48
回答 3查看 2.7K关注 0票数 6

在用Org–Babel编写可读的Python时,我需要能够控制缩进级别(显式地使用:indentation-level 3,或者隐式地使用一些巧妙的指示)。

下面是一个演示该问题的示例文件。

代码语言:javascript
复制
#+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
EN

回答 3

Stack Overflow用户

发布于 2014-01-03 19:50:13

org-src-preserve-indentation设置为t

票数 9
EN

Stack Overflow用户

发布于 2018-03-31 23:14:47

我不太喜欢Tobias' answer,因为当我设置( org-edit-special ) (C-c ')一个代码块时,我的python模式的buffer会对我大喊大叫(我有几个带有语法检查器的python小模式),因为带有独立方法的块会有意外的缩进(因为使用org-src-preserve-indentation set,我在各个块中的所有方法前面都会有缩进)。因此,我喜欢使用org-mode的:noweb头参数的解决方案:

代码语言:javascript
复制
#+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“文件如下所示:

代码语言:javascript
复制
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__))

好的!

票数 3
EN

Stack Overflow用户

发布于 2016-06-28 22:55:56

我知道这不是理想的解决方案,但作为一种变通办法,您可以在源代码块中插入注释(特定于您的编程语言),并在该注释后进行所需的缩进。这也将在退出edit-buffer时保留缩进。

代码语言:javascript
复制
#+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_SRC
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20894683

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档